refactor chat capability & RAG pipeline(llamaindex)

This commit is contained in:
Bingxi Zhao (Frank)
2026-05-13 21:36:07 +08:00
parent c7688fd268
commit 1596807242
111 changed files with 6107 additions and 2564 deletions
File diff suppressed because it is too large Load Diff
@@ -1,176 +1,115 @@
# AgenticChatPipeline prompts (English)
# These prompts are consumed by deeptutor.agents.chat.agentic_pipeline.AgenticChatPipeline,
# which powers the chat capability's 4-stage pipeline: thinking → acting → observing → responding.
# Independent from chat_agent.yaml in this folder (used by the legacy single-turn ChatAgent).
# Single-loop chat pipeline: one merged system prompt; the LLM decides whether
# to call tools natively, and the pipeline iterates until the model returns a
# final response. Consumed by deeptutor.agents.chat.agentic_pipeline.
# ---------------------------------------------------------------------------
# Stage labels (used in trace metadata, surfaced in UI)
# ---------------------------------------------------------------------------
labels:
reasoning: "Reasoning"
observation: "Observation"
final_response: "Final response"
tool_call: "Tool call"
retrieve: "Retrieve"
final_response: "Final response"
answer_now: "Answer now"
# ---------------------------------------------------------------------------
# Thinking stage
# Single chat system prompt (capability-agnostic chat persona)
# ---------------------------------------------------------------------------
thinking:
system: |-
You are DeepTutor's internal thinking module (NOT user-facing). Your output is a brief internal analysis memo consumed by the downstream acting / responding stages. It will never be shown to the user directly.
# This template names NO specific tools and contains NO tool-specific usage
# guidance. All "when to use which tool, with what arguments" copy is
# injected dynamically through {tool_list} from per-tool YAML hints, and only
# appears when the corresponding tool is actually enabled.
#
# Placeholders filled by the pipeline at call time:
# {kb_note} — knowledge-base attachment notice (may be empty)
# {tool_list} — enabled-tool catalog with short_description / when_to_use /
# input_format (may be empty)
#
# memory_context, skills_context, and source_manifest are appended as
# separate top-level system sections by the pipeline — they are NOT
# substituted into this template — so prompt caching stays effective when
# only the manifest tail changes between turns.
system: |-
You are DeepTutor, an interactive tutor that helps the user think through their question. Reply directly to the user — never describe your internal pipeline, stages, or planning out loud.
Output format (use natural paragraphs, no headings needed):
- User goal: summarize what the user actually wants in 1-2 sentences.
- Known vs. missing: what information is already available in the conversation, and what is still missing.
- Tool plan: which tools could fill the gaps, with brief rationale. Write "No tools needed" if information is sufficient.
- Answer key points: 2-4 key points the final answer should cover.
# Output protocol (mandatory — every reply must comply)
Critical constraints:
- Output ONLY the internal analysis memo. Do NOT produce a user-facing answer, conclusion, or worked solution.
- You may mention which tools seem useful, but do not call tools in this stage.
- Keep it concise — no more than 200 words.
Every reply MUST begin with exactly one of these three labels on the very first line, all-caps, wrapped with two backticks on each side:
{kb_note}
Enabled tools:
{tool_list}
user: |-
[User request]
{user_message}
``FINISH`` → This reply IS the final user-facing answer. No tools. Whatever follows the label is the answer.
``TOOL`` → This reply will use tools. After the label you may write one short sentence of intent, then emit native tool_calls.
``THINK`` → This reply is intermediate reasoning — **no tools, and not the final answer either**. You're writing your thoughts to push toward the next iteration. The next iteration will continue from here and eventually finish with ``FINISH``.
Produce the internal analysis memo (do NOT answer the user or draw conclusions).
Pick one per reply based on current context:
- Simple question / enough info → ``FINISH``.
- Need external info / computation / retrieval → ``TOOL``.
- Complex problem that benefits from multi-step reasoning before acting → ``THINK`` (loop a few rounds; always close with ``FINISH``).
Examples:
``FINISH``
9876543 + 234567 = 10,111,110.
``TOOL``
Let me run Python.
[native tool_call: code_execution(...)]
``THINK``
This problem has three steps: X, then Y, then Z. Next iteration I'll tackle X first…
Never:
- Put anything before the label (no leading prose, quotes, or stray characters).
- Use single backticks, brackets, or any alternate wrapper.
- Emit more than one label in a single reply.
# Per-turn reasoning
1. Read the user's request. If you already have enough information for a reliable answer, answer directly with ``FINISH``. When unsure, lean on enabled tools rather than guessing — never fabricate precise values, external facts, or citations.
2. In a ``TOOL`` reply, multiple complementary tools may run in the same iteration. In a ``THINK`` reply, write your reasoning only — no tools. In a ``FINISH`` reply, deliver the answer and stop.
3. Once enough material is gathered, close with ``FINISH``.
Hard rules for tool calls:
- Tool names, parameter names, source ids, and KB names must be copied verbatim from the "Enabled tools" and "Knowledge bases / sources" blocks below. Never invent.
- Arguments must be concrete and executable; once you decide to call a tool, fill the arguments meaningfully — empty queries and placeholders are invalid.
When to skip tools (use ``FINISH``):
- Pure conversation: greetings, chitchat, emotional response.
- Text rewriting, translation, formatting, Markdown polish.
- Definitional / conceptual questions where you are 100% confident and no precision or recency is required.
{kb_note}
Enabled tools:
{tool_list}
# ---------------------------------------------------------------------------
# Acting stage
# User-message wrapper (kept trivial — most prompts will just be the raw user
# question; attached sources flow in via the separately-appended manifest).
# ---------------------------------------------------------------------------
acting:
system: |-
You are DeepTutor's tool-using agent. Based on the user request and prior thinking, autonomously choose and call only the enabled tools that are truly helpful.
Rules:
1. Review the full enabled tool list before deciding; do not fixate on a single tool too early.
2. For complex questions that need definitions, grounding, outside evidence, papers, calculation, or deeper reasoning, prefer calling multiple complementary tools in parallel so each one covers a distinct information need.
3. Call tools only when they add value, but when they materially improve answer quality you should use them fully.
4. Use concrete, executable arguments grounded in the user's request, and adapt the wording when different tools need different query styles.
5. When calling rag, the query must be a non-empty natural-language retrieval sentence and kb_name must be one of the attached knowledge bases. To consult several knowledge bases, issue one rag call per kb_name in the same turn.
6. If enough evidence already exists, you may skip tool use.
7. Do not produce the final student-facing answer here; this stage is only for tool use.
8. At most {max_parallel_tools} tools may run in parallel in one turn; if several complementary tools are relevant, prefer issuing them together in the same turn.
{kb_note}
Enabled tools:
{tool_list}
Tool usage notes:
{tool_aliases}
user: |-
User request:
{user_message}
[Thinking]
{thinking}
First reason about which information gaps require tools, using the full enabled tool list. If tool use is needed, prefer calling multiple complementary tools in the same turn, up to {max_parallel_tools} total.
user_template: |-
{user_message}
# ---------------------------------------------------------------------------
# Observing stage
# ---------------------------------------------------------------------------
observing:
system: |-
You are DeepTutor's observing stage. Based on the outputs from the thinking and acting stages, prepare an internal synthesis for the final answer stage. Do not answer the student directly.
Prioritize:
1. confirmed facts and conclusions
2. key evidence from tool outputs
3. what the final answer must explain clearly
{rag_hint}
Tool context for this turn:
{tool_list}
# Injected at {rag_hint} when RAG is enabled
rag_hint: |-
If RAG (knowledge base retrieval) was called, assess whether the question is best answered from the retrieved content, from memory / general knowledge, or a mix of both — include this judgment in your synthesis. When tool evidence conflicts with the initial thinking, prefer the evidence.
user_intro: |-
Summarize what was learned from the reasoning and tool execution for the tutor's internal observation note. Focus on confirmed facts, remaining uncertainty, and what the final answer should emphasize. Do not address the student directly.
# ---------------------------------------------------------------------------
# Responding stage (final user-facing answer)
# ---------------------------------------------------------------------------
responding:
system: |-
You are DeepTutor's final response stage. Use the observation and tool evidence to provide a clear, direct, well-structured answer to the user.
Requirements:
1. Output only the final user-facing answer.
2. Do not reveal the internal chain, reasoning, or tool orchestration.
3. Naturally integrate evidence or limits surfaced by the tools.
{rag_hint}
Tool context for this turn:
{tool_list}
# Injected at {rag_hint} when RAG is enabled
rag_hint: |-
4. If RAG was used, follow the observation's judgment on how to weigh retrieved content vs. general knowledge. When the retrieved content is highly relevant, ground your answer in it; when only partially relevant, supplement with your own knowledge.
user: |-
User request:
{user_message}
[Observation]
{observation}
[Tool Trace]
{tool_trace}
Use this material to produce the final answer for the user. Do not mention the internal pipeline, thinking, or observing stages.
# ---------------------------------------------------------------------------
# ReAct fallback (when native tool calling is unavailable)
# ---------------------------------------------------------------------------
react_fallback:
system: |-
You are DeepTutor's ReAct tool agent. Output exactly one JSON object and nothing else.
JSON format:
{{
"action": "<tool_name_or_done>",
"action_input": {{ ... }}
}}
Available actions:
{tool_table}
{kb_note}
Decide from the user request and the full enabled tool list whether tool use is truly needed; if it is, choose the single tool that best closes the most important information gap. If you call rag, action_input must include a non-empty query. If no tool is needed, set action=done.
done_when_to_use: "Use when the available information is sufficient and no more tools are needed."
done_input_format: "Empty string."
# ---------------------------------------------------------------------------
# Answer-now stage (user explicitly requested "answer now", skip further planning)
# Answer-now path (user explicitly clicked "Answer now" mid-stream — used as
# a synthetic user message after the captured partial draft is injected as a
# fake assistant turn; the pipeline calls the LLM once with tools disabled).
# ---------------------------------------------------------------------------
answer_now:
user: |-
Original user request:
{original_user_message}
[Current Draft]
{partial_response}
[Execution Trace]
{trace_summary}
Using only the material already gathered so far, produce the final user-facing answer now. Do not continue planning or call tools, and do not mention internal stages. If something is still uncertain, be explicit about the uncertainty while still giving the most useful answer you can.
Stop using tools and produce the user-facing answer now based on what you have already produced and any tool evidence you've gathered. Do not mention internal stages or planning. If something is still uncertain, say so briefly while giving the most useful answer you can.
# ---------------------------------------------------------------------------
# Progress notices and short copy
# ---------------------------------------------------------------------------
notices:
no_tools_enabled: "No tools are enabled for this turn, so tool execution was skipped."
react_fallback_switch: "The current model does not support native tool calling, so ReAct text orchestration is used."
no_tools_enabled: "No tools are enabled for this turn."
no_tool_call_needed: "No tool call was needed for this turn."
too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one turn, so the list was truncated."
too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one iteration, so the list was truncated."
tool_unknown_error: "An unknown error occurred while executing {tool}."
start_retrieval: "Starting retrieval"
empty_tool_result: "The tool completed without returning text output."
images_stripped: "The current model `{model}` does not support image input, so image attachments were ignored in the thinking stage."
images_stripped: "The current model `{model}` does not support image input, so image attachments were ignored."
max_iterations_reached: "Reached the maximum number of tool iterations for this turn. Producing the best answer I can with what I have."
context_window_guard: "Trimmed older tool results to keep this turn within the model's context window."
# ---------------------------------------------------------------------------
# Empty-state copy
@@ -1,176 +1,97 @@
# AgenticChatPipeline 提示词(中文)
# 这些提示词供 deeptutor.agents.chat.agentic_pipeline.AgenticChatPipeline 使用,
# 对应 chat capability 的四阶段 pipeline:thinking → acting → observing → responding。
# 与同目录下 chat_agent.yaml(旧的 REST 单轮 ChatAgent 用)不冲突。
# 单循环 chat pipeline:单一合并 system prompt;LLM 自行决定是否原生调用工具,
# pipeline 反复迭代直到模型给出最终回答。供 deeptutor.agents.chat.agentic_pipeline 使用。
# ---------------------------------------------------------------------------
# 各阶段标签(用于 trace metadata,前端展示)
# ---------------------------------------------------------------------------
labels:
reasoning: "推理中"
observation: "整理观察"
final_response: "生成回答"
reasoning: "推理"
tool_call: "调用工具"
retrieve: "检索"
final_response: "生成回答"
answer_now: "直接回答"
# ---------------------------------------------------------------------------
# Thinking 阶段
# 单一 chat system prompt(capability-agnostic chat persona)
# ---------------------------------------------------------------------------
thinking:
system: |-
你是 DeepTutor 内部的 thinking 模块(不面向用户)。你的产出是一份简短的内部分析备忘,供后续 acting / responding 阶段消费,绝不会直接展示给用户。
# 不在这里点名任何具体工具,也不写工具适用场景。所有"什么时候用什么工具、
# 怎么用"的信息都通过 {tool_list} 动态注入——只在用户启用了对应工具时才出现。
#
# pipeline 在调用时替换的占位符:
# {kb_note} — 知识库挂载提示(可能为空)
# {tool_list} — 启用工具列表(含 short_description / when_to_use / input_format,可能为空)
#
# memory_context、skills_context、source_manifest 由 pipeline 作为独立的
# system 段落分别附加在本模板之后——不替换进本模板,保留 prompt cache。
system: |-
你是 DeepTutor,一名互动式教练,帮助用户思考问题。直接面向用户作答——不要描述内部 pipeline、阶段或规划过程。
产出格式(用自然段落,不需要标题):
- 用户目标:用一两句话概括用户真正想要什么。
- 已知 vs. 缺失:当前对话和上下文中已经有什么信息,还缺什么。
- 工具规划:哪些工具可能补足缺失信息,简要说明理由。如果信息已足够,写"无需工具"。
- 回答要点:最终回答应覆盖的关键点(列 2-4 条)。
# 输出协议(强制,每一轮回复都必须遵守)
关键约束:
- 你只输出内部分析备忘,不要给出面向用户的回答、结论或解题过程。
- 可以提及预计使用哪些工具,但不要真正调用工具。
- 保持简洁,不超过 200 字。
你的回复**必须以下面三个标签之一作为最开头**,整体顶格写、独占一行、全大写、左右各用两个反引号包裹:
{kb_note}
当前启用工具:
{tool_list}
user: |-
[用户问题]
{user_message}
``FINISH`` → 本轮就是面向用户的最终回答,不调用任何工具,标签后面的全部内容就是答案正文。
``TOOL`` → 本轮要调用工具。标签后可以用一句话简述要做什么,然后通过原生 tool_calls 发起工具调用。
``THINK`` → 本轮是中间推理,**不调用工具,但也不是最终答案**——你只是在边想边写、为下一轮做准备。下一轮你会继续基于这一轮的思路推进,最终会以 ``FINISH`` 收尾。
请输出内部分析备忘(不要回答用户,不要给出结论)。
你自己根据当前问题难度、已有信息和工具情况自主选择三者之一:
- 简单问题、信息已足 → 直接 ``FINISH``。
- 需要外部信息 / 计算 / 检索 → ``TOOL``。
- 问题很复杂、需要把推理拆成多步先想清楚再回答 → ``THINK``(最多迭代几轮,每轮一个 ``THINK``,最后一定要 ``FINISH``)。
绝对不要:
- 在标签前面加任何字符(空格、引号、换行除外)。
- 用单反引号、方括号或别的格式代替双反引号包裹。
- 在同一轮里输出多个标签。
# 每一轮的处理思路
1. 仔细读用户的问题。判断现有信息是否已足以给出可靠回答;不确定时倾向使用已启用工具,不要凭脑补给精确数值或外部事实。
2. ``TOOL`` 轮里可以并行调用多个互补工具;``THINK`` 轮里不调工具,而是深入的思考可以用的思路;``FINISH`` 轮里给最终答案、不再调工具。
3. 一旦素材足够,用 ``FINISH`` 结尾。
调用工具时的硬规则:
- 工具名、参数名、source id、知识库名只能从下方"启用工具"和"知识库 / 来源"中复制,不要凭空发明。
- 参数要具体、可执行;一旦决定调用,参数填实——空查询、占位符是无效的。
什么时候不调工具(用 ``FINISH`` 直接答即可):
- 纯对话:打招呼、闲聊、情绪回应。
- 文本改写、翻译、格式调整、Markdown 美化。
- 问的就是定义、概念且你 100% 确信答案、不存在精度或时效要求。
{kb_note}
启用工具:
{tool_list}
# ---------------------------------------------------------------------------
# Acting 阶段
# user message 包装(保持最小——大多数情况下就是原始用户问题;
# 挂载的来源由独立附加的 manifest 段提供)。
# ---------------------------------------------------------------------------
acting:
system: |-
你是 DeepTutor 的工具调用代理。你的任务是根据用户问题和前序 thinking,从当前已启用的工具中自主选择必要工具并调用。
规则:
1. 先完整审视所有已启用工具,再决定最有帮助的工具组合;不要只盯住单个工具。
2. 对于需要定义、事实核验、外部资料、论文、计算、推理等不同信息面的复杂问题,优先并行调用多个互补工具来覆盖这些信息面。
3. 只调用真正有帮助的工具,但只要工具能显著提升答案质量,就应充分调用。
4. 参数要具体、可执行,优先使用用户原问题中的关键信息,必要时针对不同工具改写成最适合它的查询。
5. 调用 rag 时,query 必须是非空的自然语言检索句,kb_name 必须从已挂载的知识库中选一个。如果要查多个知识库,请在同一轮内对每个 kb_name 各发起一次 rag 调用。
6. 如果信息已经足够,可以不调用工具。
7. 不要输出最终回答给学生;这里只负责工具选择与调用。
8. 单轮最多并行调用 {max_parallel_tools} 个工具;如果有多个互补工具都相关,优先在同一轮一起调用。
{kb_note}
当前可用工具:
{tool_list}
工具使用提示:
{tool_aliases}
user: |-
用户问题:
{user_message}
[Thinking]
{thinking}
请先基于问题与全部可用工具,判断有哪些信息缺口需要工具补足。如果需要,请尽量在同一轮并行调用多个互补工具,但总数不要超过 {max_parallel_tools} 个。
user_template: |-
{user_message}
# ---------------------------------------------------------------------------
# Observing 阶段
# ---------------------------------------------------------------------------
observing:
system: |-
你是 DeepTutor 的 observing 阶段。请基于 thinking 和 acting 阶段的输出,整理一份内部观察总结,供最终回答阶段使用。不要直接回答学生。
优先总结:
1. 已确认的事实与结论
2. 工具结果带来的关键证据
3. 仍需在最终回答中解释清楚的点
{rag_hint}
本轮可用工具背景:
{tool_list}
# 当 RAG 工具被启用时,插入到 system 的 {rag_hint} 占位处
rag_hint: |-
若本轮调用了知识库检索(RAG),请评估用户问题更适合基于检索到的知识库内容回答、基于记忆与通识回答、还是两者结合,并将判断写入总结。当工具返回的证据与初始 thinking 的推断不一致时,以实际证据为准。
user_intro: |-
请整理本轮推理与工具执行得到的关键信息,输出给 tutor 自己看的观察总结。聚焦:已确认事实、仍不确定的点、最终回答应强调什么。不要直接写给学生。
# ---------------------------------------------------------------------------
# Responding 阶段(最终面向用户)
# ---------------------------------------------------------------------------
responding:
system: |-
你是 DeepTutor 的最终回答阶段。请根据 observation 和工具结果,给用户一个清晰、直接、结构良好的正式答复。
要求:
1. 只输出面向用户的正式回答。
2. 不要暴露内部链路、思考过程或工具编排。
3. 若工具结果提供了证据或限制,请自然融入答案。
{rag_hint}
本轮工具背景:
{tool_list}
# 当 RAG 工具被启用时,插入到 system 的 {rag_hint} 占位处
rag_hint: |-
4. 若使用了知识库检索,请根据 observation 的判断,合理权衡检索内容与通识。当检索内容与问题高度相关时,以其为核心依据;部分相关时,可结合自身知识补充。
user: |-
用户问题:
{user_message}
[Observation]
{observation}
[Tool Trace]
{tool_trace}
请基于以上内容,直接给出正式回答。不要暴露内部 pipeline、thinking、observing 等字样。
# ---------------------------------------------------------------------------
# ReAct fallback(不支持原生 tool-calling 时的回退)
# ---------------------------------------------------------------------------
react_fallback:
system: |-
你是 DeepTutor 的 ReAct 工具代理。你必须只输出一个 JSON 对象,不要输出其他文本。
JSON 格式:
{{
"action": "<tool_name_or_done>",
"action_input": {{ ... }}
}}
可选动作如下:
{tool_table}
{kb_note}
先基于用户问题和可用工具列表判断是否真的需要工具;若需要,请选择最能补足关键信息缺口的那个工具。如果调用 rag,action_input 中 query 必须是非空检索句。如果不需要工具,请输出 action=done。
done_when_to_use: "当已有信息足够,且不需要继续调用工具时使用。"
done_input_format: "空字符串。"
# ---------------------------------------------------------------------------
# Answer-now 阶段(用户主动请求"立即回答",跳过后续规划)
# Answer-now 路径(用户主动点击"直接回答"中途打断——用作合成 user 消息,
# 此前已捕获的草稿会作为伪造的 assistant 轮注入;pipeline 关闭工具单轮调用)
# ---------------------------------------------------------------------------
answer_now:
user: |-
用户原始问题:
{original_user_message}
[Current Draft]
{partial_response}
[Execution Trace]
{trace_summary}
请基于当前已经完成的内容,立刻直接生成给用户的最终答复。不要继续规划或调用工具,不要提到内部阶段。如果信息仍有缺口,请诚实说明不确定之处,但仍尽可能先给出当前最有用的回答。
请基于你已经产出的内容和已收集到的工具证据,立刻给出面向用户的最终答复,不要再调工具。不要提到内部阶段或规划。如果仍有不确定,请简短说明,但仍然给出当前最有用的回答。
# ---------------------------------------------------------------------------
# 进度提示与短文案
# ---------------------------------------------------------------------------
notices:
no_tools_enabled: "当前没有启用任何工具,本轮跳过工具调用。"
react_fallback_switch: "当前模型不支持原生工具调用,已切换到 ReAct 文本编排。"
no_tools_enabled: "本轮没有启用任何工具。"
no_tool_call_needed: "本轮不需要调用工具。"
too_many_tool_calls: "模型请求了 {requested} 个工具,本轮最多并行执行 {limit} 个,已截断。"
too_many_tool_calls: "模型请求了 {requested} 个工具,单次迭代最多并行执行 {limit} 个,已截断。"
tool_unknown_error: "执行工具 {tool} 时发生未知错误。"
start_retrieval: "开始检索"
empty_tool_result: "工具执行完成,但没有返回文本内容。"
images_stripped: "当前模型 `{model}` 不支持图像输入,thinking 阶段已忽略本轮图片附件。"
images_stripped: "当前模型 `{model}` 不支持图像输入,本轮图片附件已被忽略。"
max_iterations_reached: "已达到本轮工具迭代上限,将基于当前材料给出最佳回答。"
context_window_guard: "已裁剪较旧的工具结果,以确保本轮在模型上下文窗口内。"
# ---------------------------------------------------------------------------
# 空状态文案
+12 -60
View File
@@ -1,5 +1,4 @@
import asyncio
from dataclasses import asdict
from datetime import datetime
import json
import logging
@@ -11,13 +10,11 @@ from fastapi import APIRouter, HTTPException
from fastapi.responses import Response, StreamingResponse
from pydantic import BaseModel
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
from deeptutor.co_writer.edit_agent import (
EditAgent,
load_history,
print_stats,
save_history,
save_tool_call,
tool_calls_dir,
)
from deeptutor.co_writer.storage import (
@@ -25,7 +22,6 @@ from deeptutor.co_writer.storage import (
CoWriterDocumentSummary,
get_co_writer_storage,
)
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
from deeptutor.services.llm import clean_thinking_tags
@@ -226,34 +222,22 @@ async def _run_react_edit(
language: str,
stream: StreamBus | None = None,
) -> dict[str, object]:
selected_text, instruction, tools, knowledge_bases, prompt = _prepare_react_edit_request(
selected_text, instruction, tools, _knowledge_bases, _prompt = _prepare_react_edit_request(
request, language
)
operation_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
context = UnifiedContext(
session_id="",
user_message=prompt,
conversation_history=[],
enabled_tools=tools,
active_capability="chat",
knowledge_bases=knowledge_bases,
attachments=[],
config_overrides={},
language=language,
metadata={"source": "co_writer_react_edit", "mode": request.mode},
)
pipeline = AgenticChatPipeline(language=language)
# NOTE: this endpoint previously invoked the chat pipeline's private
# stage methods to pre-compute a "thinking" pass and a one-shot tool
# round before the edit agent ran. That coupling broke when the chat
# pipeline collapsed to a single iterative loop. The endpoint kept its
# response shape (``thinking`` and ``tool_traces``) but the values are
# now empty by default — the edit agent does its job directly. If
# pre-edit retrieval becomes needed again, build it inside co_writer
# rather than parasitising the chat pipeline.
active_stream = stream or StreamBus()
enabled_tools = pipeline._normalize_enabled_tools(context.enabled_tools)
thinking_text = await pipeline._stage_thinking(context, enabled_tools, active_stream)
tool_traces = await pipeline._stage_acting(
context=context,
enabled_tools=enabled_tools,
thinking_text=thinking_text,
stream=active_stream,
)
thinking_text = ""
tool_traces: list = []
agent = get_edit_agent()
system_prompt = (
@@ -267,23 +251,6 @@ async def _run_react_edit(
mode=request.mode,
language=language,
)
if thinking_text.strip():
if language.startswith("zh"):
final_prompt += f"\n内部推理摘要(不要暴露给用户):\n{thinking_text.strip()}\n"
else:
final_prompt += (
f"\nInternal reasoning summary (do not reveal):\n{thinking_text.strip()}\n"
)
if tool_traces:
formatted_traces = pipeline._format_tool_traces(tool_traces)
if language.startswith("zh"):
final_prompt += f"\n工具结果(只吸收事实,不要解释过程):\n{formatted_traces}\n"
else:
final_prompt += (
f"\nTool results (absorb the facts only, do not explain the process):\n"
f"{formatted_traces}\n"
)
response_chunks: list[str] = []
if stream is None:
async for _c in agent.stream_llm(
@@ -321,21 +288,6 @@ async def _run_react_edit(
)
tool_call_file = None
if tool_traces:
tool_call_file = save_tool_call(
operation_id,
"react_tools",
{
"type": "react_tools",
"timestamp": datetime.now().isoformat(),
"operation_id": operation_id,
"mode": request.mode,
"tools": tools,
"kb_name": request.kb_name,
"thinking": thinking_text,
"tool_traces": [asdict(trace) for trace in tool_traces],
},
)
history = load_history()
history.append(
@@ -362,7 +314,7 @@ async def _run_react_edit(
"edited_text": edited_text,
"operation_id": operation_id,
"thinking": thinking_text,
"tool_traces": [asdict(trace) for trace in tool_traces],
"tool_traces": tool_traces,
}
if stream is not None:
await active_stream.result(result, source="co_writer_react_edit")
+18 -11
View File
@@ -159,6 +159,18 @@ class SupportedFileTypesInfo(BaseModel):
max_pdf_size_bytes: int
IMAGE_ACCEPT_MIME_TYPES = {
".bmp": "image/bmp",
".gif": "image/gif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".tif": "image/tiff",
".tiff": "image/tiff",
".webp": "image/webp",
}
def _build_unique_task_id(task_type: str, task_key_prefix: str) -> str:
task_manager = TaskIDManager.get_instance()
task_key = f"{task_key_prefix}_{datetime.now().isoformat()}_{uuid4().hex[:8]}"
@@ -426,7 +438,6 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
await initializer.process_documents()
_task_log(task_id, "Document processing complete")
initializer.extract_numbered_items()
_task_log(task_id, "Finalizing initialization")
indexed_count = len(FileTypeRouter.collect_supported_files(initializer.raw_dir))
@@ -558,15 +569,6 @@ async def run_upload_processing_task(
processed_files = await adder.process_new_documents(staged_files)
_task_log(task_id, f"Indexed {len(processed_files)} file(s)")
if processed_files:
progress_tracker.update(
ProgressStage.EXTRACTING_ITEMS,
"Extracting numbered items...",
current=0,
total=len(processed_files),
)
adder.extract_numbered_items_for_new_docs(processed_files, batch_size=20)
adder.update_metadata(len(processed_files) if processed_files else 0)
if folder_id and processed_files:
@@ -651,9 +653,14 @@ async def get_rag_providers():
async def get_supported_file_types():
"""Return the current upload policy so the web client stays in sync."""
extensions = sorted(FileTypeRouter.get_supported_extensions())
accept_items = extensions + [
mime
for extension, mime in sorted(IMAGE_ACCEPT_MIME_TYPES.items())
if extension in FileTypeRouter.IMAGE_EXTENSIONS
]
return SupportedFileTypesInfo(
extensions=extensions,
accept=",".join(extensions),
accept=",".join(dict.fromkeys(accept_items)),
max_file_size_bytes=DocumentValidator.MAX_FILE_SIZE,
max_pdf_size_bytes=DocumentValidator.MAX_PDF_SIZE,
)
+24
View File
@@ -21,6 +21,16 @@ class SessionRenameRequest(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
class BranchSelectionRequest(BaseModel):
"""Edit-branch picker state: `{parent_message_id: chosen_child_id}`.
Stored inside the session preferences blob so it survives reloads
without a dedicated column.
"""
selected_branches: dict[str, int] = Field(default_factory=dict)
class QuizResultItem(BaseModel):
question_id: str = ""
question: str = Field(..., min_length=1)
@@ -114,6 +124,20 @@ async def delete_session(session_id: str):
return {"deleted": True, "session_id": session_id}
@router.put("/{session_id}/branch-selection")
async def update_branch_selection(session_id: str, payload: BranchSelectionRequest):
store = get_sqlite_session_store()
session = await store.get_session(session_id)
if session is None:
raise HTTPException(status_code=404, detail="Session not found")
updated = await store.update_session_preferences(
session_id, {"selected_branches": dict(payload.selected_branches)}
)
if not updated:
raise HTTPException(status_code=404, detail="Session not found")
return {"selected_branches": payload.selected_branches}
@router.delete("/{session_id}/messages/{message_id}")
async def delete_turn_by_message(session_id: str, message_id: int):
store = get_sqlite_session_store()
+7 -2
View File
@@ -47,6 +47,12 @@ class UnifiedContext:
attachments: Images / files sent with the message.
config_overrides: Per-request config tweaks (e.g. temperature).
language: UI / response language ("en" | "zh").
memory_context: Memory snapshot text injected into the system prompt.
skills_context: Skill instructions injected into the system prompt.
source_manifest: Plain-text manifest of attached sources (one line per
source: id/name/type/preview). Empty when no sources are attached.
Consumed by the chat capability to render an "Attached Sources"
section in the system prompt and to enable the ``read_source`` tool.
metadata: Catch-all for capability-specific extras.
"""
@@ -59,8 +65,7 @@ class UnifiedContext:
attachments: list[Attachment] = field(default_factory=list)
config_overrides: dict[str, Any] = field(default_factory=dict)
language: str = "en"
notebook_context: str = ""
history_context: str = ""
memory_context: str = ""
skills_context: str = ""
source_manifest: str = ""
metadata: dict[str, Any] = field(default_factory=dict)
-9
View File
@@ -171,14 +171,6 @@ class DocumentAdder:
with open(self.metadata_file, "w", encoding="utf-8") as f:
json.dump(metadata, f, indent=2, ensure_ascii=False)
def extract_numbered_items_for_new_docs(
self, processed_files: List[Path], batch_size: int = 20
) -> None:
"""Compatibility no-op: numbered-item extraction is deprecated."""
_ = batch_size
if processed_files:
logger.info("Skipping numbered items extraction for incremental add (feature removed)")
def update_metadata(self, added_count: int) -> None:
"""Update metadata after incremental add."""
metadata: dict = {}
@@ -266,7 +258,6 @@ async def add_documents(
)
return 0
processed = await adder.process_new_documents(new_files)
adder.extract_numbered_items_for_new_docs(processed)
adder.update_metadata(len(processed))
manager.update_kb_status(
-12
View File
@@ -223,11 +223,6 @@ class KnowledgeBaseInitializer:
"""No-op retained for compatibility with previous pipelines."""
logger.info("Skipping legacy structure cleanup (llamaindex-only mode)")
def extract_numbered_items(self, batch_size: int = 20) -> None:
"""Compatibility no-op: numbered-item extraction is deprecated."""
_ = batch_size
logger.info("Skipping numbered items extraction (deprecated feature removed)")
async def display_statistics_generic(self) -> None:
"""Display basic statistics."""
raw_files = list(self.raw_dir.glob("*")) if self.raw_dir.exists() else []
@@ -250,7 +245,6 @@ async def initialize_knowledge_base(
base_dir: str = "./data/knowledge_bases",
api_key: Optional[str] = None,
base_url: Optional[str] = None,
skip_extract: bool = False,
) -> bool:
"""Convenience initializer used by CLI wrappers."""
from deeptutor.knowledge.manager import KnowledgeBaseManager
@@ -267,8 +261,6 @@ async def initialize_knowledge_base(
initializer.create_directory_structure()
copied_files = initializer.copy_documents(source_files)
await initializer.process_documents()
if not skip_extract:
initializer.extract_numbered_items()
manager.update_kb_status(
name=kb_name,
status="ready",
@@ -322,8 +314,6 @@ async def main() -> None:
parser.add_argument("--api-key", default=default_api_key)
parser.add_argument("--base-url", default=default_base_url)
parser.add_argument("--skip-processing", action="store_true")
parser.add_argument("--skip-extract", action="store_true")
parser.add_argument("--batch-size", type=int, default=20)
args = parser.parse_args()
@@ -348,8 +338,6 @@ async def main() -> None:
if not args.skip_processing:
await initializer.process_documents()
if not args.skip_processing and not args.skip_extract:
initializer.extract_numbered_items(batch_size=args.batch_size)
if __name__ == "__main__":
-2
View File
@@ -25,7 +25,6 @@ class ProgressStage(Enum):
INITIALIZING = "initializing" # Initializing
PROCESSING_DOCUMENTS = "processing_documents" # Processing documents
PROCESSING_FILE = "processing_file" # Processing single file
EXTRACTING_ITEMS = "extracting_items" # Extracting numbered items
COMPLETED = "completed" # Completed
ERROR = "error" # Error
@@ -93,7 +92,6 @@ class ProgressTracker:
"initializing",
"processing_documents",
"processing_file",
"extracting_items",
]:
status = "processing"
else:
@@ -113,6 +113,8 @@ class ToolRegistry:
hints = self.get_prompt_hints(names, language=language)
if format == "list":
return composer.format_list(hints)
if format == "list_with_usage":
return composer.format_list_with_usage(hints)
if format == "table":
return composer.format_table(
hints,
@@ -31,6 +31,10 @@ _CONTEXT_WINDOW_KEYS = (
"max_sequence_length",
)
_KNOWN_CONTEXT_WINDOWS: tuple[tuple[str, int], ...] = (
("deepseek-v4", 1_000_000),
)
@dataclass(frozen=True)
class ContextWindowDetectionResult:
@@ -61,6 +65,16 @@ def _record_identities(item: Mapping[str, Any]) -> set[str]:
return aliases
def _known_context_window(model: str) -> int | None:
normalized = (model or "").strip().lower()
if not normalized:
return None
for pattern, context_window in _KNOWN_CONTEXT_WINDOWS:
if pattern in normalized:
return context_window
return None
def _recursive_context_window(value: Any) -> int | None:
if isinstance(value, Mapping):
for key in _CONTEXT_WINDOW_KEYS:
@@ -175,6 +189,15 @@ async def detect_context_window(
detected_at=detected_at,
)
known_window = _known_context_window(llm_config.model)
if known_window is not None:
return ContextWindowDetectionResult(
context_window=known_window,
source="known_model",
detail="Matched built-in context-window metadata for this model family.",
detected_at=detected_at,
)
fallback = default_context_window_for_model(
model=llm_config.model,
max_tokens=llm_config.max_tokens,
+30 -16
View File
@@ -29,6 +29,21 @@ def _redact(value: str) -> str:
return f"{value[:4]}...{value[-4:]}"
def _coerce_int(value: Any, default: int, *, minimum: int = 1) -> int:
try:
parsed = int(value)
except (TypeError, ValueError):
return default
return max(minimum, parsed)
def _coerce_float(value: Any, default: float) -> float:
try:
return float(value)
except (TypeError, ValueError):
return default
@dataclass
class TestRun:
id: str
@@ -235,20 +250,25 @@ class ConfigTestRunner:
from .loader import get_agent_params
probe_params = get_agent_params("llm_probe")
max_tokens = max(1, int(probe_params.get("max_tokens", 1024)))
max_tokens = _coerce_int(probe_params.get("max_tokens"), 1024)
temperature = _coerce_float(probe_params.get("temperature"), 0.1)
token_kwargs: dict[str, Any] = get_token_limit_kwargs(
llm_config.model, max_tokens=max_tokens
)
run.emit("info", f"Token options: {json.dumps(token_kwargs)}")
if llm_config.reasoning_effort:
run.emit("info", f"Reasoning effort: {llm_config.reasoning_effort}")
response = await llm_complete(
model=llm_config.model,
prompt="Say 'OK' and identify the model you are using.",
system_prompt="Respond briefly but include your model identity if possible.",
binding=llm_config.binding,
api_key=llm_config.api_key or "sk-no-key-required",
base_url=llm_config.base_url or "",
temperature=0.1,
base_url=llm_config.effective_url or llm_config.base_url or "",
api_version=llm_config.api_version,
temperature=temperature,
extra_headers=llm_config.extra_headers,
reasoning_effort=llm_config.reasoning_effort,
**token_kwargs,
)
snippet = (response or "").strip()
@@ -289,7 +309,7 @@ class ConfigTestRunner:
run.emit("info", "Loading embedding config from the active catalog selection.")
resolved = resolve_embedding_runtime_config(catalog=catalog)
catalog_dim = int(str(model.get("dimension") or 0))
catalog_dim = _coerce_int(model.get("dimension"), 0, minimum=0)
# Force the smoke probe to send NO `dimensions=` parameter so we get
# the model's native max dim back. If we used the configured dim,
# Matryoshka models (OpenAI text-embedding-3-*, Cohere embed-v4,
@@ -403,18 +423,12 @@ class ConfigTestRunner:
# Always persist: the probe runs end-to-end successfully, so the
# detected dim is authoritative. ``_persist_embedding_dimension`` also
# writes the refreshed ``supported_dimensions`` CSV in the same save.
try:
saved_catalog = self._persist_embedding_dimension(catalog, model, detected_dim)
run.emit(
"catalog",
"Saved detected embedding dimension to model_catalog.json.",
catalog=saved_catalog,
)
except Exception as exc: # pragma: no cover - persistence best-effort
run.emit(
"warning",
f"Could not save detected embedding dimension: {exc}",
)
saved_catalog = self._persist_embedding_dimension(catalog, model, detected_dim)
run.emit(
"catalog",
"Saved detected embedding dimension to model_catalog.json.",
catalog=saved_catalog,
)
def _test_search(self, run: TestRun, catalog: dict[str, Any]) -> None:
from deeptutor.services.search import web_search
@@ -11,6 +11,23 @@ from dataclasses import dataclass
from typing import Any, Dict, List, Optional
def looks_like_multimodal_embedding_model(model_name: Optional[str]) -> bool:
"""Best-effort guard for OpenAI-compatible multimodal embedding models."""
if not model_name:
return False
normalized = model_name.lower().replace("_", "-")
return any(
marker in normalized
for marker in (
"qwen3-vl-embedding",
"multimodal-embedding",
"vision-embedding",
"vl-embedding",
"image-embedding",
)
)
@dataclass
class EmbeddingRequest:
"""
@@ -20,26 +20,31 @@ class CohereEmbeddingAdapter(BaseEmbeddingAdapter):
"dimensions": [256, 512, 1024, 1536],
"default": 1024,
"api_version": "v2",
"multimodal": True,
},
"embed-english-v3.0": {
"dimensions": [1024],
"default": 1024,
"api_version": "v1",
"multimodal": False,
},
"embed-multilingual-v3.0": {
"dimensions": [1024],
"default": 1024,
"api_version": "v1",
"multimodal": False,
},
"embed-multilingual-light-v3.0": {
"dimensions": [384],
"default": 384,
"api_version": "v1",
"multimodal": False,
},
"embed-english-light-v3.0": {
"dimensions": [384],
"default": 384,
"api_version": "v1",
"multimodal": False,
},
}
@@ -75,6 +80,10 @@ class CohereEmbeddingAdapter(BaseEmbeddingAdapter):
if not request.truncate:
payload["truncate"] = "NONE"
else:
if request.contents and not bool(model_info.get("multimodal", False)):
raise ValueError(
f"Cohere model '{model_name}' does not support multimodal `contents`."
)
payload = {
"model": model_name,
"embedding_types": ["float"],
@@ -151,11 +160,13 @@ class CohereEmbeddingAdapter(BaseEmbeddingAdapter):
def get_model_info(self) -> Dict[str, Any]:
model_info = self.MODELS_INFO.get(self.model, {})
dimensions_list = model_info.get("dimensions", [])
api_version = self.api_version or model_info.get("api_version") or "v2"
return {
"model": self.model,
"dimensions": model_info.get("default", self.dimensions),
"supports_variable_dimensions": len(dimensions_list) > 1
if isinstance(dimensions_list, list)
else False,
"multimodal": bool(model_info.get("multimodal", False)) and api_version != "v1",
"provider": "cohere",
}
+21 -2
View File
@@ -14,8 +14,16 @@ logger = logging.getLogger(__name__)
class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
MODELS_INFO = {
"jina-embeddings-v3": {"default": 1024, "dimensions": [32, 64, 128, 256, 512, 768, 1024]},
"jina-embeddings-v4": {"default": 1024, "dimensions": [32, 64, 128, 256, 512, 768, 1024]},
"jina-embeddings-v3": {
"default": 1024,
"dimensions": [32, 64, 128, 256, 512, 768, 1024],
"multimodal": False,
},
"jina-embeddings-v4": {
"default": 1024,
"dimensions": [32, 64, 128, 256, 512, 768, 1024],
"multimodal": True,
},
}
INPUT_TYPE_TO_TASK = {
@@ -43,6 +51,10 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
)
return False
def _supports_multimodal(self, model_name: str | None) -> bool:
info = self.MODELS_INFO.get(model_name or "")
return bool(isinstance(info, dict) and info.get("multimodal", False))
async def embed(self, request: EmbeddingRequest) -> EmbeddingResponse:
headers = {
"Authorization": f"Bearer {self.api_key}",
@@ -54,6 +66,11 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
# arrays in `input`; v3 is text-only. Treat `contents` as advisory:
# if set, flatten each {"text"|"image"|"video": value} to its value.
if request.contents:
if not self._supports_multimodal(request.model or self.model):
raise ValueError(
f"Jina model '{request.model or self.model}' does not support "
"multimodal `contents`."
)
input_payload = [
next(iter(item.values())) for item in request.contents if isinstance(item, dict)
]
@@ -123,6 +140,7 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
"dimensions": model_info.get("default", self.dimensions),
"supported_dimensions": model_info.get("dimensions", []),
"supports_variable_dimensions": True,
"multimodal": bool(model_info.get("multimodal", False)),
"provider": "jina",
}
else:
@@ -130,5 +148,6 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
"model": self.model,
"dimensions": model_info or self.dimensions,
"supports_variable_dimensions": False,
"multimodal": False,
"provider": "jina",
}
@@ -140,5 +140,6 @@ class OllamaEmbeddingAdapter(BaseEmbeddingAdapter):
"dimensions": self.MODELS_INFO.get(self.model, self.dimensions),
"local": True,
"supports_variable_dimensions": False,
"multimodal": False,
"provider": "ollama",
}
@@ -13,6 +13,7 @@ from .base import (
EmbeddingProviderError,
EmbeddingRequest,
EmbeddingResponse,
looks_like_multimodal_embedding_model,
)
logger = logging.getLogger(__name__)
@@ -151,15 +152,21 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
headers["Authorization"] = f"Bearer {api_key}"
headers.update({str(k): str(v) for k, v in self.extra_headers.items()})
# Multimodal: pass `contents` through as `input` when set. SiliconFlow's
# Qwen3-VL family accepts mixed [{"text"}, {"image"}] arrays in `input`.
# Pure text-only OpenAI rejects them; that's on the user to pair models
# and providers correctly.
# Multimodal: pass `contents` through as `input` only for model names
# that clearly advertise image/vision embedding support. This prevents
# image indexing from accidentally hitting ordinary text-embedding
# models just because the provider family has some multimodal models.
model = request.model or self.model
if request.contents and not looks_like_multimodal_embedding_model(model):
raise ValueError(
f"OpenAI-compatible embedding model '{model}' does not support "
"multimodal `contents`."
)
input_payload: Any = request.contents if request.contents else request.texts
payload = {
"input": input_payload,
"model": request.model or self.model,
"model": model,
"encoding_format": request.encoding_format or "float",
}
@@ -169,7 +176,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
# supports the param — other providers (e.g. Qwen text-embedding-v4 via
# litellm gateway) return HTTP 400 if we send it.
dim_value = request.dimensions or self.dimensions
if dim_value and self._should_send_dimensions(request.model or self.model):
if dim_value and self._should_send_dimensions(model):
payload["dimensions"] = dim_value
# URL transparency: hit `base_url` verbatim. Azure's `?api-version=...`
@@ -216,7 +223,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
f"Embedding provider returned HTTP {response.status_code}",
status=response.status_code,
body=body_text,
model=request.model or self.model,
model=model,
url=url,
provider="openai_compat",
)
@@ -253,7 +260,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
),
status=response.status_code,
body=body_text,
model=request.model or self.model,
model=model,
url=url,
provider="openai_compat",
) from exc
@@ -291,7 +298,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
expected_dims = request.dimensions or self.dimensions
model_name = data.get("model") if isinstance(data, dict) else None
if not model_name:
model_name = request.model or self.model
model_name = model
if expected_dims and actual_dims != expected_dims:
logger.warning(
@@ -320,6 +327,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
"dimensions": model_info.get("default", self.dimensions),
"supported_dimensions": model_info.get("dimensions", []),
"supports_variable_dimensions": len(model_info.get("dimensions", [])) > 1,
"multimodal": looks_like_multimodal_embedding_model(self.model),
"provider": "openai_compatible",
}
else:
@@ -327,5 +335,6 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
"model": self.model,
"dimensions": model_info or self.dimensions,
"supports_variable_dimensions": False,
"multimodal": looks_like_multimodal_embedding_model(self.model),
"provider": "openai_compatible",
}
@@ -147,5 +147,6 @@ class OpenAISDKEmbeddingAdapter(BaseEmbeddingAdapter):
"model": self.model,
"dimensions": self.dimensions,
"supports_variable_dimensions": False,
"multimodal": False,
"provider": "openai_sdk",
}
+71 -1
View File
@@ -3,7 +3,7 @@
from __future__ import annotations
import logging
from typing import List, Optional
from typing import Any, Dict, List, Optional
from deeptutor.services.config.provider_runtime import (
EMBEDDING_PROVIDERS,
@@ -151,6 +151,76 @@ class EmbeddingClient:
)
return all_embeddings
def supports_multimodal_contents(self) -> bool:
"""Return whether the configured adapter/model accepts multimodal contents."""
try:
info = self.adapter.get_model_info()
if "multimodal" in info:
return bool(info.get("multimodal"))
except Exception:
pass
spec = EMBEDDING_PROVIDERS.get(self.config.binding)
return bool(spec and spec.multimodal)
async def embed_contents(
self,
contents: List[Dict[str, Any]],
*,
progress_callback=None,
) -> List[List[float]]:
"""Embed provider-agnostic multimodal content items.
``contents`` uses the same simple contract as ``EmbeddingRequest``:
``[{"text": "..."}, {"image": "data:...|url"}, {"video": "..."}]``.
"""
if not contents:
return []
if not self.supports_multimodal_contents():
raise ValueError(
"Configured embedding provider/model does not support multimodal contents."
)
import asyncio
spec = EMBEDDING_PROVIDERS.get(self.config.binding)
provider_max = spec.max_batch_items if spec else 256
batch_size = max(1, min(self.config.batch_size, provider_max))
all_embeddings: List[List[float]] = []
total_batches = (len(contents) + batch_size - 1) // batch_size
for i, start in enumerate(range(0, len(contents), batch_size)):
batch = contents[start : start + batch_size]
request = EmbeddingRequest(
texts=[],
model=self.config.model,
dimensions=self.config.dim or None,
contents=batch,
enable_fusion=False,
)
response = await self.adapter.embed(request)
validated = validate_embedding_batch(
response.embeddings,
expected_count=len(batch),
binding=self.config.binding,
model=self.config.model,
batch_index=i + 1,
total_batches=total_batches,
start_index=start,
)
all_embeddings.extend(validated)
if progress_callback:
try:
progress_callback(i + 1, total_batches)
except Exception:
pass
if i < total_batches - 1 and self.config.batch_delay > 0:
await asyncio.sleep(self.config.batch_delay)
return all_embeddings
def embed_sync(self, texts: List[str]) -> List[List[float]]:
import asyncio
+12 -1
View File
@@ -174,9 +174,20 @@ MODEL_OVERRIDES: dict[str, dict[str, object]] = {
"has_thinking_tags": True,
"supports_vision": False,
},
# Qwen text models often share the same provider/gateway as Qwen-VL.
# Keep thinking-tag handling broad, but only mark explicit VL/vision model
# names as image-capable so RAG image indexing can fail closed.
"qwen/qwen2.5-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen/qwen3-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen/qwen2-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen/qwen-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen2.5-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen3-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen2-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen": {
"has_thinking_tags": True,
"supports_vision": True,
"supports_vision": False,
},
"qwq": {
"has_thinking_tags": True,
+5
View File
@@ -12,6 +12,7 @@ from collections.abc import Awaitable, Callable
import logging
from typing import cast
from .capabilities import supports_vision
from .config import LLMConfig, get_llm_config
from .utils import sanitize_url
@@ -139,6 +140,10 @@ class LLMClient:
"""
return self._build_factory_model_func(allow_multimodal=True)
def supports_multimodal_images(self) -> bool:
"""Return whether the configured LLM can accept image input."""
return supports_vision(getattr(self.config, "binding", "openai"), self.config.model)
def _build_factory_model_func(self, allow_multimodal: bool) -> Callable[..., object]:
"""Build adapter callables on top of the unified factory.complete API."""
from . import factory
+95 -3
View File
@@ -27,6 +27,9 @@ from .utils import is_local_llm_server
DEFAULT_MAX_RETRIES = settings.retry.max_retries
DEFAULT_RETRY_DELAY = settings.retry.base_delay
DEFAULT_EXPONENTIAL_BACKOFF = settings.retry.exponential_backoff
DEFAULT_STREAM_COALESCE_CHARS = 64
DEFAULT_STREAM_COALESCE_SECONDS = 0.04
STREAM_CONTROL_TOKENS = {"<think>", "</think>"}
CallKwargs = dict[str, Any]
@@ -276,6 +279,20 @@ def _find_last_user_message(messages: list[dict[str, Any]]) -> dict[str, Any] |
return None
def _coerce_stream_coalesce_chars(value: Any) -> int:
try:
return max(1, int(value))
except (TypeError, ValueError):
return DEFAULT_STREAM_COALESCE_CHARS
def _coerce_stream_coalesce_seconds(value: Any) -> float:
try:
return max(0.0, float(value))
except (TypeError, ValueError):
return DEFAULT_STREAM_COALESCE_SECONDS
def _append_image_placeholder(messages: list[dict[str, Any]]) -> None:
target = _find_last_user_message(messages)
placeholder = "[image omitted]"
@@ -299,6 +316,8 @@ def _apply_inline_image_data(
binding: str,
model: str,
image_data: str | None,
image_mime_type: str = "image/png",
image_filename: str = "image.png",
) -> list[dict[str, Any]]:
if not image_data:
return messages
@@ -306,8 +325,8 @@ def _apply_inline_image_data(
attachment = SimpleNamespace(
type="image",
base64=image_data,
filename="image.png",
mime_type="image/png",
filename=image_filename,
mime_type=image_mime_type,
)
result = prepare_multimodal_messages(messages, [attachment], binding=binding, model=model)
if result.images_stripped:
@@ -325,6 +344,8 @@ def _sanitize_call_kwargs(
for key in (
"messages",
"image_data",
"image_mime_type",
"image_filename",
"api_key",
"base_url",
"api_version",
@@ -356,6 +377,8 @@ async def complete(
caller_extra_headers = kwargs.pop("extra_headers", None)
reasoning_effort = kwargs.pop("reasoning_effort", None)
image_data = kwargs.pop("image_data", None)
image_mime_type = kwargs.pop("image_mime_type", "image/png")
image_filename = kwargs.pop("image_filename", "image.png")
config, provider_spec = _resolve_call_config(
model=model,
@@ -374,6 +397,8 @@ async def complete(
binding=capability_binding,
model=config.model,
image_data=image_data,
image_mime_type=str(image_mime_type or "image/png"),
image_filename=str(image_filename or "image.png"),
)
retry_delays = _build_retry_delays(max_retries, retry_delay, exponential_backoff)
extra_kwargs = _sanitize_call_kwargs(
@@ -415,6 +440,14 @@ async def stream(
caller_extra_headers = kwargs.pop("extra_headers", None)
reasoning_effort = kwargs.pop("reasoning_effort", None)
image_data = kwargs.pop("image_data", None)
image_mime_type = kwargs.pop("image_mime_type", "image/png")
image_filename = kwargs.pop("image_filename", "image.png")
stream_coalesce_chars = _coerce_stream_coalesce_chars(
kwargs.pop("stream_coalesce_chars", DEFAULT_STREAM_COALESCE_CHARS)
)
stream_coalesce_seconds = _coerce_stream_coalesce_seconds(
kwargs.pop("stream_coalesce_seconds", DEFAULT_STREAM_COALESCE_SECONDS)
)
config, provider_spec = _resolve_call_config(
model=model,
@@ -433,6 +466,8 @@ async def stream(
binding=capability_binding,
model=config.model,
image_data=image_data,
image_mime_type=str(image_mime_type or "image/png"),
image_filename=str(image_filename or "image.png"),
)
retry_delays = _build_retry_delays(max_retries, retry_delay, exponential_backoff)
extra_kwargs = _sanitize_call_kwargs(
@@ -503,13 +538,70 @@ async def stream(
task = asyncio.create_task(_runner())
try:
sent_first_text_chunk = False
buffered_chunks: list[str] = []
buffered_chars = 0
def _flush_buffer() -> str:
nonlocal buffered_chars
text = "".join(buffered_chunks)
buffered_chunks.clear()
buffered_chars = 0
return text
async def _queue_get(timeout: float | None = None) -> str | BaseException | None:
if timeout is None:
return await queue.get()
return await asyncio.wait_for(queue.get(), timeout=timeout)
while True:
item = await queue.get()
if item is None:
if buffered_chunks:
yield _flush_buffer()
break
if isinstance(item, BaseException):
if buffered_chunks:
yield _flush_buffer()
raise item
yield item
if item in STREAM_CONTROL_TOKENS or stream_coalesce_seconds <= 0:
if buffered_chunks:
yield _flush_buffer()
yield item
continue
if not sent_first_text_chunk:
sent_first_text_chunk = True
yield item
continue
buffered_chunks.append(item)
buffered_chars += len(item)
deadline = asyncio.get_running_loop().time() + stream_coalesce_seconds
while buffered_chunks and buffered_chars < stream_coalesce_chars:
timeout = deadline - asyncio.get_running_loop().time()
if timeout <= 0:
break
try:
next_item = await _queue_get(timeout)
except asyncio.TimeoutError:
break
if next_item is None:
if buffered_chunks:
yield _flush_buffer()
await task
return
if isinstance(next_item, BaseException):
if buffered_chunks:
yield _flush_buffer()
raise next_item
if next_item in STREAM_CONTROL_TOKENS:
if buffered_chunks:
yield _flush_buffer()
yield next_item
break
buffered_chunks.append(next_item)
buffered_chars += len(next_item)
if buffered_chunks:
yield _flush_buffer()
await task
finally:
if not task.done():
@@ -56,6 +56,9 @@ _THINKING_STYLE_MAP = {
"enable_thinking": lambda enabled: {"enable_thinking": enabled},
"reasoning_split": lambda enabled: {"reasoning_split": enabled},
}
_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (
("deepseek", "deepseek-v4-flash"),
)
def _short_tool_id() -> str:
@@ -105,6 +108,16 @@ def _responses_circuit_key(
return f"{model_name}|{effort}"
def _disable_thinking_by_default(spec: "ProviderSpec | None", model_name: str) -> bool:
if not spec:
return False
normalized = (model_name or "").strip().lower()
return any(
spec.name == provider and pattern in normalized
for provider, pattern in _THINKING_DISABLED_BY_DEFAULT
)
class OpenAICompatProvider(LLMProvider):
"""Unified provider for all OpenAI-compatible APIs.
@@ -323,6 +336,16 @@ class OpenAICompatProvider(LLMProvider):
)
if extra:
kwargs.setdefault("extra_body", {}).update(extra)
elif (
spec
and spec.thinking_style
and _disable_thinking_by_default(spec, model_name)
):
extra = _THINKING_STYLE_MAP.get(spec.thinking_style, lambda _enabled: None)(
False
)
if extra:
kwargs.setdefault("extra_body", {}).update(extra)
if tools:
kwargs["tools"] = tools
+1 -1
View File
@@ -54,7 +54,7 @@ def list_pipelines() -> List[Dict[str, str]]:
{
"id": DEFAULT_PROVIDER,
"name": "LlamaIndex",
"description": "Pure vector retrieval, fastest processing speed.",
"description": "LlamaIndex retrieval with hybrid BM25/vector fusion when available.",
}
]
+8 -2
View File
@@ -34,6 +34,7 @@ class FileClassification:
parser_files: List[str]
text_files: List[str]
image_files: List[str]
unsupported: List[str]
@@ -217,6 +218,7 @@ class FileTypeRouter:
"""Classify a list of files by processing method."""
parser_files = []
text_files = []
image_files = []
unsupported = []
for path in file_paths:
@@ -231,17 +233,21 @@ class FileTypeRouter:
parser_files.append(path)
elif doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN):
text_files.append(path)
elif doc_type == DocumentType.IMAGE:
image_files.append(path)
else:
unsupported.append(path)
logger.debug(
f"Classified {len(file_paths)} files: "
f"{len(parser_files)} parser, {len(text_files)} text, {len(unsupported)} unsupported"
f"{len(parser_files)} parser, {len(text_files)} text, "
f"{len(image_files)} image, {len(unsupported)} unsupported"
)
return FileClassification(
parser_files=parser_files,
text_files=text_files,
image_files=image_files,
unsupported=unsupported,
)
@@ -303,7 +309,7 @@ class FileTypeRouter:
@classmethod
def get_supported_extensions(cls) -> set[str]:
"""Get the set of all supported file extensions."""
return cls.PARSER_EXTENSIONS | cls.TEXT_EXTENSIONS
return cls.PARSER_EXTENSIONS | cls.TEXT_EXTENSIONS | cls.IMAGE_EXTENSIONS
@classmethod
def has_supported_extension(cls, file_path: str | Path) -> bool:
@@ -0,0 +1,60 @@
"""Configuration helpers for DeepTutor's LlamaIndex RAG pipeline."""
from __future__ import annotations
from dataclasses import dataclass
import os
VECTOR_PROFILE = "vector"
HYBRID_PROFILE = "hybrid"
SUPPORTED_RETRIEVAL_PROFILES = {VECTOR_PROFILE, HYBRID_PROFILE}
@dataclass(frozen=True)
class RetrievalConfig:
"""Runtime retrieval knobs for the LlamaIndex pipeline."""
profile: str = HYBRID_PROFILE
vector_top_k_multiplier: int = 2
bm25_top_k_multiplier: int = 2
fusion_num_queries: int = 1
def candidate_top_k(self, top_k: int, multiplier: int) -> int:
"""Return the number of candidates to ask a child retriever for."""
requested = max(1, int(top_k))
return max(requested, requested * max(1, int(multiplier)))
def normalize_retrieval_profile(value: str | None) -> str:
"""Return a supported retrieval profile, defaulting to hybrid."""
profile = (value or "").strip().lower()
if profile in SUPPORTED_RETRIEVAL_PROFILES:
return profile
return HYBRID_PROFILE
def retrieval_config_from_env() -> RetrievalConfig:
"""Build retrieval config from environment variables.
The default is intentionally ``hybrid``. If the optional LlamaIndex BM25
integration is not installed, the retriever builder transparently falls
back to plain vector retrieval.
"""
return RetrievalConfig(
profile=normalize_retrieval_profile(
os.getenv("DEEPTUTOR_RAG_RETRIEVAL_PROFILE")
or os.getenv("RAG_RETRIEVAL_PROFILE")
)
)
__all__ = [
"HYBRID_PROFILE",
"RetrievalConfig",
"SUPPORTED_RETRIEVAL_PROFILES",
"VECTOR_PROFILE",
"normalize_retrieval_profile",
"retrieval_config_from_env",
]
@@ -2,16 +2,33 @@
from __future__ import annotations
import base64
import logging
import mimetypes
from pathlib import Path
from typing import Iterable
from typing import Any, Iterable
from llama_index.core import Document
from llama_index.core.schema import ImageNode
from deeptutor.services.embedding import get_embedding_client
from deeptutor.services.llm.client import get_llm_client
from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.utils.document_extractor import DocumentExtractionError, extract_text_from_path
from deeptutor.utils.document_validator import DocumentValidator
IMAGE_DESCRIPTION_SYSTEM_PROMPT = (
"You describe images for a retrieval-augmented knowledge base. "
"Be factual, concise, and include any visible text, labels, diagrams, "
"tables, logos, or important visual relationships. Do not invent details."
)
IMAGE_DESCRIPTION_PROMPT = (
"Describe this image so that a text-only answer generator can understand "
"and cite it later. Include visible text/OCR if present, the main subject, "
"and any educational or technical meaning. Keep the answer under 180 words."
)
class LlamaIndexDocumentLoader:
"""Convert source files into LlamaIndex ``Document`` objects."""
@@ -19,8 +36,8 @@ class LlamaIndexDocumentLoader:
def __init__(self, logger=None) -> None:
self.logger = logger or logging.getLogger(__name__)
async def load(self, file_paths: Iterable[str]) -> list[Document]:
documents: list[Document] = []
async def load(self, file_paths: Iterable[str]) -> list[Any]:
documents: list[Any] = []
classification = FileTypeRouter.classify_files(list(file_paths))
for file_path_str in classification.parser_files:
@@ -35,6 +52,10 @@ class LlamaIndexDocumentLoader:
text = await FileTypeRouter.read_text_file(str(file_path))
self._append_if_nonempty(documents, file_path, text)
if classification.image_files:
image_nodes = await self._load_image_nodes(classification.image_files)
documents.extend(image_nodes)
for file_path_str in classification.unsupported:
self.logger.warning(f"Skipped unsupported file: {Path(file_path_str).name}")
@@ -52,7 +73,128 @@ class LlamaIndexDocumentLoader:
self.logger.error(f"Failed to extract {file_path.name}: {exc}")
return ""
def _append_if_nonempty(self, documents: list[Document], file_path: Path, text: str) -> None:
async def _load_image_nodes(self, file_paths: list[str]) -> list[ImageNode]:
embedding_client = get_embedding_client()
llm_client = get_llm_client()
unsupported_reasons = []
if not embedding_client.supports_multimodal_contents():
unsupported_reasons.append(
"embedding provider/model does not support multimodal contents "
f"(binding={embedding_client.config.binding}, "
f"model={embedding_client.config.model})"
)
if not llm_client.supports_multimodal_images():
unsupported_reasons.append(
"LLM provider/model does not support multimodal image input "
f"(binding={llm_client.config.binding}, model={llm_client.config.model})"
)
if unsupported_reasons:
reason_text = "; ".join(unsupported_reasons)
for file_path_str in file_paths:
self.logger.warning(
"Skipped image file because image indexing requires both "
f"multimodal embedding and multimodal LLM support; {reason_text}: "
f"{Path(file_path_str).name}"
)
return []
paths = [Path(file_path_str) for file_path_str in file_paths]
embedded_paths: list[Path] = []
descriptions: list[str] = []
contents = []
for path in paths:
try:
image_payload = self._load_image_payload(path)
description = await self._describe_image(
path,
image_payload["base64"],
image_payload["mimetype"],
)
if not description:
self.logger.warning(
"Skipped image file because the configured multimodal LLM "
f"returned no description: {path.name}"
)
continue
contents.append({"image": image_payload["data_uri"]})
embedded_paths.append(path)
descriptions.append(description)
except OSError as exc:
self.logger.error(f"Failed to read image {path.name}: {exc}")
except Exception as exc:
self.logger.error(
"Failed to describe image %s with configured multimodal LLM "
"(binding=%s, model=%s): %s",
path.name,
llm_client.config.binding,
llm_client.config.model,
exc,
)
if not contents:
return []
try:
embeddings = await embedding_client.embed_contents(contents)
except Exception as exc:
self.logger.error(
"Failed to embed image contents with configured multimodal embedding "
"provider/model (binding=%s, model=%s): %s",
embedding_client.config.binding,
embedding_client.config.model,
exc,
)
return []
nodes: list[ImageNode] = []
for path, description, embedding in zip(embedded_paths, descriptions, embeddings):
mimetype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
nodes.append(
ImageNode(
text=f"[Image] {path.name}\n\n{description}",
image_path=str(path),
image_mimetype=mimetype,
metadata={
"file_name": path.name,
"file_path": str(path),
"content_type": "image",
"image_description": description,
},
embedding=embedding,
)
)
self.logger.info(f"Loaded image: {path.name} ({len(embedding)}D vector)")
return nodes
async def _describe_image(
self, file_path: Path, image_base64: str, mimetype: str
) -> str:
llm_client = get_llm_client()
response = await llm_client.complete(
IMAGE_DESCRIPTION_PROMPT,
system_prompt=IMAGE_DESCRIPTION_SYSTEM_PROMPT,
image_data=image_base64,
image_mime_type=mimetype,
image_filename=file_path.name,
)
return response.strip()
def _load_image_payload(self, file_path: Path) -> dict[str, str]:
size = file_path.stat().st_size
if size > DocumentValidator.MAX_FILE_SIZE:
raise OSError(
f"image file too large: {size} bytes; "
f"maximum allowed: {DocumentValidator.MAX_FILE_SIZE} bytes"
)
mimetype = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
encoded = base64.b64encode(file_path.read_bytes()).decode("ascii")
return {
"base64": encoded,
"data_uri": f"data:{mimetype};base64,{encoded}",
"mimetype": mimetype,
}
def _append_if_nonempty(self, documents: list[Any], file_path: Path, text: str) -> None:
if text.strip():
documents.append(
Document(
@@ -0,0 +1,78 @@
"""LlamaIndex ingestion helpers.
This module keeps DeepTutor's indexing path thin by delegating parsing
transformations and embedding to LlamaIndex's official IngestionPipeline.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from llama_index.core import Settings, VectorStoreIndex
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.schema import BaseNode
def build_ingestion_pipeline() -> IngestionPipeline:
"""Create the default DeepTutor ingestion pipeline.
The embedding step uses ``Settings.embed_model``, which is configured by
``embedding_adapter.configure_llamaindex_settings`` to call DeepTutor's
configured embedding service rather than any local model.
"""
return IngestionPipeline(
transformations=[
SentenceSplitter(
chunk_size=Settings.chunk_size,
chunk_overlap=Settings.chunk_overlap,
),
Settings.embed_model,
],
)
def documents_to_nodes(documents: list[Any], *, show_progress: bool = True) -> list[Any]:
"""Convert LlamaIndex documents into embedded nodes.
Pre-embedded nodes, such as ImageNode instances produced by the document
loader, pass through unchanged so they are not re-embedded as text.
"""
text_documents = [document for document in documents if not isinstance(document, BaseNode)]
preembedded_nodes = [document for document in documents if isinstance(document, BaseNode)]
nodes: list[Any] = []
if text_documents:
pipeline = build_ingestion_pipeline()
nodes.extend(pipeline.run(documents=text_documents, show_progress=show_progress))
nodes.extend(preembedded_nodes)
return nodes
def create_index_from_documents(
documents: list[Any], storage_dir: Path, *, show_progress: bool = True
) -> tuple[VectorStoreIndex, int]:
"""Create and persist a VectorStoreIndex from documents."""
nodes = documents_to_nodes(documents, show_progress=show_progress)
index = VectorStoreIndex(nodes=nodes, show_progress=show_progress)
index.storage_context.persist(persist_dir=str(storage_dir))
return index, len(documents)
def insert_documents_into_index(
index: Any, documents: list[Any], *, show_progress: bool = True
) -> int:
"""Transform documents once, then insert nodes into an existing index."""
nodes = documents_to_nodes(documents, show_progress=show_progress)
index.insert_nodes(nodes)
return len(documents)
__all__ = [
"build_ingestion_pipeline",
"create_index_from_documents",
"documents_to_nodes",
"insert_documents_into_index",
]
@@ -0,0 +1,139 @@
"""Retriever composition for the LlamaIndex RAG pipeline."""
from __future__ import annotations
import logging
from pathlib import Path
import shutil
from typing import Any
from llama_index.core.llms.mock import MockLLM
from llama_index.core.retrievers import QueryFusionRetriever
from llama_index.core.retrievers.fusion_retriever import FUSION_MODES
from .config import HYBRID_PROFILE, VECTOR_PROFILE, RetrievalConfig, retrieval_config_from_env
logger = logging.getLogger(__name__)
BM25_PERSIST_DIRNAME = "bm25_retriever"
def _import_bm25_retriever():
try:
from llama_index.retrievers.bm25 import BM25Retriever
return BM25Retriever
except ImportError:
return None
def _bm25_persist_dir(storage_dir: Path) -> Path:
return storage_dir / BM25_PERSIST_DIRNAME
def _set_similarity_top_k(retriever: Any, top_k: int) -> Any:
if hasattr(retriever, "similarity_top_k"):
retriever.similarity_top_k = top_k
return retriever
def build_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> Any | None:
"""Build or load LlamaIndex's official BM25 retriever if available."""
top_k = max(1, int(top_k))
bm25_cls = _import_bm25_retriever()
if bm25_cls is None:
logger.info(
"LlamaIndex BM25 retriever package is not installed; "
"falling back to vector retrieval."
)
return None
persist_dir = _bm25_persist_dir(storage_dir)
if persist_dir.exists():
try:
retriever = bm25_cls.from_persist_dir(str(persist_dir))
return _set_similarity_top_k(retriever, top_k)
except Exception as exc:
logger.warning("Failed to load persisted BM25 retriever from %s: %s", persist_dir, exc)
try:
return bm25_cls.from_defaults(index=index, similarity_top_k=top_k)
except Exception as exc:
logger.warning("Failed to build BM25 retriever; falling back to vector retrieval: %s", exc)
return None
def persist_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> bool:
"""Persist BM25 sidecar index for faster hybrid retrieval.
Missing optional dependencies are non-fatal because hybrid retrieval can
still be enabled in deployments that install ``llama-index-retrievers-bm25``.
"""
top_k = max(1, int(top_k))
bm25_cls = _import_bm25_retriever()
if bm25_cls is None:
return False
persist_dir = _bm25_persist_dir(storage_dir)
if persist_dir.exists():
shutil.rmtree(persist_dir, ignore_errors=True)
try:
retriever = bm25_cls.from_defaults(index=index, similarity_top_k=top_k)
except Exception as exc:
logger.warning("Failed to build BM25 retriever for persistence: %s", exc)
return False
if not hasattr(retriever, "persist"):
return False
persist_dir.mkdir(parents=True, exist_ok=True)
try:
retriever.persist(str(persist_dir))
return True
except Exception as exc:
logger.warning("Failed to persist BM25 retriever to %s: %s", persist_dir, exc)
return False
def build_retriever(
index: Any,
storage_dir: Path,
*,
top_k: int = 5,
config: RetrievalConfig | None = None,
) -> Any:
"""Compose the retrieval stack from official LlamaIndex retrievers."""
top_k = max(1, int(top_k))
retrieval_config = config or retrieval_config_from_env()
if retrieval_config.profile == VECTOR_PROFILE:
return index.as_retriever(similarity_top_k=top_k)
bm25_top_k = retrieval_config.candidate_top_k(top_k, retrieval_config.bm25_top_k_multiplier)
bm25_retriever = build_bm25_retriever(index, storage_dir, top_k=bm25_top_k)
if bm25_retriever is None:
return index.as_retriever(similarity_top_k=top_k)
if retrieval_config.profile == HYBRID_PROFILE:
vector_top_k = retrieval_config.candidate_top_k(
top_k, retrieval_config.vector_top_k_multiplier
)
vector_retriever = index.as_retriever(similarity_top_k=vector_top_k)
return QueryFusionRetriever(
[vector_retriever, bm25_retriever],
llm=MockLLM(),
mode=FUSION_MODES.RECIPROCAL_RANK,
similarity_top_k=top_k,
num_queries=retrieval_config.fusion_num_queries,
use_async=False,
)
return index.as_retriever(similarity_top_k=top_k)
__all__ = [
"BM25_PERSIST_DIRNAME",
"build_bm25_retriever",
"build_retriever",
"persist_bm25_retriever",
]
@@ -8,7 +8,7 @@ from pathlib import Path
import shutil
from typing import Any
from llama_index.core import StorageContext, VectorStoreIndex, load_index_from_storage
from llama_index.core import StorageContext, load_index_from_storage
from deeptutor.services.embedding.validation import validate_embedding_batch
from deeptutor.services.rag.index_versioning import (
@@ -18,6 +18,8 @@ from deeptutor.services.rag.index_versioning import (
resolve_storage_dir_for_write,
)
from . import ingestion, retrievers
@dataclass(frozen=True)
class AddStoragePlan:
@@ -65,19 +67,27 @@ def resolve_add_storage_plan(kb_dir: Path, signature: EmbeddingSignature | None)
def create_index(documents: list[Any], storage_dir: Path, *, show_progress: bool = True) -> int:
index = VectorStoreIndex.from_documents(documents, show_progress=show_progress)
index.storage_context.persist(persist_dir=str(storage_dir))
return len(documents)
index, count = ingestion.create_index_from_documents(
documents, storage_dir, show_progress=show_progress
)
retrievers.persist_bm25_retriever(index, storage_dir, top_k=20)
return count
def insert_documents(existing_storage: Path, storage_dir: Path, documents: list[Any]) -> int:
storage_context = StorageContext.from_defaults(persist_dir=str(existing_storage))
index = load_index_from_storage(storage_context)
_validate_persisted_embeddings(index, existing_storage)
for document in documents:
index.insert(document)
if hasattr(index, "insert_nodes"):
count = ingestion.insert_documents_into_index(index, documents, show_progress=True)
else:
# Some tests use a tiny fake index that only implements insert().
for document in documents:
index.insert(document)
count = len(documents)
index.storage_context.persist(persist_dir=str(storage_dir))
return len(documents)
retrievers.persist_bm25_retriever(index, storage_dir, top_k=20)
return count
def _validate_embedding_dict(embedding_dict: Any, *, label: str) -> None:
@@ -166,7 +176,7 @@ def retrieve_nodes(storage_dir: Path, query: str, *, top_k: int = 5) -> list[Any
storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))
index = load_index_from_storage(storage_context)
_validate_persisted_embeddings(index, storage_dir)
retriever = index.as_retriever(similarity_top_k=top_k)
retriever = retrievers.build_retriever(index, storage_dir, top_k=top_k)
return retriever.retrieve(query)
@@ -310,9 +310,15 @@ class ContextBuilder:
llm_config: LLMConfig,
language: str = "en",
on_event: Callable[[StreamEvent], Awaitable[None]] | None = None,
leaf_message_id: int | None = None,
) -> ContextBuildResult:
session = await self.store.get_session(session_id)
messages = await self.store.get_messages_for_context(session_id)
# When ``leaf_message_id`` is given (edit-branch turn), only the
# ancestor path of that message is included in context — sibling
# branches at any depth are excluded.
messages = await self.store.get_messages_for_context(
session_id, leaf_message_id=leaf_message_id
)
if session is None:
return ContextBuildResult([], "", "", [], 0, self._history_budget(llm_config))
+11 -1
View File
@@ -290,7 +290,12 @@ class PocketBaseSessionStore:
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
metadata: dict[str, Any] | None = None,
parent_message_id: int | None = None,
) -> int:
# ``parent_message_id`` is accepted to match the protocol shape but is
# not yet wired through PocketBase storage — branching only works on
# the SQLite backend today.
_ = parent_message_id
now = time.time()
def _add():
@@ -385,7 +390,12 @@ class PocketBaseSessionStore:
logger.warning(f"get_messages failed: {exc}")
return []
async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]:
async def get_messages_for_context(
self, session_id: str, leaf_message_id: int | None = None
) -> list[dict[str, Any]]:
# leaf_message_id (branch-aware context) is not supported on PocketBase
# yet; fall back to the linear, append-only view.
_ = leaf_message_id
messages = await self.get_messages(session_id)
return [
{"id": m["id"], "role": m["role"], "content": m["content"] or ""}
+4 -1
View File
@@ -54,6 +54,7 @@ class SessionStoreProtocol(Protocol):
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
metadata: dict[str, Any] | None = None,
parent_message_id: int | None = None,
) -> int: ...
async def delete_message(self, message_id: int | str) -> bool: ...
@@ -64,7 +65,9 @@ class SessionStoreProtocol(Protocol):
async def get_messages(self, session_id: str) -> list[dict[str, Any]]: ...
async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]: ...
async def get_messages_for_context(
self, session_id: str, leaf_message_id: int | None = None
) -> list[dict[str, Any]]: ...
async def list_sessions(
self,
@@ -0,0 +1,671 @@
"""Branch-isolated, cumulative source inventory for the chat capability.
The chat pipeline shows the LLM an "Attached Sources" manifest each turn so
it can decide whether to call ``read_source(id)`` for full text. Historically
this manifest only listed sources the user attached in the *current* turn —
so the model forgot anything uploaded in earlier turns unless re-attached.
This module materialises the manifest as a **session-cumulative inventory**:
* Sources attached in the current turn (the "fresh" set) get a full preview
in the manifest, just like before.
* Sources attached in *prior* turns on the active branch's ancestor chain
(the "historical" set) get a compact one-line row: id, name, kind, size,
and the turn ordinal where they first appeared. The LLM can call
``read_source(id)`` to load full text when the question warrants it.
Both sets dedupe by source id; fresh always wins on collision. Branch
isolation is enforced by walking ``parent_message_id`` from the active
branch's leaf, so sibling branches never leak sources into each other.
The output is decoupled from the rest of ``turn_runtime``:
inventory = await build_inventory(store, ..., fresh_*=...)
manifest_text, source_index = render_manifest(inventory)
``source_index`` is the per-turn ``{source_id: full_text}`` map handed to
``ReadSourceTool`` via tool-call kwargs injection.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any, Sequence
from deeptutor.services.session.protocol import SessionStoreProtocol
logger = logging.getLogger(__name__)
# Per-source text-preview caps. Fresh sources get a meaningful preview so
# the model can answer simple "is this the right one?" questions without
# read_source. Historical sources surface only their identity — the model
# pays the read_source cost only when it actually needs them.
MANIFEST_PREVIEW_CHARS_FRESH = 2000
# Image attachments flow through the multimodal block path; never list them.
_IMAGE_MIME_PREFIX = "image/"
@dataclass(frozen=True)
class SourceEntry:
"""One row in the per-turn Attached Sources manifest."""
sid: str
kind: str # "notebook" | "book" | "history" | "question" | "attachment"
name: str
full_text: str
fresh: bool
# 1-indexed ordinal of the user turn this source first appeared in,
# within the active branch's lineage. Fresh sources use the **current**
# turn's ordinal so the manifest can label them consistently.
first_seen_turn: int
@property
def char_count(self) -> int:
return len(self.full_text)
@dataclass
class SourceInventory:
"""Ordered set of ``SourceEntry`` keyed by ``sid``.
``add`` is the only mutator. On duplicate ``sid`` the existing entry is
upgraded to ``fresh=True`` if the incoming entry is fresh — so a source
attached in the current turn always renders with a preview even if it
was also attached in a prior turn.
"""
entries: list[SourceEntry] = field(default_factory=list)
_index: dict[str, int] = field(default_factory=dict, repr=False)
def add(self, entry: SourceEntry) -> None:
if not entry.sid:
return
if not entry.full_text.strip():
return
existing_pos = self._index.get(entry.sid)
if existing_pos is None:
self._index[entry.sid] = len(self.entries)
self.entries.append(entry)
return
existing = self.entries[existing_pos]
# Fresh always wins; otherwise keep the earlier registration.
if entry.fresh and not existing.fresh:
self.entries[existing_pos] = entry
def is_empty(self) -> bool:
return not self.entries
def __contains__(self, sid: str) -> bool:
return sid in self._index
# ---------------------------------------------------------------------------
# Public API: build + render
# ---------------------------------------------------------------------------
async def build_inventory(
store: SessionStoreProtocol,
*,
session_id: str,
leaf_message_id: int | None,
current_turn_ordinal: int,
fresh_attachment_records: Sequence[dict[str, Any]],
fresh_notebook_records: Sequence[dict[str, Any]],
fresh_book_context_text: str,
fresh_book_references: Sequence[dict[str, Any]],
fresh_history_session_ids: Sequence[Any],
fresh_question_entry_ids: Sequence[Any],
) -> SourceInventory:
"""Compose the session-cumulative inventory for one chat turn.
Fresh refs are added first (so they shadow historical entries on the
same sid); historical refs are then collected from the active branch's
ancestor messages. The caller passes already-resolved notebook records
and the already-rendered book context — keeping side-effects (LLM
summarisation, file I/O) under the caller's control rather than buried
inside this module.
"""
inv = SourceInventory()
_add_fresh(
inv,
current_turn_ordinal=current_turn_ordinal,
attachment_records=fresh_attachment_records,
notebook_records=fresh_notebook_records,
book_context_text=fresh_book_context_text,
book_references=fresh_book_references,
)
# History + question entries are async (per-id store fetches), keep them
# in a separate phase so the sync fresh additions don't block.
await _add_fresh_history(
inv,
store=store,
history_session_ids=fresh_history_session_ids,
current_turn_ordinal=current_turn_ordinal,
)
await _add_fresh_questions(
inv,
store=store,
question_entry_ids=fresh_question_entry_ids,
current_turn_ordinal=current_turn_ordinal,
)
await _add_historical(
inv, store=store, session_id=session_id, leaf_message_id=leaf_message_id
)
return inv
def render_manifest(inv: SourceInventory) -> tuple[str, dict[str, str]]:
"""Render the inventory into (manifest_text, source_index).
``manifest_text`` is the human/LLM-readable block injected at the tail
of the chat system prompt. ``source_index`` maps each source id to its
full extracted text and is handed to ``ReadSourceTool`` so the LLM can
read on demand.
"""
if inv.is_empty():
return "", {}
source_index: dict[str, str] = {sid: e.full_text for sid, e in _iter_sid_entries(inv)}
rendered_rows: list[str] = []
for entry in inv.entries:
rendered_rows.append(_render_row(entry))
header = (
"[Attached Sources]\n"
"Sources the user has attached in this conversation. Rows marked "
"`previously attached (turn N)` were uploaded in earlier turns and "
"show only their identity — call `read_source(source_id)` to load "
"their full text when the question warrants it. Rows with a "
"`preview` field were attached **this turn** and the preview is "
"often enough to answer without another tool call. Never invent "
"source ids."
)
return header + "\n\n" + "\n\n".join(rendered_rows), source_index
# ---------------------------------------------------------------------------
# Internals
# ---------------------------------------------------------------------------
def _iter_sid_entries(inv: SourceInventory):
seen: set[str] = set()
for e in inv.entries:
if e.sid in seen:
continue
seen.add(e.sid)
yield e.sid, e
def _clip_preview(text: str, limit: int = MANIFEST_PREVIEW_CHARS_FRESH) -> str:
cleaned = (text or "").strip()
if len(cleaned) <= limit:
return cleaned
return cleaned[:limit].rstrip() + "…"
def _format_size(char_count: int) -> str:
"""Compact size hint for historical rows ('~3 KB', '~120 chars')."""
if char_count >= 1024:
return f"~{round(char_count / 1024)} KB"
return f"~{char_count} chars"
def _render_row(entry: SourceEntry) -> str:
if entry.fresh:
preview = _clip_preview(entry.full_text)
return (
f"- id={entry.sid} type={entry.kind} name={entry.name!r}\n"
f" preview: {preview!r}"
)
return (
f"- id={entry.sid} type={entry.kind} name={entry.name!r}"
f" size={_format_size(entry.char_count)} "
f"source: previously attached (turn {entry.first_seen_turn})"
)
# ----- Fresh source addition (current-turn payload) -----------------------
def _add_fresh(
inv: SourceInventory,
*,
current_turn_ordinal: int,
attachment_records: Sequence[dict[str, Any]],
notebook_records: Sequence[dict[str, Any]],
book_context_text: str,
book_references: Sequence[dict[str, Any]],
) -> None:
"""Add the synchronously-available fresh sources (notebook records,
book pages, attachments)."""
for rec in notebook_records:
rid = str(rec.get("id", "") or "").strip()
full = str(rec.get("output", "") or "")
if not rid or not full.strip():
continue
inv.add(
SourceEntry(
sid=f"nb-{rid}",
kind="notebook",
name=str(rec.get("title") or rec.get("name") or "Untitled record"),
full_text=full,
fresh=True,
first_seen_turn=current_turn_ordinal,
)
)
# Books: split the cumulative ``build_book_context`` output by the
# ``---`` section separator so each book gets its own ``bk-{book_id}``
# sid. The order in ``book_references`` matches the order
# ``build_book_context`` produces sections in, so we can zip them.
book_sections = _split_book_sections(book_context_text)
for ref, section in zip(book_references, book_sections, strict=False):
book_id = str(ref.get("book_id") or "").strip()
if not book_id or not section.strip():
continue
inv.add(
SourceEntry(
sid=f"bk-{book_id}",
kind="book",
name=_extract_book_title(section, fallback=f"Book {book_id}"),
full_text=section,
fresh=True,
first_seen_turn=current_turn_ordinal,
)
)
for record in attachment_records:
if str(record.get("type", "")).lower() == "image":
continue
mime = str(record.get("mime_type", "")).lower()
if mime.startswith(_IMAGE_MIME_PREFIX):
continue
text = str(record.get("extracted_text", "") or "")
att_id = str(record.get("id", "") or "").strip()
if not text.strip() or not att_id:
continue
inv.add(
SourceEntry(
sid=f"at-{att_id}",
kind="attachment",
name=str(record.get("filename") or "Untitled file"),
full_text=text,
fresh=True,
first_seen_turn=current_turn_ordinal,
)
)
async def _add_fresh_history(
inv: SourceInventory,
*,
store: SessionStoreProtocol,
history_session_ids: Sequence[Any],
current_turn_ordinal: int,
) -> None:
for raw in history_session_ids:
hs_id = str(raw or "").strip()
if not hs_id:
continue
text, name = await _load_history_session(store, hs_id)
if not text:
continue
inv.add(
SourceEntry(
sid=f"hs-{hs_id}",
kind="history",
name=name,
full_text=text,
fresh=True,
first_seen_turn=current_turn_ordinal,
)
)
async def _add_fresh_questions(
inv: SourceInventory,
*,
store: SessionStoreProtocol,
question_entry_ids: Sequence[Any],
current_turn_ordinal: int,
) -> None:
get_entry = getattr(store, "get_notebook_entry", None)
if not callable(get_entry):
return
for raw in question_entry_ids:
try:
eid = int(raw)
except (TypeError, ValueError):
continue
block, stem = await _load_question_entry(store, eid)
if not block:
continue
inv.add(
SourceEntry(
sid=f"qb-{eid}",
kind="question",
name=stem,
full_text=block,
fresh=True,
first_seen_turn=current_turn_ordinal,
)
)
# ----- Historical source collection ---------------------------------------
async def _add_historical(
inv: SourceInventory,
*,
store: SessionStoreProtocol,
session_id: str,
leaf_message_id: int | None,
) -> None:
"""Walk the active branch's ancestor user messages and pull in
references they carried. Sources already in ``inv`` (i.e. fresh
duplicates) are skipped — fresh entries always win."""
lineage = await _load_lineage(store, session_id, leaf_message_id)
user_turn_ordinal = 0
for msg in lineage:
if msg.get("role") != "user":
continue
user_turn_ordinal += 1
await _collect_from_user_message(
inv, store=store, msg=msg, turn_ordinal=user_turn_ordinal
)
async def _collect_from_user_message(
inv: SourceInventory,
*,
store: SessionStoreProtocol,
msg: dict[str, Any],
turn_ordinal: int,
) -> None:
"""Drain one prior user message into the inventory as historical
entries. Attachments are pulled from the persisted ``attachments``
JSON; space refs are pulled from ``metadata.request_snapshot`` and
re-resolved through their respective services so the historical
full text always reflects the current state of the referenced object.
"""
# Attachments — extracted_text was persisted at upload time, no
# external lookup needed.
for att in msg.get("attachments") or []:
att_id = str(att.get("id", "") or "").strip()
if not att_id:
continue
sid = f"at-{att_id}"
if sid in inv:
continue
mime = str(att.get("mime_type", "")).lower()
if mime.startswith(_IMAGE_MIME_PREFIX):
continue
text = str(att.get("extracted_text") or "")
if not text.strip():
continue
inv.add(
SourceEntry(
sid=sid,
kind="attachment",
name=str(att.get("filename") or "Untitled file"),
full_text=text,
fresh=False,
first_seen_turn=turn_ordinal,
)
)
snap = (msg.get("metadata") or {}).get("request_snapshot") or {}
if not isinstance(snap, dict):
return
# Notebook records — re-resolve through the notebook service.
notebook_refs = snap.get("notebookReferences") or []
if notebook_refs:
from deeptutor.services.notebook import get_notebook_manager
try:
records = get_notebook_manager().get_records_by_references(list(notebook_refs))
except Exception:
records = []
for rec in records:
rid = str(rec.get("id", "") or "").strip()
if not rid:
continue
sid = f"nb-{rid}"
if sid in inv:
continue
full = str(rec.get("output", "") or "")
if not full.strip():
continue
inv.add(
SourceEntry(
sid=sid,
kind="notebook",
name=str(rec.get("title") or rec.get("name") or "Untitled record"),
full_text=full,
fresh=False,
first_seen_turn=turn_ordinal,
)
)
# Books — one source per book_id (union of page ranges across all
# turns is implicit because we always pull the *current* book reference
# to render).
for ref in snap.get("bookReferences") or []:
book_id = str((ref or {}).get("book_id") or "").strip()
if not book_id:
continue
sid = f"bk-{book_id}"
if sid in inv:
continue
section_text, name = _resolve_book_section(ref)
if not section_text.strip():
continue
inv.add(
SourceEntry(
sid=sid,
kind="book",
name=name,
full_text=section_text,
fresh=False,
first_seen_turn=turn_ordinal,
)
)
# History sessions — async, one store fetch per id.
for raw in snap.get("historyReferences") or []:
hs_id = str(raw or "").strip()
if not hs_id:
continue
sid = f"hs-{hs_id}"
if sid in inv:
continue
text, name = await _load_history_session(store, hs_id)
if not text:
continue
inv.add(
SourceEntry(
sid=sid,
kind="history",
name=name,
full_text=text,
fresh=False,
first_seen_turn=turn_ordinal,
)
)
# Question-bank entries.
for raw in snap.get("questionNotebookReferences") or []:
try:
eid = int(raw)
except (TypeError, ValueError):
continue
sid = f"qb-{eid}"
if sid in inv:
continue
block, stem = await _load_question_entry(store, eid)
if not block:
continue
inv.add(
SourceEntry(
sid=sid,
kind="question",
name=stem,
full_text=block,
fresh=False,
first_seen_turn=turn_ordinal,
)
)
# ----- Lineage walker (branch-safe, store-protocol-compatible) ------------
async def _load_lineage(
store: SessionStoreProtocol,
session_id: str,
leaf_message_id: int | None,
) -> list[dict[str, Any]]:
"""Return the active branch's ancestor user/assistant messages in
chronological order. When ``leaf_message_id`` is ``None`` (legacy
linear append), returns every message in the session. When it's set
(branched edit), walks the ``parent_message_id`` chain up from that
leaf so sibling branches are excluded. Uses ``get_messages`` (which
every store implements) plus a Python-side parent walk, avoiding a
sqlite-only ``get_message_path``.
"""
all_msgs = await store.get_messages(session_id)
if leaf_message_id is None:
return all_msgs
by_id: dict[int, dict[str, Any]] = {}
for m in all_msgs:
mid = m.get("id")
if mid is not None:
by_id[int(mid)] = m
chain: list[dict[str, Any]] = []
current: int | None = int(leaf_message_id)
safety = 10_000
while current is not None and safety > 0:
m = by_id.get(int(current))
if m is None:
break
chain.append(m)
parent = m.get("parent_message_id")
current = int(parent) if parent is not None else None
safety -= 1
chain.reverse()
return chain
# ----- Per-type resolvers shared by fresh + historical paths --------------
def _split_book_sections(book_context_text: str) -> list[str]:
"""Split the output of ``build_book_context`` back into per-book
sections. ``build_book_context`` joins sections with ``"\\n\\n---\\n\\n"``;
we split on the same separator. Returns an empty list when input is
empty."""
if not book_context_text.strip():
return []
return [seg for seg in book_context_text.split("\n\n---\n\n") if seg.strip()]
def _extract_book_title(section: str, *, fallback: str) -> str:
"""``_serialize_book_header`` prefixes every section with
``# Book: <title>`` — extract that here for the manifest's name field."""
first_line = section.lstrip().split("\n", 1)[0]
prefix = "# Book: "
if first_line.startswith(prefix):
return first_line[len(prefix):].strip() or fallback
return fallback
def _resolve_book_section(book_reference: dict[str, Any]) -> tuple[str, str]:
"""Resolve a single book reference into its serialized section + title.
Used by the historical-collection path where each past turn's book
reference is rendered independently (so the per-book ``bk-{book_id}``
source id stays stable). Returns ``("", "")`` on failure.
"""
from deeptutor.book.context import build_book_context
try:
result = build_book_context([book_reference])
except Exception:
logger.debug("Failed to resolve historical book reference", exc_info=True)
return "", ""
text = (result.text or "").strip()
if not text:
return "", ""
name = _extract_book_title(
text, fallback=f"Book {book_reference.get('book_id', '?')}"
)
return text, name
async def _load_history_session(
store: SessionStoreProtocol, history_session_id: str
) -> tuple[str, str]:
"""Fetch and serialize a referenced history session into transcript +
title. Returns ``("", "")`` when the session is empty or missing.
"""
try:
meta = await store.get_session(history_session_id)
except Exception:
meta = None
if not meta:
return "", ""
try:
messages_in_hs = await store.get_messages_for_context(history_session_id)
except Exception:
messages_in_hs = []
transcript_lines = [
f"## {str(m.get('role', '')).title()}\n{m.get('content', '')}"
for m in messages_in_hs
if str(m.get("content", "") or "").strip()
]
if not transcript_lines:
return "", ""
name = str(meta.get("title", "") or "Untitled session")
return "\n\n".join(transcript_lines), name
async def _load_question_entry(
store: SessionStoreProtocol, entry_id: int
) -> tuple[str, str]:
"""Fetch and render one question-bank entry into a markdown block +
short stem (used as the manifest name). Returns ``("", "")`` on
missing entry. Imports the renderer lazily to avoid pulling
``turn_runtime``'s import surface into modules that consume this one."""
get_entry = getattr(store, "get_notebook_entry", None)
if not callable(get_entry):
return "", ""
try:
entry = await get_entry(entry_id)
except Exception:
entry = None
if not entry:
return "", ""
# Use the existing turn_runtime helper for consistency with fresh-path
# formatting. Imported here to keep this module's static deps minimal.
from deeptutor.services.session.turn_runtime import _format_question_bank_entry
block = _format_question_bank_entry(entry)
if not block.strip():
return "", ""
stem_source = str(entry.get("question", "") or "Untitled question")
stem = stem_source[:60].rstrip() or "Untitled question"
return block, stem
__all__ = [
"MANIFEST_PREVIEW_CHARS_FRESH",
"SourceEntry",
"SourceInventory",
"build_inventory",
"render_manifest",
]
+175 -22
View File
@@ -21,6 +21,18 @@ def _json_dumps(value: Any) -> str:
return json.dumps(value, ensure_ascii=False)
# Sentinel so ``add_message`` can distinguish "caller wants the legacy
# auto-pick-latest-message default" from "caller explicitly wants the
# message attached at the session root (parent = NULL)". Both surface as
# ``None`` in the public ``parent_message_id`` arg, which is why we need
# a sentinel separate from None.
class _Unset:
pass
_PARENT_AUTO = _Unset()
def _json_loads(value: str | None, default: Any) -> Any:
if not value:
return default
@@ -109,11 +121,20 @@ class SQLiteSessionStore:
events_json TEXT DEFAULT '',
attachments_json TEXT DEFAULT '',
metadata_json TEXT DEFAULT '{}',
created_at REAL NOT NULL
created_at REAL NOT NULL,
-- Edit-branching: NULL for the first message in a session;
-- otherwise the immediately preceding message on the path
-- this row continues. Siblings (same parent) are alternate
-- branches the user can switch between.
parent_message_id INTEGER
);
CREATE INDEX IF NOT EXISTS idx_messages_session_created
ON messages(session_id, created_at, id);
-- ``idx_messages_parent`` is created after the
-- parent_message_id migration runs (see below). Putting it
-- in this script would fail on legacy DBs where the column
-- gets added by ALTER TABLE further down.
CREATE INDEX IF NOT EXISTS idx_sessions_updated_at
ON sessions(updated_at DESC);
@@ -202,6 +223,34 @@ class SQLiteSessionStore:
}
if "metadata_json" not in message_columns:
conn.execute("ALTER TABLE messages ADD COLUMN metadata_json TEXT DEFAULT '{}'")
if "parent_message_id" not in message_columns:
conn.execute("ALTER TABLE messages ADD COLUMN parent_message_id INTEGER")
# Backfill: for every existing session, treat the message stream
# as a single linear path — each row's parent is the previous
# row (by id) in the same session. Rows with no predecessor stay
# NULL. We do this per session in pure Python to avoid relying
# on window functions, which older SQLite builds may not have.
sessions_rows = conn.execute("SELECT id FROM sessions").fetchall()
for srow in sessions_rows:
prev_id: int | None = None
msg_rows = conn.execute(
"SELECT id FROM messages WHERE session_id = ? ORDER BY id ASC",
(srow[0],),
).fetchall()
for mrow in msg_rows:
if prev_id is not None:
conn.execute(
"UPDATE messages SET parent_message_id = ? WHERE id = ?",
(prev_id, mrow[0]),
)
prev_id = mrow[0]
# Always ensure the parent-lookup index exists — covers both
# the legacy-migration case (just added the column) and the
# fresh-DB case (created above without the index inline).
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_messages_parent "
"ON messages(session_id, parent_message_id)"
)
conn.commit()
async def _run(self, fn, *args):
@@ -572,6 +621,7 @@ class SQLiteSessionStore:
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
metadata: dict[str, Any] | None = None,
parent_message_id: int | None | _Unset = _PARENT_AUTO,
) -> int:
now = time.time()
with self._connect() as conn:
@@ -581,12 +631,29 @@ class SQLiteSessionStore:
if session is None:
raise ValueError(f"Session not found: {session_id}")
resolved_parent_id: int | None
if isinstance(parent_message_id, _Unset):
# Legacy auto-append path: chain off the latest row in the
# session so the linear thread stays connected.
last_row = conn.execute(
"SELECT id FROM messages WHERE session_id = ? ORDER BY id DESC LIMIT 1",
(session_id,),
).fetchone()
resolved_parent_id = int(last_row["id"]) if last_row is not None else None
else:
# Caller pinned a parent explicitly — including ``None``,
# which means "attach at the session root" (used by edits
# of the very first message in a session).
resolved_parent_id = (
int(parent_message_id) if parent_message_id is not None else None
)
cur = conn.execute(
"""
INSERT INTO messages (
session_id, role, content, capability, events_json,
attachments_json, metadata_json, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
attachments_json, metadata_json, created_at, parent_message_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
session_id,
@@ -597,6 +664,7 @@ class SQLiteSessionStore:
_json_dumps(attachments or []),
_json_dumps(metadata or {}),
now,
resolved_parent_id,
),
)
@@ -627,6 +695,7 @@ class SQLiteSessionStore:
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
metadata: dict[str, Any] | None = None,
parent_message_id: int | None | _Unset = _PARENT_AUTO,
) -> int:
return await self._run(
self._add_message_sync,
@@ -637,6 +706,7 @@ class SQLiteSessionStore:
events,
attachments,
metadata,
parent_message_id,
)
def _delete_message_sync(self, message_id: int | str) -> bool:
@@ -775,7 +845,7 @@ class SQLiteSessionStore:
row = conn.execute(
"""
SELECT id, session_id, role, content, capability, events_json,
attachments_json, metadata_json, created_at
attachments_json, metadata_json, created_at, parent_message_id
FROM messages
WHERE session_id = ?
ORDER BY id DESC
@@ -787,7 +857,7 @@ class SQLiteSessionStore:
row = conn.execute(
"""
SELECT id, session_id, role, content, capability, events_json,
attachments_json, metadata_json, created_at
attachments_json, metadata_json, created_at, parent_message_id
FROM messages
WHERE session_id = ? AND role = ?
ORDER BY id DESC
@@ -805,6 +875,8 @@ class SQLiteSessionStore:
return await self._run(self._get_last_message_sync, session_id, role)
def _serialize_message(self, row: sqlite3.Row) -> dict[str, Any]:
row_keys = row.keys()
parent_id = row["parent_message_id"] if "parent_message_id" in row_keys else None
return {
"id": row["id"],
"session_id": row["session_id"],
@@ -815,6 +887,7 @@ class SQLiteSessionStore:
"attachments": _json_loads(row["attachments_json"], []),
"metadata": _json_loads(row["metadata_json"], {}),
"created_at": row["created_at"],
"parent_message_id": int(parent_id) if parent_id is not None else None,
}
def _get_messages_sync(self, session_id: str) -> list[dict[str, Any]]:
@@ -822,7 +895,7 @@ class SQLiteSessionStore:
rows = conn.execute(
"""
SELECT id, session_id, role, content, capability, events_json,
attachments_json, metadata_json, created_at
attachments_json, metadata_json, created_at, parent_message_id
FROM messages
WHERE session_id = ?
ORDER BY id ASC
@@ -831,27 +904,107 @@ class SQLiteSessionStore:
).fetchall()
return [self._serialize_message(row) for row in rows]
def _get_message_path_sync(
self, session_id: str, leaf_message_id: int
) -> list[dict[str, Any]]:
"""Return the chain of messages from the session root down to
``leaf_message_id`` (inclusive), in chronological order.
Used by the turn runtime to build LLM context for a branched
re-run: only ancestors of the new user message are included, so
sibling branches at any depth are excluded.
"""
with self._connect() as conn:
chain: list[dict[str, Any]] = []
current: int | None = int(leaf_message_id)
# Bound the walk defensively in case of corrupted parent pointers.
safety = 10_000
while current is not None and safety > 0:
row = conn.execute(
"""
SELECT id, session_id, role, content, capability, events_json,
attachments_json, metadata_json, created_at, parent_message_id
FROM messages
WHERE id = ? AND session_id = ?
""",
(current, session_id),
).fetchone()
if row is None:
break
chain.append(self._serialize_message(row))
parent = row["parent_message_id"]
current = int(parent) if parent is not None else None
safety -= 1
chain.reverse()
return chain
async def get_message_path(
self, session_id: str, leaf_message_id: int
) -> list[dict[str, Any]]:
return await self._run(self._get_message_path_sync, session_id, int(leaf_message_id))
async def get_messages(self, session_id: str) -> list[dict[str, Any]]:
return await self._run(self._get_messages_sync, session_id)
def _get_messages_for_context_sync(self, session_id: str) -> list[dict[str, Any]]:
def _get_messages_for_context_sync(
self, session_id: str, leaf_message_id: int | None = None
) -> list[dict[str, Any]]:
with self._connect() as conn:
rows = conn.execute(
"""
SELECT id, role, content
FROM messages
WHERE session_id = ?
AND role IN ('user', 'assistant', 'system')
ORDER BY id ASC
""",
(session_id,),
).fetchall()
return [
{"id": row["id"], "role": row["role"], "content": row["content"] or ""} for row in rows
]
if leaf_message_id is None:
rows = conn.execute(
"""
SELECT id, role, content
FROM messages
WHERE session_id = ?
AND role IN ('user', 'assistant', 'system')
ORDER BY id ASC
""",
(session_id,),
).fetchall()
return [
{
"id": row["id"],
"role": row["role"],
"content": row["content"] or "",
}
for row in rows
]
# Branch-aware path walk: include only ancestors (+ leaf) so
# sibling branches at any depth are excluded from LLM context.
chain: list[dict[str, Any]] = []
current: int | None = int(leaf_message_id)
safety = 10_000
while current is not None and safety > 0:
row = conn.execute(
"""
SELECT id, role, content, parent_message_id
FROM messages
WHERE id = ? AND session_id = ?
AND role IN ('user', 'assistant', 'system')
""",
(current, session_id),
).fetchone()
if row is None:
break
chain.append(
{
"id": row["id"],
"role": row["role"],
"content": row["content"] or "",
}
)
parent = row["parent_message_id"]
current = int(parent) if parent is not None else None
safety -= 1
chain.reverse()
return chain
async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]:
return await self._run(self._get_messages_for_context_sync, session_id)
async def get_messages_for_context(
self, session_id: str, leaf_message_id: int | None = None
) -> list[dict[str, Any]]:
return await self._run(
self._get_messages_for_context_sync, session_id, leaf_message_id
)
def _list_sessions_sync(
self,
+378 -178
View File
@@ -155,6 +155,44 @@ def _format_question_bank_entry(entry: dict[str, Any]) -> str:
return "\n".join(lines)
async def _count_branch_user_turns(
store: SessionStoreProtocol,
session_id: str,
leaf_message_id: int | None,
) -> int:
"""Count user messages on the active branch's ancestor chain.
Used by the chat source inventory to assign ``first_seen_turn`` for
*fresh* sources (= current turn = past_user_turns + 1). When
``leaf_message_id`` is ``None`` (legacy linear append) all messages
in the session are counted; otherwise we walk the
``parent_message_id`` chain so sibling branches don't inflate the
count. Kept tiny and protocol-only (``get_messages``) so it stays
compatible with every store backend.
"""
all_msgs = await store.get_messages(session_id)
if leaf_message_id is None:
return sum(1 for m in all_msgs if m.get("role") == "user")
by_id: dict[int, dict[str, Any]] = {}
for m in all_msgs:
mid = m.get("id")
if mid is not None:
by_id[int(mid)] = m
count = 0
current: int | None = int(leaf_message_id)
safety = 10_000
while current is not None and safety > 0:
m = by_id.get(int(current))
if m is None:
break
if m.get("role") == "user":
count += 1
parent = m.get("parent_message_id")
current = int(parent) if parent is not None else None
safety -= 1
return count
async def _build_question_bank_context(
store: SessionStoreProtocol,
entry_ids: list[Any],
@@ -348,6 +386,9 @@ class _TurnExecution:
payload: dict[str, Any]
task: asyncio.Task[None] | None = None
subscribers: list[_LiveSubscriber] = field(default_factory=list)
events: list[dict[str, Any]] = field(default_factory=list)
next_seq: int = 1
events_flushed: bool = False
class TurnRuntimeManager:
@@ -475,7 +516,7 @@ class TurnRuntimeManager:
session_metadata["superseded_turn_id"] = str(superseded_turn_id)
if runtime_only_config.get("_regenerate"):
session_metadata["regenerate"] = True
await self._persist_and_publish(
await self._publish_live_event(
execution,
StreamEvent(
type=StreamEventType.SESSION,
@@ -624,21 +665,33 @@ class TurnRuntimeManager:
queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue()
subscriber = _LiveSubscriber(queue=queue)
execution: _TurnExecution | None = None
live_backlog: list[dict[str, Any]] = []
async with self._lock:
execution = self._executions.get(turn_id)
if execution is not None:
execution.subscribers.append(subscriber)
live_backlog = [
item
for item in execution.events
if int(item.get("seq") or 0) > last_seq
]
catchup = await self.store.get_turn_events(turn_id, after_seq=last_seq)
for item in live_backlog:
seq = int(item.get("seq") or 0)
if seq <= last_seq:
continue
last_seq = seq
yield item
catchup = []
if execution is None:
catchup = await self.store.get_turn_events(turn_id, after_seq=last_seq)
for item in catchup:
seq = int(item.get("seq") or 0)
if seq <= last_seq:
continue
last_seq = seq
if execution is None:
yield item
else:
queue.put_nowait(item)
yield item
turn = await self.store.get_turn(turn_id)
if execution is None:
@@ -682,6 +735,7 @@ class TurnRuntimeManager:
attachment_records = []
assistant_events: list[dict[str, Any]] = []
assistant_content = ""
stream_done_sent = False
llm_scope_token: Token[LLMConfig | None] | None = None
reset_active_llm_selection: Callable[[Token[LLMConfig | None] | None], None] | None = None
@@ -708,6 +762,25 @@ class TurnRuntimeManager:
request_config.pop("_regenerated_from_message_id", None)
request_config.pop("_superseded_turn_id", None)
raw_user_content = str(payload.get("content", "") or "")
# Edit-branching tip: when the FE includes ``parent_message_id``
# (even as ``null``), the new user message attaches at that
# exact parent — creating a sibling of any existing children
# and forcing LLM context to come from that parent's ancestor
# chain only. When the key is absent (legacy callers), the
# store auto-appends to the latest message in the session.
branch_parent_explicit = "parent_message_id" in payload
branch_parent_raw = payload.get("parent_message_id")
branch_parent_id: int | None
if branch_parent_explicit:
try:
branch_parent_id = (
int(branch_parent_raw) if branch_parent_raw is not None else None
)
except (TypeError, ValueError):
branch_parent_id = None
branch_parent_explicit = False
else:
branch_parent_id = None
notebook_references = payload.get("notebook_references", []) or []
history_references = payload.get("history_references", []) or []
question_notebook_references = payload.get("question_notebook_references", []) or []
@@ -799,7 +872,9 @@ class TurnRuntimeManager:
]
if followup_question_context:
existing_messages = await self.store.get_messages_for_context(session_id)
existing_messages = await self.store.get_messages_for_context(
session_id, leaf_message_id=branch_parent_id
)
if not existing_messages:
await self.store.add_message(
session_id=session_id,
@@ -815,13 +890,16 @@ class TurnRuntimeManager:
builder = ContextBuilder(self.store)
async def _emit_context_event(event: StreamEvent) -> None:
await self._persist_and_publish(execution, event)
if event.source in {"context", "context_builder"}:
return
await self._publish_live_event(execution, event)
history_result = await builder.build(
session_id=session_id,
llm_config=llm_config,
language=payload.get("language", "en"),
on_event=_emit_context_event,
leaf_message_id=branch_parent_id,
)
memory_service = get_memory_service()
memory_context = memory_service.build_memory_context(memory_references)
@@ -878,123 +956,175 @@ class TurnRuntimeManager:
user_block = user_skill_service.load_for_context(user_picks)
skills_context = "\n\n".join(part for part in (admin_block, user_block) if part)
if notebook_references:
referenced_records = get_notebook_manager().get_records_by_references(
notebook_references
# Chat capability uses the lightweight manifest + read_source
# affordance (no upstream LLM call, no wholesale-dump into the
# user message). All other capabilities keep the legacy concat
# path because their internal pipelines consume the named blocks
# (``[Notebook Context]`` etc.) directly.
is_chat_capability = (capability_name or "") in {"", "chat"}
source_manifest_text = ""
source_index: dict[str, str] = {}
if is_chat_capability:
from deeptutor.services.session.source_inventory import (
build_inventory,
render_manifest,
)
if referenced_records:
analysis_agent = NotebookAnalysisAgent(
language=str(payload.get("language", "en") or "en")
resolved_notebook_records = (
get_notebook_manager().get_records_by_references(notebook_references)
if notebook_references
else []
)
# Current turn ordinal = (#user messages on this branch's
# ancestor chain) + 1. ``_count_branch_user_turns`` walks
# the same lineage the inventory builder uses, so we agree
# on what "turn N" means for the historical labels.
current_turn_ordinal = await _count_branch_user_turns(
self.store, session_id, branch_parent_id
) + 1
inventory = await build_inventory(
self.store,
session_id=session_id,
leaf_message_id=branch_parent_id,
current_turn_ordinal=current_turn_ordinal,
fresh_attachment_records=attachment_records,
fresh_notebook_records=resolved_notebook_records,
fresh_book_context_text=book_context,
fresh_book_references=book_references,
fresh_history_session_ids=history_references,
fresh_question_entry_ids=question_notebook_references,
)
source_manifest_text, source_index = render_manifest(inventory)
effective_user_message = raw_user_content
else:
if notebook_references:
referenced_records = get_notebook_manager().get_records_by_references(
notebook_references
)
notebook_context = await analysis_agent.analyze(
user_question=raw_user_content,
records=referenced_records,
emit=_emit_context_event,
)
if history_references:
history_records: list[dict[str, Any]] = []
for session_ref in history_references:
history_session_id = str(session_ref or "").strip()
if not history_session_id:
continue
history_session = await self.store.get_session(history_session_id)
if not history_session:
continue
history_messages = await self.store.get_messages_for_context(history_session_id)
transcript_lines = [
f"## {str(message.get('role', '')).title()}\n{message.get('content', '')}"
for message in history_messages
if str(message.get("content", "") or "").strip()
]
if not transcript_lines:
continue
history_summary = str(
history_session.get("compressed_summary", "") or ""
).strip()
if not history_summary:
history_summary = _clip_text(
" ".join(
str(message.get("content", "") or "").strip()
for message in history_messages[-4:]
if str(message.get("content", "") or "").strip()
),
limit=400,
if referenced_records:
analysis_agent = NotebookAnalysisAgent(
language=str(payload.get("language", "en") or "en")
)
notebook_context = await analysis_agent.analyze(
user_question=raw_user_content,
records=referenced_records,
emit=_emit_context_event,
)
if not history_summary:
history_summary = f"{len(history_messages)} messages"
history_records.append(
{
"id": history_session_id,
"notebook_id": "__history__",
"notebook_name": "History",
"title": str(history_session.get("title", "") or "Untitled session"),
"summary": history_summary,
"output": "\n\n".join(transcript_lines),
"metadata": {
"session_id": history_session_id,
"source": "history",
},
}
if history_references:
history_records: list[dict[str, Any]] = []
for session_ref in history_references:
history_session_id = str(session_ref or "").strip()
if not history_session_id:
continue
history_session = await self.store.get_session(history_session_id)
if not history_session:
continue
history_messages = await self.store.get_messages_for_context(history_session_id)
transcript_lines = [
f"## {str(message.get('role', '')).title()}\n{message.get('content', '')}"
for message in history_messages
if str(message.get("content", "") or "").strip()
]
if not transcript_lines:
continue
history_summary = str(
history_session.get("compressed_summary", "") or ""
).strip()
if not history_summary:
history_summary = _clip_text(
" ".join(
str(message.get("content", "") or "").strip()
for message in history_messages[-4:]
if str(message.get("content", "") or "").strip()
),
limit=400,
)
if not history_summary:
history_summary = f"{len(history_messages)} messages"
history_records.append(
{
"id": history_session_id,
"notebook_id": "__history__",
"notebook_name": "History",
"title": str(history_session.get("title", "") or "Untitled session"),
"summary": history_summary,
"output": "\n\n".join(transcript_lines),
"metadata": {
"session_id": history_session_id,
"source": "history",
},
}
)
if history_records:
analysis_agent = NotebookAnalysisAgent(
language=str(payload.get("language", "en") or "en")
)
history_context = await analysis_agent.analyze(
user_question=raw_user_content,
records=history_records,
emit=_emit_context_event,
)
if not history_context.strip():
MAX_FALLBACK_CHARS = 8000
parts: list[str] = []
total = 0
for record in history_records:
output = record.get("output")
if not output:
continue
part = f"## Session: {record.get('title', 'Untitled')}\n{output}"
if total + len(part) > MAX_FALLBACK_CHARS:
remaining = MAX_FALLBACK_CHARS - total
if remaining > 100:
parts.append(part[:remaining] + "\n...(truncated)")
break
parts.append(part)
total += len(part)
history_context = "\n\n".join(parts)
if question_notebook_references:
question_bank_context = await _build_question_bank_context(
self.store, question_notebook_references
)
if history_records:
analysis_agent = NotebookAnalysisAgent(
language=str(payload.get("language", "en") or "en")
)
history_context = await analysis_agent.analyze(
user_question=raw_user_content,
records=history_records,
emit=_emit_context_event,
)
if not history_context.strip():
MAX_FALLBACK_CHARS = 8000
parts: list[str] = []
total = 0
for record in history_records:
output = record.get("output")
if not output:
continue
part = f"## Session: {record.get('title', 'Untitled')}\n{output}"
if total + len(part) > MAX_FALLBACK_CHARS:
remaining = MAX_FALLBACK_CHARS - total
if remaining > 100:
parts.append(part[:remaining] + "\n...(truncated)")
break
parts.append(part)
total += len(part)
history_context = "\n\n".join(parts)
if question_notebook_references:
question_bank_context = await _build_question_bank_context(
self.store, question_notebook_references
)
effective_user_message = raw_user_content
context_parts: list[str] = []
if document_texts:
context_parts.append("[Attached Documents]\n" + "\n\n".join(document_texts))
if book_context:
context_parts.append(f"[Book Context]\n{book_context}")
if notebook_context:
context_parts.append(f"[Notebook Context]\n{notebook_context}")
if history_context:
context_parts.append(f"[History Context]\n{history_context}")
if question_bank_context:
context_parts.append(f"[Question Bank Context]\n{question_bank_context}")
if context_parts:
context_parts.append(f"[User Question]\n{raw_user_content}")
effective_user_message = "\n\n".join(context_parts)
effective_user_message = raw_user_content
context_parts: list[str] = []
if document_texts:
context_parts.append("[Attached Documents]\n" + "\n\n".join(document_texts))
if book_context:
context_parts.append(f"[Book Context]\n{book_context}")
if notebook_context:
context_parts.append(f"[Notebook Context]\n{notebook_context}")
if history_context:
context_parts.append(f"[History Context]\n{history_context}")
if question_bank_context:
context_parts.append(f"[Question Bank Context]\n{question_bank_context}")
if context_parts:
context_parts.append(f"[User Question]\n{raw_user_content}")
effective_user_message = "\n\n".join(context_parts)
conversation_history = list(history_result.conversation_history)
conversation_context_text = history_result.context_text
new_user_message_id: int | None = None
if persist_user_message:
await self.store.add_message(
# Pass parent explicitly only when the FE pinned it (covers
# both branched edits with a positive id and root edits
# with explicit null). Otherwise let the store auto-append.
parent_kwargs: dict[str, Any] = (
{"parent_message_id": branch_parent_id}
if branch_parent_explicit
else {}
)
new_user_message_id = await self.store.add_message(
session_id=session_id,
role="user",
content=raw_user_content,
@@ -1014,6 +1144,7 @@ class TurnRuntimeManager:
memory_references=memory_references,
llm_selection=payload.get("llm_selection"),
),
**parent_kwargs,
)
context = UnifiedContext(
@@ -1026,10 +1157,9 @@ class TurnRuntimeManager:
attachments=attachments,
config_overrides=request_config,
language=payload.get("language", "en"),
notebook_context=notebook_context,
history_context=history_context,
memory_context=memory_context,
skills_context=skills_context,
source_manifest=source_manifest_text,
metadata={
"conversation_summary": history_result.conversation_summary,
"conversation_context_text": conversation_context_text,
@@ -1050,6 +1180,11 @@ class TurnRuntimeManager:
"llm_selection": payload.get("llm_selection") or {},
"llm_model": str(getattr(llm_config, "model", "") or ""),
"llm_provider": str(getattr(llm_config, "provider_name", "") or ""),
# Per-turn full-text payload for read_source. Empty when
# the manifest is empty (non-chat capabilities, or chat
# turns with no attached sources). Consumed by the chat
# pipeline's tool kwargs injector.
"source_index": source_index,
},
)
@@ -1057,19 +1192,46 @@ class TurnRuntimeManager:
async for event in orch.handle(context):
if event.type == StreamEventType.SESSION:
continue
payload_event = await self._persist_and_publish(execution, event)
payload_event = await self._publish_live_event(execution, event)
if event.type == StreamEventType.DONE:
stream_done_sent = True
if payload_event.get("type") not in {"done", "session"}:
assistant_events.append(payload_event)
if _should_capture_assistant_content(event):
assistant_content += event.content
await self.store.add_message(
session_id=session_id,
role="assistant",
content=assistant_content,
capability=capability_name,
events=assistant_events,
)
# Assistant continues the same branch as the user message it
# answers. If we just persisted a new user row we chain off
# that; if we did not (regenerate path) and the caller pinned a
# parent, we use it; otherwise we let the store auto-append
# (legacy behavior).
if new_user_message_id is not None:
await self.store.add_message(
session_id=session_id,
role="assistant",
content=assistant_content,
capability=capability_name,
events=assistant_events,
parent_message_id=new_user_message_id,
)
elif branch_parent_explicit:
await self.store.add_message(
session_id=session_id,
role="assistant",
content=assistant_content,
capability=capability_name,
events=assistant_events,
parent_message_id=branch_parent_id,
)
else:
await self.store.add_message(
session_id=session_id,
role="assistant",
content=assistant_content,
capability=capability_name,
events=assistant_events,
)
await self._flush_buffered_events(execution)
await self.store.update_turn_status(turn_id, "completed")
if not is_regenerate:
try:
@@ -1083,45 +1245,59 @@ class TurnRuntimeManager:
except Exception:
logger.debug("Failed to refresh lightweight memory", exc_info=True)
except asyncio.CancelledError:
if not stream_done_sent:
await self._publish_live_event(
execution,
StreamEvent(
type=StreamEventType.ERROR,
source=capability_name,
content="Turn cancelled",
metadata={"turn_terminal": True, "status": "cancelled"},
),
)
await self._publish_live_event(
execution,
StreamEvent(
type=StreamEventType.DONE,
source=capability_name,
metadata={"status": "cancelled"},
),
)
await self._flush_buffered_events(execution)
await self.store.update_turn_status(turn_id, "cancelled", "Turn cancelled")
await self._persist_and_publish(
execution,
StreamEvent(
type=StreamEventType.ERROR,
source=capability_name,
content="Turn cancelled",
metadata={"turn_terminal": True, "status": "cancelled"},
),
)
await self._persist_and_publish(
execution,
StreamEvent(
type=StreamEventType.DONE,
source=capability_name,
metadata={"status": "cancelled"},
),
)
raise
except Exception as exc:
logger.error("Turn %s failed: %s", turn_id, exc, exc_info=True)
await self.store.update_turn_status(turn_id, "failed", str(exc))
await self._persist_and_publish(
execution,
StreamEvent(
type=StreamEventType.ERROR,
source=capability_name,
content=str(exc),
metadata={"turn_terminal": True, "status": "failed"},
),
)
await self._persist_and_publish(
execution,
StreamEvent(
type=StreamEventType.DONE,
source=capability_name,
metadata={"status": "failed"},
),
)
if stream_done_sent:
logger.error(
"Post-stream persistence for turn %s failed: %s",
turn_id,
exc,
exc_info=True,
)
with contextlib.suppress(Exception):
await self._flush_buffered_events(execution)
await self.store.update_turn_status(turn_id, "failed", str(exc))
else:
logger.error("Turn %s failed: %s", turn_id, exc, exc_info=True)
await self._publish_live_event(
execution,
StreamEvent(
type=StreamEventType.ERROR,
source=capability_name,
content=str(exc),
metadata={"turn_terminal": True, "status": "failed"},
),
)
await self._publish_live_event(
execution,
StreamEvent(
type=StreamEventType.DONE,
source=capability_name,
metadata={"status": "failed"},
),
)
await self._flush_buffered_events(execution)
await self.store.update_turn_status(turn_id, "failed", str(exc))
finally:
if llm_scope_token is not None and reset_active_llm_selection is not None:
reset_active_llm_selection(llm_scope_token)
@@ -1133,7 +1309,7 @@ class TurnRuntimeManager:
subscriber.queue.put_nowait(None)
self._executions.pop(turn_id, None)
async def _persist_and_publish(
async def _publish_live_event(
self,
execution: _TurnExecution,
event: StreamEvent,
@@ -1143,26 +1319,50 @@ class TurnRuntimeManager:
event.session_id = execution.session_id
event.turn_id = execution.turn_id
payload = event.to_dict()
try:
persisted = await self.store.append_turn_event(execution.turn_id, payload)
except ValueError as exc:
# A turn can disappear when the session is deleted while the turn task
# is still draining events. Avoid cascading failures in the error path.
if "Turn not found:" not in str(exc):
raise
logger.warning(
"Skip persisting event for missing turn %s (%s)",
execution.turn_id,
event.type.value,
)
persisted = payload
self._mirror_event_to_workspace(execution, persisted)
async with self._lock:
subscribers = list(self._executions.get(execution.turn_id, execution).subscribers)
current = self._executions.get(execution.turn_id, execution)
seq = int(payload.get("seq") or 0)
if seq <= 0:
seq = current.next_seq
current.next_seq += 1
if current is not execution:
execution.next_seq = max(execution.next_seq, current.next_seq)
else:
current.next_seq = max(current.next_seq, seq + 1)
execution.next_seq = max(execution.next_seq, seq + 1)
payload["seq"] = seq
current.events.append(payload)
if current is not execution:
execution.events.append(payload)
subscribers = list(current.subscribers)
for subscriber in subscribers:
with contextlib.suppress(asyncio.QueueFull):
subscriber.queue.put_nowait(persisted)
return persisted
subscriber.queue.put_nowait(payload)
return payload
async def _flush_buffered_events(self, execution: _TurnExecution) -> None:
"""Persist buffered turn events after the live stream has already drained."""
async with self._lock:
if execution.events_flushed:
return
execution.events_flushed = True
events = list(execution.events)
for payload in events:
try:
persisted = await self.store.append_turn_event(execution.turn_id, payload)
except ValueError as exc:
# A turn can disappear when the session is deleted while the turn task
# is draining post-stream persistence. Avoid cascading failures.
if "Turn not found:" not in str(exc):
raise
logger.warning(
"Skip persisting event for missing turn %s (%s)",
execution.turn_id,
payload.get("type", ""),
)
continue
self._mirror_event_to_workspace(execution, persisted)
@staticmethod
def _mirror_event_to_workspace(execution: _TurnExecution, payload: dict[str, Any]) -> None:
+68
View File
@@ -502,6 +502,72 @@ class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):
)
class ReadSourceTool(_PromptHintsMixin, BaseTool):
"""Load the full text of an attached Space source by its manifest id.
The chat pipeline auto-enables this tool whenever a turn has any non-image
attached source (notebook record, book reference, history session,
question-bank entry, or document attachment). The per-turn full-text
payload is carried in ``context.metadata["source_index"]`` as
``{source_id: str}`` and injected into the tool call by
``_augment_tool_kwargs``. The tool itself stays stateless.
"""
def get_definition(self) -> ToolDefinition:
return ToolDefinition(
name="read_source",
description=(
"Load the full text of one attached source by id. Use ONLY when "
"the preview shown in the Attached Sources manifest is "
"insufficient to answer the user's question. The id must be "
"copied verbatim from the manifest — do not invent ids. Do not "
"call this on every source 'just in case'."
),
parameters=[
ToolParameter(
name="source_id",
type="string",
description=(
"The source identifier from the Attached Sources "
"manifest. Begins with one of: nb- (notebook record), "
"bk- (book reference), hs- (history session), qb- "
"(question-bank entry), at- (document attachment)."
),
),
],
)
async def execute(self, **kwargs: Any) -> ToolResult:
source_id = str(kwargs.get("source_id") or "").strip()
if not source_id:
return ToolResult(
content="Error: source_id is required.",
success=False,
)
source_index = kwargs.get("source_index")
if not isinstance(source_index, dict) or not source_index:
return ToolResult(
content=(
"Error: no attached sources are available for this turn."
),
success=False,
)
full_text = source_index.get(source_id)
if not full_text:
available = ", ".join(sorted(source_index.keys()))
return ToolResult(
content=(
f"Error: unknown source_id {source_id!r}. "
f"Valid ids for this turn: {available or '(none)'}."
),
success=False,
)
return ToolResult(
content=str(full_text),
metadata={"source_id": source_id, "char_count": len(str(full_text))},
)
BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
BrainstormTool,
RAGTool,
@@ -510,6 +576,7 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
ReasonTool,
PaperSearchToolWrapper,
GeoGebraAnalysisTool,
ReadSourceTool,
)
BUILTIN_TOOL_NAMES: tuple[str, ...] = tuple(tool_type().name for tool_type in BUILTIN_TOOL_TYPES)
@@ -531,6 +598,7 @@ __all__ = [
"GeoGebraAnalysisTool",
"PaperSearchToolWrapper",
"RAGTool",
"ReadSourceTool",
"ReasonTool",
"WebSearchTool",
]
+22
View File
@@ -98,6 +98,28 @@ class ToolPromptComposer:
lines.append(f"- {name}: {hint.short_description}")
return "\n".join(lines)
def format_list_with_usage(self, hints: list[ToolHintEntry]) -> str:
"""Per-tool bullet that includes ``when_to_use`` and ``input_format``.
Used by the chat persona prompt so the LLM has enough per-tool
guidance to decide *whether* to call it, not just *what it is*.
Tools without a ``short_description`` are skipped entirely so the
block never carries empty bullets.
"""
when_label = "When to use" if self.language != "zh" else "适用场景"
input_label = "Input" if self.language != "zh" else "参数格式"
blocks: list[str] = []
for name, hint in hints:
if not hint.short_description:
continue
entry: list[str] = [f"- `{name}` — {hint.short_description}"]
if hint.when_to_use:
entry.append(f" {when_label}: {hint.when_to_use}")
if hint.input_format:
entry.append(f" {input_label}: {hint.input_format}")
blocks.append("\n".join(entry))
return "\n".join(blocks)
def format_table(
self,
hints: list[ToolHintEntry],
@@ -0,0 +1,6 @@
short_description: "Load the full text of an attached source (notebook record, book pages, history session, question-bank entry, document attachment) by its manifest id."
when_to_use: "Call ONLY when the preview shown in the \"Attached Sources\" manifest is not enough to answer the user's question. Do not re-fetch sources whose preview already covers the question."
input_format: "{\"source_id\": \"the exact id from the manifest (e.g. nb-... / bk-... / hs-... / qb-... / at-...)\"}."
guideline: "Copy source_id verbatim from the manifest — never invent or guess one. Load one source per call; issue separate calls if multiple sources are needed."
note: "When no source is attached, this tool will not appear; do not ask the user to clarify \"which material\"."
phase: "exploration"
@@ -0,0 +1,6 @@
short_description: "按 id 加载已挂载来源(笔记、书页、历史会话、题库条目、附件)的完整文本。"
when_to_use: "仅当上方 \"Attached Sources\" 清单中某条目的 preview 不足以回答用户问题时才调用;preview 已经包含的内容不要重复调。"
input_format: "{\"source_id\": \"清单中给出的精确 id(如 nb-... / bk-... / hs-... / qb-... / at-...)\"}。"
guideline: "source_id 必须照搬清单原文,绝不拼造。一次只能取一个来源,多个来源相关时按需多次调用。"
note: "如果用户根本没挂任何来源,本工具不会出现;不要凭空询问\"哪份资料\"。"
phase: "exploration"
@@ -40,6 +40,9 @@ _DEFAULT_OPENROUTER_HEADERS = {
"HTTP-Referer": "https://github.com/HKUDS/DeepTutor",
"X-OpenRouter-Title": "DeepTutor",
}
_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (
("deepseek", "deepseek-v4-flash"),
)
def _short_tool_id() -> str:
@@ -47,6 +50,16 @@ def _short_tool_id() -> str:
return "".join(secrets.choice(_ALNUM) for _ in range(9))
def _disable_thinking_by_default(spec: ProviderSpec | None, model_name: str) -> bool:
if not spec:
return False
normalized = (model_name or "").strip().lower()
return any(
spec.name == provider and pattern in normalized
for provider, pattern in _THINKING_DISABLED_BY_DEFAULT
)
def _get(obj: Any, key: str) -> Any:
if isinstance(obj, dict):
return obj.get(key)
@@ -276,6 +289,11 @@ class OpenAICompatProvider(LLMProvider):
extra = {"reasoning_split": thinking_enabled}
if extra:
kwargs.setdefault("extra_body", {}).update(extra)
elif spec and _disable_thinking_by_default(spec, model_name):
if spec.name == "deepseek":
kwargs.setdefault("extra_body", {}).update(
{"thinking": {"type": "disabled"}}
)
# Providers that handle thinking via extra_body don't need a
# top-level reasoning_effort when the intent is to disable thinking.
-1
View File
@@ -175,7 +175,6 @@ def register(app: typer.Typer) -> None:
kb_name=name,
source_files=doc_paths,
base_dir=str(mgr.base_dir),
skip_extract=True,
)
)
except Exception as exc:
+1
View File
@@ -31,6 +31,7 @@ dependencies = [
"perplexityai>=0.1.0",
"oauth-cli-kit>=0.1.1",
"llama-index>=0.14.12",
"llama-index-retrievers-bm25>=0.7.1,<0.8.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
+9
View File
@@ -36,6 +36,7 @@ dependencies = [
"perplexityai>=0.1.0",
"oauth-cli-kit>=0.1.1",
"llama-index>=0.14.12",
"llama-index-retrievers-bm25>=0.7.1,<0.8.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
@@ -70,6 +71,7 @@ cli = [
"oauth-cli-kit>=0.1.1",
# RAG (LlamaIndex)
"llama-index>=0.14.12",
"llama-index-retrievers-bm25>=0.7.1,<0.8.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
@@ -144,6 +146,13 @@ dev = [
"pre-commit>=3.0.0",
"safety<3.0.0",
"bandit>=1.8.0",
# Test fixture builders for document-loader tests. Runtime pulls these via
# cli/server, but dev keeps them explicit for pytest collection.
"python-docx>=1.1.0",
"openpyxl>=3.1.0",
"python-pptx>=1.0.0",
"pypdf>=4.0.0",
"defusedxml>=0.7.1",
]
# Everything: server + tutorbot + non-E2EE matrix + math-animator + dev tools.
+1
View File
@@ -38,6 +38,7 @@ aiosqlite>=0.19.0
# --- RAG (LlamaIndex) ---
llama-index>=0.14.12
llama-index-retrievers-bm25>=0.7.1,<0.8.0
PyMuPDF>=1.26.0
numpy>=1.24.0,<3.0.0
arxiv>=2.0.0
+9
View File
@@ -14,3 +14,12 @@ pytest-asyncio>=0.23.0
pre-commit>=3.0.0
safety<3.0.0
bandit>=1.8.0
# --- Test fixture builders for document-loader tests ---
# These are also pulled by cli.txt at runtime; keep explicit here so dev/test
# installs have the imports needed during pytest collection.
python-docx>=1.1.0
openpyxl>=3.1.0
python-pptx>=1.0.0
pypdf>=4.0.0
defusedxml>=0.7.1
+3 -47
View File
@@ -10,11 +10,10 @@ Features:
- Validate required index files
- Copy/migrate KB to target directory
- Register in kb_config.json
- Optionally extract numbered items (if content_list exists)
- Run test query to verify migration
Usage:
python scripts/migrate_kb.py /path/to/kb --name my_kb --test --extract-items
python scripts/migrate_kb.py /path/to/kb --name my_kb --test
python scripts/migrate_kb.py /path/to/kb --validate-only
"""
@@ -176,11 +175,9 @@ def validate_kb(kb_path: Path) -> dict:
"needs_reindex": False,
"missing_files": [],
"found_files": [],
"has_content_list": False,
"has_raw_docs": False,
"has_images": False,
"has_metadata": False,
"has_numbered_items": False,
}
if not kb_path.exists():
@@ -216,9 +213,6 @@ def validate_kb(kb_path: Path) -> dict:
result["found_files"] = found
# Check optional directories
content_list_dir = kb_path / "content_list"
result["has_content_list"] = content_list_dir.exists() and any(content_list_dir.glob("*.json"))
raw_dir = kb_path / "raw"
result["has_raw_docs"] = raw_dir.exists() and any(raw_dir.iterdir())
@@ -226,8 +220,6 @@ def validate_kb(kb_path: Path) -> dict:
result["has_images"] = images_dir.exists() and any(images_dir.iterdir())
result["has_metadata"] = (kb_path / "metadata.json").exists()
result["has_numbered_items"] = (kb_path / "numbered_items.json").exists()
return result
@@ -349,21 +341,6 @@ def register_kb(
return True
async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:
"""
Extract numbered items from content_list files.
Args:
kb_name: Knowledge base name
kb_base_dir: Base directory for knowledge bases
Returns:
True if successful
"""
_ = (kb_name, kb_base_dir)
print(" ⚠️ Numbered item extraction is deprecated and has been removed. Skipping.")
return False
async def test_kb_search(kb_name: str, query: str = "What is this knowledge base about?") -> bool:
"""
@@ -411,7 +388,6 @@ async def migrate_kb(
target_base_dir: str | None = None,
kb_name: str | None = None,
run_test: bool = False,
extract_items: bool = False,
validate_only: bool = False,
force: bool = False,
) -> bool:
@@ -423,7 +399,6 @@ async def migrate_kb(
target_base_dir: Target base directory (default: data/knowledge_bases)
kb_name: Name for the migrated KB (default: source directory name)
run_test: Run a test query after migration
extract_items: Extract numbered items if content_list exists
validate_only: Only validate, don't migrate
force: Overwrite existing KB if exists
@@ -465,7 +440,6 @@ async def migrate_kb(
print(f" Provider: {validation['provider']}")
print(f" Needs reindex: {'Yes' if validation['needs_reindex'] else 'No'}")
print(f" Found files: {', '.join(validation['found_files'][:5])}...")
print(f" Has content_list: {'Yes' if validation['has_content_list'] else 'No'}")
print(f" Has raw docs: {'Yes' if validation['has_raw_docs'] else 'No'}")
print(f" Has images: {'Yes' if validation['has_images'] else 'No'}")
print()
@@ -506,18 +480,9 @@ async def migrate_kb(
)
print()
# Step 4: Extract numbered items (optional)
if extract_items and validation["has_content_list"]:
print("Step 4: Extracting numbered items...")
await extract_numbered_items(kb_name, target_base)
print()
elif extract_items:
print("Step 4: Skipping numbered items extraction (no content_list)")
print()
# Step 5: Test search (optional)
# Step 4: Test search (optional)
if run_test:
print("Step 5: Testing knowledge base...")
print("Step 4: Testing knowledge base...")
await test_kb_search(kb_name)
print()
@@ -549,8 +514,6 @@ Examples:
# Migrate and run test query
python scripts/migrate_kb.py /path/to/kb --test
# Migrate and extract numbered items
python scripts/migrate_kb.py /path/to/kb --extract-items
# Validate only (don't migrate)
python scripts/migrate_kb.py /path/to/kb --validate-only
@@ -572,12 +535,6 @@ Examples:
parser.add_argument("--test", action="store_true", help="Run a test query after migration")
parser.add_argument(
"--extract-items",
action="store_true",
help="Extract numbered items from content_list (requires LLM API)",
)
parser.add_argument(
"--validate-only",
action="store_true",
@@ -597,7 +554,6 @@ Examples:
target_base_dir=args.target_dir,
kb_name=args.name,
run_test=args.test,
extract_items=args.extract_items,
validate_only=args.validate_only,
force=args.force,
)
@@ -25,144 +25,6 @@ async def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asynci
await asyncio.sleep(0)
return events, consumer # type: ignore[return-value]
@pytest.mark.asyncio
async def test_native_tool_loop_executes_parallel_tool_calls(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
"deeptutor.agents.chat.agentic_pipeline.get_llm_config",
lambda: SimpleNamespace(
binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
),
)
class FakeRegistry:
def __init__(self) -> None:
self.inflight = 0
self.max_inflight = 0
def build_openai_schemas(self, _enabled_tools):
return [{"type": "function", "function": {"name": "web_search"}}]
def build_prompt_text(self, enabled_tools, **_kwargs):
return "\n".join(enabled_tools)
def get_enabled(self, selected):
return [SimpleNamespace(name=name) for name in selected]
async def execute(self, name: str, **kwargs):
self.inflight += 1
self.max_inflight = max(self.max_inflight, self.inflight)
await asyncio.sleep(0.05)
self.inflight -= 1
return ToolResult(
content=f"{name} => {kwargs.get('query', '') or kwargs.get('context', '')}".strip(),
sources=[{"tool": name}],
metadata={"tool": name},
success=True,
)
registry = FakeRegistry()
monkeypatch.setattr(
"deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry
)
pipeline = AgenticChatPipeline(language="en")
pipeline.registry = registry
class FakeCreate:
def __init__(self) -> None:
self.calls = 0
async def __call__(self, **_kwargs):
self.calls += 1
if self.calls == 1:
return SimpleNamespace(
choices=[
SimpleNamespace(
message=SimpleNamespace(
content="",
tool_calls=[
SimpleNamespace(
id="tool-call-1",
function=SimpleNamespace(
name="web_search",
arguments='{"query":"first"}',
),
),
SimpleNamespace(
id="tool-call-2",
function=SimpleNamespace(
name="reason",
arguments='{"context":"second"}',
),
),
],
)
)
]
)
return SimpleNamespace(
choices=[
SimpleNamespace(
message=SimpleNamespace(
content="No more tools needed.",
tool_calls=[],
)
)
]
)
fake_create = FakeCreate()
monkeypatch.setattr(
pipeline,
"_build_openai_client",
lambda: SimpleNamespace(
chat=SimpleNamespace(
completions=SimpleNamespace(create=fake_create),
)
),
)
bus = StreamBus()
events, consumer = await _collect_bus_events(bus)
context = UnifiedContext(
session_id="session-1",
user_message="compare two sources",
enabled_tools=["web_search", "reason"],
language="en",
metadata={"turn_id": "turn-1"},
)
traces = await pipeline._run_native_tool_loop(
context=context,
enabled_tools=["web_search", "reason"],
thinking_text="Need outside evidence and a reasoning cross-check.",
stream=bus,
)
await asyncio.sleep(0)
await bus.close()
await consumer
assert fake_create.calls == 1
assert registry.max_inflight >= 2
assert [trace.name for trace in traces] == ["web_search", "reason"]
tool_result_events = [event for event in events if event.type.value == "tool_result"]
assert len(tool_result_events) == 2
assert tool_result_events[0].metadata["tool_call_id"] == "tool-call-1"
assert tool_result_events[1].metadata["tool_call_id"] == "tool-call-2"
assert tool_result_events[0].metadata["tool_index"] == 0
assert tool_result_events[1].metadata["tool_index"] == 1
acting_thinking_events = [
event
for event in events
if event.type == StreamEventType.THINKING and event.stage == "acting"
]
assert acting_thinking_events == []
@pytest.mark.asyncio
async def test_execute_tool_call_streams_retrieve_progress_for_rag(
monkeypatch: pytest.MonkeyPatch,
@@ -223,9 +85,7 @@ async def test_execute_tool_call_streams_retrieve_progress_for_rag(
retrieve_meta = pipeline._retrieve_trace_metadata(
trace_meta,
context=context,
tool_call_id="tool-call-rag",
tool_name="rag",
tool_index=0,
tool_args={"query": "transformer model", "kb_name": "demo-kb"},
)
@@ -329,222 +189,3 @@ def test_build_llm_tool_schemas_kb_name_enum_matches_attached() -> None:
assert parameters["required"] == ["query", "kb_name"]
assert parameters["additionalProperties"] is False
@pytest.mark.asyncio
async def test_native_rag_call_forwards_llm_chosen_kb_name(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
"deeptutor.agents.chat.agentic_pipeline.get_llm_config",
lambda: SimpleNamespace(
binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
),
)
class FakeRegistry:
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
def build_openai_schemas(self, _enabled_tools):
return [
{
"type": "function",
"function": {
"name": "rag",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"kb_name": {"type": "string"},
},
"required": ["query", "kb_name"],
},
},
}
]
def build_prompt_text(self, enabled_tools, **_kwargs):
return "\n".join(enabled_tools)
async def execute(self, name: str, **kwargs):
self.calls.append({"name": name, **kwargs})
return ToolResult(
content="grounded result",
sources=[{"tool": name, "kb_name": kwargs.get("kb_name")}],
metadata={"tool": name},
success=True,
)
registry = FakeRegistry()
monkeypatch.setattr(
"deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry
)
pipeline = AgenticChatPipeline(language="en")
pipeline.registry = registry
class FakeCreate:
def __init__(self) -> None:
self.tools: list[dict[str, Any]] = []
async def __call__(self, **kwargs):
self.tools = kwargs.get("tools") or []
return SimpleNamespace(
choices=[
SimpleNamespace(
message=SimpleNamespace(
content="",
tool_calls=[
SimpleNamespace(
id="tool-call-rag",
function=SimpleNamespace(
name="rag",
arguments='{"query":"chapter summary","kb_name":"current-kb"}',
),
)
],
)
)
]
)
fake_create = FakeCreate()
monkeypatch.setattr(
pipeline,
"_build_openai_client",
lambda: SimpleNamespace(
chat=SimpleNamespace(completions=SimpleNamespace(create=fake_create)),
),
)
bus = StreamBus()
events, consumer = await _collect_bus_events(bus)
context = UnifiedContext(
session_id="session-1",
user_message="summarize chapter 3",
enabled_tools=["rag"],
knowledge_bases=["current-kb"],
language="en",
metadata={"turn_id": "turn-1"},
)
traces = await pipeline._run_native_tool_loop(
context=context,
enabled_tools=["rag"],
thinking_text="RAG would help.",
stream=bus,
)
await asyncio.sleep(0)
await bus.close()
await consumer
rag_properties = fake_create.tools[0]["function"]["parameters"]["properties"]
assert rag_properties["kb_name"]["enum"] == ["current-kb"]
assert registry.calls[0]["query"] == "chapter summary"
assert registry.calls[0]["kb_name"] == "current-kb"
assert traces[0].arguments["kb_name"] == "current-kb"
tool_call_events = [event for event in events if event.type == StreamEventType.TOOL_CALL]
assert tool_call_events[0].metadata["tool_name"] == "rag"
assert tool_call_events[0].content
@pytest.mark.asyncio
async def test_native_tool_loop_caps_parallel_tool_calls_at_eight(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
"deeptutor.agents.chat.agentic_pipeline.get_llm_config",
lambda: SimpleNamespace(
binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
),
)
class FakeRegistry:
def __init__(self) -> None:
self.calls: list[str] = []
def build_openai_schemas(self, _enabled_tools):
return [{"type": "function", "function": {"name": "web_search"}}]
def build_prompt_text(self, enabled_tools, **_kwargs):
return "\n".join(enabled_tools)
def get_enabled(self, selected):
return [SimpleNamespace(name=name) for name in selected]
async def execute(self, name: str, **kwargs):
self.calls.append(f"{name}:{kwargs.get('query', '')}")
return ToolResult(
content=f"{name} => {kwargs.get('query', '')}",
sources=[{"tool": name}],
metadata={"tool": name},
success=True,
)
registry = FakeRegistry()
monkeypatch.setattr(
"deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry
)
pipeline = AgenticChatPipeline(language="en")
pipeline.registry = registry
tool_calls = [
SimpleNamespace(
id=f"tool-call-{index}",
function=SimpleNamespace(
name="web_search",
arguments=f'{{"query":"q{index}"}}',
),
)
for index in range(10)
]
async def fake_create(**_kwargs):
return SimpleNamespace(
choices=[
SimpleNamespace(
message=SimpleNamespace(
content="Use multiple tools in parallel.",
tool_calls=tool_calls,
)
)
]
)
monkeypatch.setattr(
pipeline,
"_build_openai_client",
lambda: SimpleNamespace(
chat=SimpleNamespace(
completions=SimpleNamespace(create=fake_create),
)
),
)
bus = StreamBus()
events, consumer = await _collect_bus_events(bus)
context = UnifiedContext(
session_id="session-1",
user_message="collect broad evidence",
enabled_tools=["web_search"],
language="en",
metadata={"turn_id": "turn-1"},
)
traces = await pipeline._run_native_tool_loop(
context=context,
enabled_tools=["web_search"],
thinking_text="Need multiple web sources.",
stream=bus,
)
await asyncio.sleep(0)
await bus.close()
await consumer
assert len(traces) == 8
assert len(registry.calls) == 8
assert registry.calls[-1] == "web_search:q7"
progress_events = [event.content for event in events if event.type == StreamEventType.PROGRESS]
assert any("8 can run in parallel" in content for content in progress_events)
+12 -4
View File
@@ -36,13 +36,21 @@ def test_agentic_chat_final_prompt_uses_selected_language(
lambda: FakeRegistry(),
)
zh_prompt = AgenticChatPipeline(language="zh")._responding_system_prompt([])
en_prompt = AgenticChatPipeline(language="en")._responding_system_prompt([])
from deeptutor.core.context import UnifiedContext
assert "你是 DeepTutor 的最终回答阶段" in zh_prompt
ctx = UnifiedContext()
zh_prompt = AgenticChatPipeline(language="zh")._build_system_prompt([], ctx)
en_prompt = AgenticChatPipeline(language="en")._build_system_prompt([], ctx)
# Single-loop pipeline merged the four stage prompts into one chat
# persona; the language directive (append_language_directive) still
# runs at the end, so per-language imperatives must surface.
assert "请严格使用中文" in zh_prompt
assert "You are DeepTutor's final response stage" in en_prompt
assert "Write ALL reader-facing text" in en_prompt
# Persona phrasing differs by language so the prompts are not just
# English text with a Chinese tail appended.
assert "你是 DeepTutor" in zh_prompt
assert "You are DeepTutor" in en_prompt
def test_legacy_chat_agent_system_prompt_uses_selected_language() -> None:
+4 -1
View File
@@ -102,7 +102,7 @@ def test_rag_providers_returns_llamaindex_only() -> None:
{
"id": "llamaindex",
"name": "LlamaIndex",
"description": "Pure vector retrieval, fastest processing speed.",
"description": "LlamaIndex retrieval with hybrid BM25/vector fusion when available.",
}
]
}
@@ -119,9 +119,12 @@ def test_supported_file_types_returns_upload_policy() -> None:
assert ".xlsx" in payload["extensions"]
assert ".pptx" in payload["extensions"]
assert ".md" in payload["extensions"]
assert ".png" in payload["extensions"]
assert payload["max_file_size_bytes"] > payload["max_pdf_size_bytes"] > 0
assert ".pdf" in payload["accept"]
assert ".docx" in payload["accept"]
assert ".png" in payload["accept"]
assert "image/png" in payload["accept"]
def test_create_kb_does_not_require_llm_precheck(monkeypatch, tmp_path: Path) -> None:
+15 -2
View File
@@ -98,6 +98,7 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
async def handle(self, context):
captured["user_message"] = context.user_message
captured["metadata"] = context.metadata
captured["source_manifest"] = context.source_manifest
yield StreamEvent(
type=StreamEventType.CONTENT,
source="chat",
@@ -164,8 +165,20 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
assert detail["messages"][0]["metadata"]["request_snapshot"]["bookReferences"] == [
{"book_id": "book-1", "page_ids": ["page-1"]}
]
assert "[Book Context]" in str(captured["user_message"])
assert "A selected page." in str(captured["user_message"])
# Chat capability now routes attached sources through the manifest +
# ``read_source`` tool instead of inlining ``[Book Context]`` into the
# user message. The raw user message stays raw; the book payload
# surfaces in ``context.source_manifest`` and ``metadata.source_index``.
assert str(captured["user_message"]) == "hello, i'm frank"
manifest = str(captured.get("source_manifest") or "")
assert "[Attached Sources]" in manifest
# Book source id is now per-book (``bk-{book_id}``) so multi-book
# sessions can read_source each independently. The mocked book has id
# "book-1".
assert "bk-book-1" in manifest
source_index = (captured.get("metadata") or {}).get("source_index") or {}
assert "bk-book-1" in source_index
assert "A selected page." in source_index["bk-book-1"]
assert captured["metadata"] and captured["metadata"]["book_references"] == [
{"book_id": "book-1", "page_ids": ["page-1"]}
]
+2 -4
View File
@@ -62,9 +62,8 @@ class TestUnifiedContext:
assert ctx.attachments == []
assert ctx.config_overrides == {}
assert ctx.language == "en"
assert ctx.notebook_context == ""
assert ctx.history_context == ""
assert ctx.memory_context == ""
assert ctx.source_manifest == ""
assert ctx.metadata == {}
def test_mutable_defaults_are_independent(self) -> None:
@@ -85,9 +84,8 @@ class TestUnifiedContext:
attachments=[att],
config_overrides={"temperature": 0.5},
language="zh",
notebook_context="some notes",
history_context="prior session",
memory_context="user preference",
source_manifest="id=nb-1 name=\"Lecture\" type=notebook preview=\"...\"",
metadata={"turn_id": "t1"},
)
assert ctx.session_id == "s1"
@@ -101,41 +101,41 @@ class TestGetChatParams:
assert params["react_fallback"]["max_tokens"] == 2500
class TestChatLimitsDataclass:
"""Verify _ChatLimits.from_config gracefully handles malformed input."""
class TestReadIntHelper:
"""Verify ``_read_int`` gracefully resolves the two chat token budgets
the single-loop pipeline still uses (``responding`` and ``answer_now``).
def test_from_config_with_empty_dict_uses_fallbacks(self):
from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
The legacy four-stage budgets (``thinking``/``acting``/``observing``/
``react_fallback``) are no longer consumed by the pipeline — they remain
valid keys in ``agents.yaml`` for forward/backward compatibility but
have no behavioral effect here.
"""
limits = _ChatLimits.from_config({})
assert limits.responding == 8000
assert limits.answer_now == 8000
assert limits.thinking == 2000
assert limits.observing == 2000
assert limits.acting == 2000
assert limits.react_fallback == 1500
def test_empty_dict_falls_back_to_default(self):
from deeptutor.agents.chat.agentic_pipeline import _read_int
def test_from_config_with_chat_params_defaults(self):
from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
assert _read_int({}, key="max_tokens", default=8000) == 8000
limits = _ChatLimits.from_config(DEFAULT_CHAT_PARAMS)
assert limits.responding == 8000
assert limits.react_fallback == 1500
def test_resolves_nested_max_tokens(self):
from deeptutor.agents.chat.agentic_pipeline import _read_int
def test_from_config_coerces_string_numbers(self):
from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
cfg = {"max_tokens": 5000}
assert _read_int(cfg, key="max_tokens", default=8000) == 5000
limits = _ChatLimits.from_config({"responding": {"max_tokens": "5000"}})
assert limits.responding == 5000
def test_coerces_string_numbers(self):
from deeptutor.agents.chat.agentic_pipeline import _read_int
def test_from_config_falls_back_on_garbage(self):
from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
cfg = {"max_tokens": "5000"}
assert _read_int(cfg, key="max_tokens", default=8000) == 5000
limits = _ChatLimits.from_config({"responding": {"max_tokens": "abc"}})
assert limits.responding == 8000
def test_falls_back_on_garbage(self):
from deeptutor.agents.chat.agentic_pipeline import _read_int
def test_from_config_handles_non_dict_stage_value(self):
from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
cfg = {"max_tokens": "abc"}
assert _read_int(cfg, key="max_tokens", default=8000) == 8000
limits = _ChatLimits.from_config({"responding": 12345})
assert limits.responding == 8000
def test_non_dict_input_falls_back(self):
from deeptutor.agents.chat.agentic_pipeline import _read_int
assert _read_int(12345, key="max_tokens", default=8000) == 8000
assert _read_int(None, key="max_tokens", default=8000) == 8000
@@ -56,3 +56,16 @@ def test_detect_context_window_uses_runtime_default_when_metadata_missing(
assert result.context_window == 20000
assert result.source == "default"
def test_detect_context_window_uses_known_model_metadata_when_provider_omits_window(
monkeypatch,
) -> None:
monkeypatch.setattr(
"deeptutor.services.config.context_window_detection._detect_from_models_endpoint",
_metadata_none,
)
result = asyncio.run(detect_context_window(_config(model="deepseek-v4-flash")))
assert result.context_window == 1_000_000
assert result.source == "known_model"
+53 -11
View File
@@ -173,6 +173,44 @@ class TestLlmProbeUsesAgentsYaml:
or captured_kwargs.get("max_completion_tokens") == 4096
)
@pytest.mark.asyncio
async def test_probe_passes_runtime_api_version_and_reasoning_effort(
self, monkeypatch
):
from deeptutor.services import llm as llm_module
from deeptutor.services.config import test_runner as test_runner_module
from deeptutor.services.config.test_runner import ConfigTestRunner, TestRun
captured_kwargs: dict[str, Any] = {}
async def _fake_llm_complete(**kwargs):
captured_kwargs.update(kwargs)
return "OK I am a reasoning model"
monkeypatch.setattr(
test_runner_module,
"resolve_llm_runtime_config",
lambda catalog: _stub_resolved_llm(
api_version="2026-05-01",
reasoning_effort="high",
),
)
monkeypatch.setattr(
test_runner_module,
"detect_context_window",
_stub_context_window_detection,
)
monkeypatch.setattr(llm_module, "get_token_limit_kwargs", _real_get_token_limit_kwargs)
monkeypatch.setattr(llm_module, "complete", _fake_llm_complete)
monkeypatch.setattr(llm_module, "clear_llm_config_cache", lambda: None)
runner = ConfigTestRunner()
run = TestRun(id="test-llm-probe-runtime-fields", service="llm")
await runner._test_llm(run, catalog={})
assert captured_kwargs["api_version"] == "2026-05-01"
assert captured_kwargs["reasoning_effort"] == "high"
@pytest.mark.asyncio
async def test_probe_persists_detected_context_window_when_catalog_present(
self, tmp_path, monkeypatch
@@ -259,21 +297,25 @@ class TestLlmProbeUsesAgentsYaml:
# ---------------------------------------------------------------------------
def _stub_resolved_llm():
def _stub_resolved_llm(**overrides: Any):
"""Return a minimal resolved LLM config stub."""
from deeptutor.services.config.provider_runtime import ResolvedLLMConfig
values = {
"model": "gpt-4o-mini",
"api_key": "sk-test",
"base_url": "https://api.example.com/v1",
"effective_url": "https://api.example.com/v1",
"binding": "openai",
"provider_name": "openai",
"provider_mode": "standard",
"api_version": "",
"extra_headers": {},
"reasoning_effort": None,
}
values.update(overrides)
return ResolvedLLMConfig(
model="gpt-4o-mini",
api_key="sk-test",
base_url="https://api.example.com/v1",
effective_url="https://api.example.com/v1",
binding="openai",
provider_name="openai",
provider_mode="standard",
api_version="",
extra_headers={},
reasoning_effort=None,
**values,
)
@@ -108,6 +108,32 @@ async def test_overwrite_when_catalog_dim_disagrees_unknown_model() -> None:
assert not any(e.get("active_dim_source") for e in warnings)
@pytest.mark.asyncio
async def test_non_numeric_catalog_dim_does_not_block_probe() -> None:
"""Bad manual catalog values should not stop the smoke probe from detecting
and persisting the provider's actual dimension."""
runner = ConfigTestRunner()
run = _make_run()
catalog: dict[str, Any] = {}
model: dict[str, Any] = {"dimension": "not-a-number"}
fake_client = MagicMock()
fake_client.embed = AsyncMock(return_value=[[0.5] * 768, [0.6] * 768])
with (
patch(
"deeptutor.services.config.test_runner.resolve_embedding_runtime_config",
return_value=_resolved_stub(dim=0),
),
patch("deeptutor.services.embedding.client.EmbeddingClient", return_value=fake_client),
patch.object(runner, "_persist_embedding_dimension", return_value=catalog) as persist_mock,
):
await runner._test_embedding(run, model, catalog)
persist_mock.assert_called_once()
assert persist_mock.call_args.args[2] == 768
@pytest.mark.asyncio
async def test_empty_vector_still_fatal() -> None:
runner = ConfigTestRunner()
@@ -36,12 +36,18 @@ class _FakeAdapter:
)()
def _build_config(binding: str, *, send_dimensions: bool | None = None) -> EmbeddingConfig:
def _build_config(
binding: str,
*,
model: str = "text-embedding-3-small",
base_url: str = "https://api.openai.com/v1/embeddings",
send_dimensions: bool | None = None,
) -> EmbeddingConfig:
return EmbeddingConfig(
model="text-embedding-3-small",
model=model,
api_key="sk-test",
base_url="https://api.openai.com/v1/embeddings",
effective_url="https://api.openai.com/v1/embeddings",
base_url=base_url,
effective_url=base_url,
binding=binding,
provider_name=binding,
provider_mode="standard",
@@ -217,3 +223,31 @@ def test_every_registered_provider_has_adapter() -> None:
for name in EMBEDDING_PROVIDERS:
cls = _resolve_adapter_class(name)
assert cls is not None, f"Provider '{name}' has no adapter"
def test_embedding_client_multimodal_detection_uses_model_level_metadata() -> None:
text_model = EmbeddingClient(
_build_config(
"siliconflow",
model="Qwen/Qwen3-Embedding-8B",
base_url="https://api.siliconflow.cn/v1/embeddings",
)
)
vision_model = EmbeddingClient(
_build_config(
"siliconflow",
model="Qwen/Qwen3-VL-Embedding-8B",
base_url="https://api.siliconflow.cn/v1/embeddings",
)
)
cohere_v3 = EmbeddingClient(
_build_config(
"cohere",
model="embed-multilingual-v3.0",
base_url="https://api.cohere.com/v2/embed",
)
)
assert text_model.supports_multimodal_contents() is False
assert vision_model.supports_multimodal_contents() is True
assert cohere_v3.supports_multimodal_contents() is False
@@ -10,6 +10,7 @@ import pytest
from deeptutor.services.embedding.adapters.base import EmbeddingRequest
from deeptutor.services.embedding.adapters.cohere import CohereEmbeddingAdapter
from deeptutor.services.embedding.adapters.jina import JinaEmbeddingAdapter
from deeptutor.services.embedding.adapters.ollama import OllamaEmbeddingAdapter
from deeptutor.services.embedding.adapters.openai_compatible import (
OpenAICompatibleEmbeddingAdapter,
@@ -57,6 +58,27 @@ async def test_openai_compat_passes_contents_as_input(monkeypatch: pytest.Monkey
assert captured["json"]["input"] == contents
@pytest.mark.asyncio
async def test_openai_compat_rejects_contents_for_text_embedding_model() -> None:
adapter = OpenAICompatibleEmbeddingAdapter(
{
"api_key": "sk",
"base_url": "https://api.openai.com/v1/embeddings",
"model": "text-embedding-3-small",
"request_timeout": 5,
}
)
with pytest.raises(ValueError, match="does not support multimodal"):
await adapter.embed(
EmbeddingRequest(
texts=[],
model="text-embedding-3-small",
contents=[{"image": "data:image/png;base64,XXX"}],
)
)
@pytest.mark.asyncio
async def test_ollama_rejects_multimodal_contents() -> None:
adapter = OllamaEmbeddingAdapter(
@@ -77,6 +99,26 @@ async def test_ollama_rejects_multimodal_contents() -> None:
)
@pytest.mark.asyncio
async def test_jina_v3_rejects_multimodal_contents() -> None:
adapter = JinaEmbeddingAdapter(
{
"api_key": "jina-test",
"base_url": "https://api.jina.ai/v1/embeddings",
"model": "jina-embeddings-v3",
"request_timeout": 5,
}
)
with pytest.raises(ValueError, match="does not support multimodal"):
await adapter.embed(
EmbeddingRequest(
texts=[],
model="jina-embeddings-v3",
contents=[{"image": "data:image/png;base64,XXX"}],
)
)
@pytest.mark.asyncio
async def test_cohere_v2_translates_contents_to_inputs(monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, Any] = {}
@@ -110,3 +152,34 @@ async def test_cohere_v2_translates_contents_to_inputs(monkeypatch: pytest.Monke
assert inputs[1] == {
"content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,XXX"}}]
}
def test_model_info_reports_multimodal_at_model_level() -> None:
assert CohereEmbeddingAdapter(
{
"api_key": "co-test",
"base_url": "https://api.cohere.com/v2/embed",
"model": "embed-v4.0",
}
).get_model_info()["multimodal"] is True
assert CohereEmbeddingAdapter(
{
"api_key": "co-test",
"base_url": "https://api.cohere.com/v2/embed",
"model": "embed-multilingual-v3.0",
}
).get_model_info()["multimodal"] is False
assert JinaEmbeddingAdapter(
{
"api_key": "jina-test",
"base_url": "https://api.jina.ai/v1/embeddings",
"model": "jina-embeddings-v4",
}
).get_model_info()["multimodal"] is True
assert OpenAICompatibleEmbeddingAdapter(
{
"api_key": "sk-sf",
"base_url": "https://api.siliconflow.cn/v1/embeddings",
"model": "Qwen/Qwen3-Embedding-8B",
}
).get_model_info()["multimodal"] is False
+3
View File
@@ -60,3 +60,6 @@ def test_moonshot_vision_models() -> None:
def test_qwen_model_override_enables_vision() -> None:
assert supports_vision("dashscope", "qwen-vl-plus") is True
assert supports_vision("openai", "qwen2.5-vl-72b-instruct") is True
assert supports_vision("openai", "Qwen/Qwen3-VL-235B-A22B-Instruct") is True
assert supports_vision("openai", "qwen-plus") is False
assert supports_vision("openai", "Qwen/Qwen3-235B-A22B-Instruct") is False
+9
View File
@@ -43,6 +43,15 @@ def test_client_complete_sync(monkeypatch: MonkeyPatch) -> None:
assert client.complete_sync("hello") == "ok"
def test_client_reports_multimodal_image_support() -> None:
assert LLMClient(
LLMConfig(model="gpt-4o", api_key="key", base_url="https://example.com")
).supports_multimodal_images() is True
assert LLMClient(
LLMConfig(model="gpt-3.5-turbo", api_key="key", base_url="https://example.com")
).supports_multimodal_images() is False
@pytest.mark.asyncio
async def test_client_complete_sync_running_loop() -> None:
"""complete_sync should raise when called from a running event loop."""
@@ -64,9 +64,14 @@ def test_parse_chunks_keeps_reasoning_content_out_of_visible_content(provider_cl
assert response.reasoning_content == "internal reasoning"
def _build_services_kwargs(provider_name: str, reasoning_effort: str) -> dict:
def _build_services_kwargs(
provider_name: str,
reasoning_effort: str | None,
*,
model: str = "deepseek-v4-pro",
) -> dict:
provider = ServicesOpenAICompatProvider.__new__(ServicesOpenAICompatProvider)
provider.default_model = "deepseek-v4-pro"
provider.default_model = model
provider._spec = find_service_provider(provider_name)
return provider._build_kwargs(
messages=[{"role": "user", "content": "hello"}],
@@ -79,9 +84,14 @@ def _build_services_kwargs(provider_name: str, reasoning_effort: str) -> dict:
)
def _build_tutorbot_kwargs(provider_name: str, reasoning_effort: str) -> dict:
def _build_tutorbot_kwargs(
provider_name: str,
reasoning_effort: str | None,
*,
model: str = "deepseek-v4-pro",
) -> dict:
provider = TutorBotOpenAICompatProvider.__new__(TutorBotOpenAICompatProvider)
provider.default_model = "deepseek-v4-pro"
provider.default_model = model
provider._spec = find_tutorbot_provider(provider_name)
return provider._build_kwargs(
messages=[{"role": "user", "content": "hello"}],
@@ -101,6 +111,24 @@ def test_services_provider_minimal_reasoning_uses_extra_body_only() -> None:
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
def test_services_deepseek_v4_flash_disables_thinking_by_default() -> None:
kwargs = _build_services_kwargs(
"deepseek",
None,
model="deepseek-v4-flash",
)
assert "reasoning_effort" not in kwargs
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
def test_services_deepseek_v4_pro_enables_thinking_by_default() -> None:
kwargs = _build_services_kwargs("deepseek", None)
assert kwargs["reasoning_effort"] == "high"
assert kwargs["extra_body"] == {"thinking": {"type": "enabled"}}
def test_services_dashscope_minimal_reasoning_uses_enable_thinking_only() -> None:
kwargs = _build_services_kwargs("dashscope", "minimal")
@@ -113,3 +141,14 @@ def test_tutorbot_provider_minimal_reasoning_uses_extra_body_only() -> None:
assert "reasoning_effort" not in kwargs
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
def test_tutorbot_deepseek_v4_flash_disables_thinking_by_default() -> None:
kwargs = _build_tutorbot_kwargs(
"deepseek",
None,
model="deepseek-v4-flash",
)
assert "reasoning_effort" not in kwargs
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
+8 -4
View File
@@ -66,12 +66,14 @@ class TestClassifyFiles:
)
assert cls.parser_files == [str(pdf), str(docx), str(xlsx), str(pptx)]
assert cls.text_files == [str(txt)]
assert cls.unsupported == [str(png)]
assert cls.image_files == [str(png)]
assert cls.unsupported == []
def test_empty_input_yields_empty_groups(self) -> None:
cls = FileTypeRouter.classify_files([])
assert cls.parser_files == []
assert cls.text_files == []
assert cls.image_files == []
assert cls.unsupported == []
@@ -84,6 +86,7 @@ class TestSupportedExtensionsAndGlobs:
assert ".pptx" in exts
assert ".md" in exts
assert ".txt" in exts
assert ".png" in exts
def test_glob_patterns_match_supported_extensions(self) -> None:
exts = FileTypeRouter.get_supported_extensions()
@@ -103,17 +106,18 @@ class TestSupportedExtensionsAndGlobs:
nested_upper.write_text("nested", encoding="utf-8")
deck = tmp_path / "DECK.PPTX"
deck.write_bytes(b"PK\x03\x04")
ignored = tmp_path / "image.PNG"
ignored.write_bytes(b"\x89PNG\r\n")
image = tmp_path / "image.PNG"
image.write_bytes(b"\x89PNG\r\n")
assert [path.name for path in FileTypeRouter.collect_supported_files(tmp_path)] == [
"DECK.PPTX",
"image.PNG",
"notes.md",
"REPORT.PDF",
]
assert [
path.name for path in FileTypeRouter.collect_supported_files(tmp_path, recursive=True)
] == ["DECK.PPTX", "README.MD", "notes.md", "REPORT.PDF"]
] == ["DECK.PPTX", "image.PNG", "README.MD", "notes.md", "REPORT.PDF"]
class TestQuickHelpers:
@@ -6,14 +6,11 @@ import asyncio
import io
from pathlib import Path
from docx import Document as DocxDocument
from openpyxl import Workbook
from pptx import Presentation
from pptx.util import Inches
import pytest
def _make_docx(paragraphs: list[str]) -> bytes:
DocxDocument = pytest.importorskip("docx").Document
doc = DocxDocument()
for paragraph in paragraphs:
doc.add_paragraph(paragraph)
@@ -23,6 +20,7 @@ def _make_docx(paragraphs: list[str]) -> bytes:
def _make_xlsx(rows: list[list[object]]) -> bytes:
Workbook = pytest.importorskip("openpyxl").Workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = "Data"
@@ -34,6 +32,8 @@ def _make_xlsx(rows: list[list[object]]) -> bytes:
def _make_pptx(texts: list[str]) -> bytes:
Presentation = pytest.importorskip("pptx").Presentation
Inches = pytest.importorskip("pptx.util").Inches
presentation = Presentation()
slide = presentation.slides.add_slide(presentation.slide_layouts[5])
for index, text in enumerate(texts):
@@ -77,3 +77,139 @@ def test_loader_extracts_chat_supported_office_files(tmp_path: Path) -> None:
assert "42" in all_text
assert "Slide title" in all_text
assert "Slide body" in all_text
def test_loader_skips_images_when_embedding_provider_is_text_only(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
pytest.importorskip("llama_index.core")
from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
image_path = tmp_path / "photo.png"
image_path.write_bytes(b"\x89PNG\r\n")
class _TextOnlyClient:
config = type("Config", (), {"binding": "openai", "model": "text-embedding-3-small"})()
def supports_multimodal_contents(self) -> bool:
return False
monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _TextOnlyClient())
documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
assert documents == []
def test_loader_embeds_images_when_embedding_provider_is_multimodal(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
pytest.importorskip("llama_index.core")
from llama_index.core.schema import ImageNode
from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
image_path = tmp_path / "photo.png"
image_path.write_bytes(b"\x89PNG\r\n")
captured: dict[str, object] = {}
class _MultimodalClient:
config = type("Config", (), {"binding": "siliconflow", "model": "qwen3-vl"})()
def supports_multimodal_contents(self) -> bool:
return True
async def embed_contents(self, contents):
captured["contents"] = contents
return [[0.1, 0.2, 0.3]]
class _VisionClient:
config = type("Config", (), {"binding": "openai", "model": "gpt-4o"})()
def supports_multimodal_images(self) -> bool:
return True
async def complete(self, prompt, **kwargs):
captured["llm_prompt"] = prompt
captured["llm_kwargs"] = kwargs
return "A logo image with visible HKU text."
monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _MultimodalClient())
monkeypatch.setattr(loader_module, "get_llm_client", lambda: _VisionClient())
documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
assert len(documents) == 1
assert isinstance(documents[0], ImageNode)
assert documents[0].embedding == [0.1, 0.2, 0.3]
assert documents[0].metadata["content_type"] == "image"
assert documents[0].metadata["image_description"] == "A logo image with visible HKU text."
assert "A logo image with visible HKU text." in documents[0].text
assert captured["contents"][0]["image"].startswith("data:image/png;base64,")
assert captured["llm_kwargs"]["image_mime_type"] == "image/png"
def test_loader_skips_images_when_llm_is_text_only(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
pytest.importorskip("llama_index.core")
from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
image_path = tmp_path / "photo.png"
image_path.write_bytes(b"\x89PNG\r\n")
class _MultimodalEmbeddingClient:
config = type("Config", (), {"binding": "siliconflow", "model": "qwen3-vl"})()
def supports_multimodal_contents(self) -> bool:
return True
class _TextOnlyLLMClient:
config = type("Config", (), {"binding": "openai", "model": "gpt-3.5-turbo"})()
def supports_multimodal_images(self) -> bool:
return False
monkeypatch.setattr(
loader_module, "get_embedding_client", lambda: _MultimodalEmbeddingClient()
)
monkeypatch.setattr(loader_module, "get_llm_client", lambda: _TextOnlyLLMClient())
documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
assert documents == []
def test_loader_logs_all_missing_multimodal_image_requirements(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
pytest.importorskip("llama_index.core")
from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
image_path = tmp_path / "photo.png"
image_path.write_bytes(b"\x89PNG\r\n")
class _TextOnlyEmbeddingClient:
config = type("Config", (), {"binding": "openai", "model": "text-embedding-3-small"})()
def supports_multimodal_contents(self) -> bool:
return False
class _TextOnlyLLMClient:
config = type("Config", (), {"binding": "openai", "model": "gpt-3.5-turbo"})()
def supports_multimodal_images(self) -> bool:
return False
monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _TextOnlyEmbeddingClient())
monkeypatch.setattr(loader_module, "get_llm_client", lambda: _TextOnlyLLMClient())
with caplog.at_level("WARNING"):
documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
assert documents == []
assert "requires both multimodal embedding and multimodal LLM support" in caplog.text
assert "embedding provider/model does not support multimodal contents" in caplog.text
assert "LLM provider/model does not support multimodal image input" in caplog.text
assert "text-embedding-3-small" in caplog.text
assert "gpt-3.5-turbo" in caplog.text
@@ -95,3 +95,128 @@ async def test_incremental_add_migrates_matching_legacy_index_to_flat_version(
assert captured["persist_dir"] == str(flat_storage_dir)
assert (flat_storage_dir / "docstore.json").exists()
assert json.loads((flat_storage_dir / "meta.json").read_text())["signature"] == sig.hash()
def test_hybrid_retriever_uses_official_query_fusion_when_bm25_available(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.rag.pipelines.llamaindex.config import RetrievalConfig
from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
captured: dict[str, object] = {}
class _FakeVectorRetriever:
def __init__(self, top_k: int) -> None:
self.top_k = top_k
class _FakeIndex:
def as_retriever(self, similarity_top_k: int):
captured["vector_top_k"] = similarity_top_k
return _FakeVectorRetriever(similarity_top_k)
class _FakeBM25:
@classmethod
def from_defaults(cls, index, similarity_top_k: int):
captured["bm25_top_k"] = similarity_top_k
return cls()
class _FakeFusion:
def __init__(self, retrievers, **kwargs):
captured["retrievers"] = retrievers
captured["kwargs"] = kwargs
monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: _FakeBM25)
monkeypatch.setattr(retriever_module, "QueryFusionRetriever", _FakeFusion)
retriever = retriever_module.build_retriever(
_FakeIndex(),
tmp_path,
top_k=4,
config=RetrievalConfig(profile="hybrid"),
)
assert isinstance(retriever, _FakeFusion)
assert captured["vector_top_k"] == 8
assert captured["bm25_top_k"] == 8
assert captured["kwargs"]["similarity_top_k"] == 4
assert captured["kwargs"]["num_queries"] == 1
def test_hybrid_retriever_falls_back_to_vector_when_bm25_missing(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.rag.pipelines.llamaindex.config import RetrievalConfig
from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
calls: list[int] = []
class _FakeIndex:
def as_retriever(self, similarity_top_k: int):
calls.append(similarity_top_k)
return {"top_k": similarity_top_k}
monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: None)
retriever = retriever_module.build_retriever(
_FakeIndex(),
tmp_path,
top_k=4,
config=RetrievalConfig(profile="hybrid"),
)
assert retriever == {"top_k": 4}
assert calls == [4]
def test_bm25_retriever_overrides_persisted_top_k(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
persist_dir = tmp_path / retriever_module.BM25_PERSIST_DIRNAME
persist_dir.mkdir()
class _FakeBM25:
def __init__(self) -> None:
self.similarity_top_k = 99
@classmethod
def from_persist_dir(cls, path: str):
assert path == str(persist_dir)
return cls()
monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: _FakeBM25)
retriever = retriever_module.build_bm25_retriever(object(), tmp_path, top_k=6)
assert retriever.similarity_top_k == 6
def test_bm25_persistence_drops_stale_sidecar_on_rebuild_failure(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
persist_dir = tmp_path / retriever_module.BM25_PERSIST_DIRNAME
persist_dir.mkdir()
(persist_dir / "old.json").write_text("stale", encoding="utf-8")
class _FailingBM25:
@classmethod
def from_defaults(cls, index, similarity_top_k: int):
raise RuntimeError("boom")
monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: _FailingBM25)
assert retriever_module.persist_bm25_retriever(object(), tmp_path, top_k=6) is False
assert not persist_dir.exists()
def test_retrieval_config_reads_profile_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
from deeptutor.services.rag.pipelines.llamaindex import config as config_module
monkeypatch.setenv("DEEPTUTOR_RAG_RETRIEVAL_PROFILE", " vector ")
config = config_module.retrieval_config_from_env()
assert config.profile == config_module.VECTOR_PROFILE
@@ -0,0 +1,241 @@
"""Unit tests for the cumulative source inventory used by the chat capability."""
from __future__ import annotations
from typing import Any
import pytest
from deeptutor.services.session.source_inventory import (
SourceEntry,
SourceInventory,
build_inventory,
render_manifest,
)
class FakeStore:
"""Minimal store fake covering the protocol methods source_inventory
actually calls: get_messages, get_session, get_messages_for_context,
get_notebook_entry. Tests inject the data they want via constructor."""
def __init__(
self,
*,
messages: list[dict[str, Any]] | None = None,
sessions: dict[str, dict[str, Any]] | None = None,
session_messages: dict[str, list[dict[str, Any]]] | None = None,
notebook_entries: dict[int, dict[str, Any]] | None = None,
) -> None:
self._messages = messages or []
self._sessions = sessions or {}
self._session_messages = session_messages or {}
self._notebook_entries = notebook_entries or {}
async def get_messages(self, session_id: str) -> list[dict[str, Any]]:
return self._messages
async def get_session(self, session_id: str) -> dict[str, Any] | None:
return self._sessions.get(session_id)
async def get_messages_for_context(
self, session_id: str, leaf_message_id: int | None = None
) -> list[dict[str, Any]]:
return self._session_messages.get(session_id, [])
async def get_notebook_entry(self, entry_id: int) -> dict[str, Any] | None:
return self._notebook_entries.get(entry_id)
# ---------------------------------------------------------------------------
# SourceInventory dataclass
# ---------------------------------------------------------------------------
def test_inventory_dedupe_fresh_wins() -> None:
inv = SourceInventory()
inv.add(SourceEntry(sid="at-foo", kind="attachment", name="old", full_text="old text", fresh=False, first_seen_turn=1))
inv.add(SourceEntry(sid="at-foo", kind="attachment", name="fresh", full_text="fresh text", fresh=True, first_seen_turn=2))
assert len(inv.entries) == 1
assert inv.entries[0].fresh is True
assert inv.entries[0].name == "fresh"
def test_inventory_skips_empty_text() -> None:
inv = SourceInventory()
inv.add(SourceEntry(sid="at-foo", kind="attachment", name="empty", full_text=" ", fresh=True, first_seen_turn=1))
assert inv.is_empty()
def test_inventory_preserves_insertion_order() -> None:
inv = SourceInventory()
inv.add(SourceEntry(sid="a", kind="attachment", name="A", full_text="A", fresh=True, first_seen_turn=1))
inv.add(SourceEntry(sid="b", kind="attachment", name="B", full_text="B", fresh=False, first_seen_turn=1))
inv.add(SourceEntry(sid="c", kind="notebook", name="C", full_text="C", fresh=True, first_seen_turn=1))
assert [e.sid for e in inv.entries] == ["a", "b", "c"]
# ---------------------------------------------------------------------------
# render_manifest
# ---------------------------------------------------------------------------
def test_render_manifest_empty() -> None:
text, idx = render_manifest(SourceInventory())
assert text == ""
assert idx == {}
def test_render_manifest_distinguishes_fresh_vs_historical() -> None:
inv = SourceInventory()
inv.add(SourceEntry(sid="at-fresh", kind="attachment", name="new.pdf", full_text="hello world", fresh=True, first_seen_turn=3))
inv.add(SourceEntry(sid="at-old", kind="attachment", name="old.pdf", full_text="x" * 5000, fresh=False, first_seen_turn=1))
text, idx = render_manifest(inv)
# Fresh row carries a preview field
assert "preview:" in text
assert "'hello world'" in text
# Historical row carries "previously attached (turn 1)" with no preview
assert "previously attached (turn 1)" in text
assert "size=" in text
# source_index has full text for both
assert idx["at-fresh"] == "hello world"
assert idx["at-old"] == "x" * 5000
# ---------------------------------------------------------------------------
# build_inventory
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_build_inventory_fresh_attachments_only() -> None:
store = FakeStore()
inv = await build_inventory(
store,
session_id="s1",
leaf_message_id=None,
current_turn_ordinal=1,
fresh_attachment_records=[
{"id": "a1", "type": "pdf", "filename": "x.pdf", "extracted_text": "PDF body"},
{"id": "img", "type": "image", "filename": "p.png", "extracted_text": ""}, # skipped
],
fresh_notebook_records=[],
fresh_book_context_text="",
fresh_book_references=[],
fresh_history_session_ids=[],
fresh_question_entry_ids=[],
)
assert [e.sid for e in inv.entries] == ["at-a1"]
assert inv.entries[0].fresh is True
@pytest.mark.asyncio
async def test_build_inventory_historical_attachment_visible_to_next_turn() -> None:
"""Attachment uploaded in turn 1 must appear as 'previously attached
(turn 1)' in turn 2's manifest, even though turn 2's payload is empty."""
past = [
{
"id": 1,
"role": "user",
"content": "first message",
"parent_message_id": None,
"attachments": [
{"id": "att-1", "filename": "year1-1.pdf", "extracted_text": "lecture notes", "mime_type": "application/pdf"}
],
"metadata": {"request_snapshot": {}},
},
{
"id": 2,
"role": "assistant",
"content": "ok",
"parent_message_id": 1,
"attachments": [],
"metadata": {},
},
]
store = FakeStore(messages=past)
inv = await build_inventory(
store,
session_id="s1",
leaf_message_id=None, # legacy linear; lineage walker returns all
current_turn_ordinal=2,
fresh_attachment_records=[],
fresh_notebook_records=[],
fresh_book_context_text="",
fresh_book_references=[],
fresh_history_session_ids=[],
fresh_question_entry_ids=[],
)
assert [e.sid for e in inv.entries] == ["at-att-1"]
e = inv.entries[0]
assert e.fresh is False
assert e.first_seen_turn == 1
assert e.full_text == "lecture notes"
@pytest.mark.asyncio
async def test_build_inventory_branch_isolated() -> None:
"""Branch B should not see attachments uploaded in a sibling branch A."""
# Layout:
# 1 (user, root) → 2 (assistant) → 3 (user, branch A, attaches X.pdf)
# → 4 (user, branch B, attaches Y.pdf)
# When we ask for branch B (leaf=4), only 1, 2, 4 are in lineage.
msgs = [
{"id": 1, "role": "user", "content": "q1", "parent_message_id": None,
"attachments": [], "metadata": {"request_snapshot": {}}},
{"id": 2, "role": "assistant", "content": "a1", "parent_message_id": 1,
"attachments": [], "metadata": {}},
{"id": 3, "role": "user", "content": "branch A", "parent_message_id": 2,
"attachments": [{"id": "X", "filename": "X.pdf", "extracted_text": "branchA only", "mime_type": "application/pdf"}],
"metadata": {"request_snapshot": {}}},
{"id": 4, "role": "user", "content": "branch B", "parent_message_id": 2,
"attachments": [{"id": "Y", "filename": "Y.pdf", "extracted_text": "branchB only", "mime_type": "application/pdf"}],
"metadata": {"request_snapshot": {}}},
]
store = FakeStore(messages=msgs)
# Render branch B's inventory (leaf=4) — should see Y, not X.
inv = await build_inventory(
store,
session_id="s1",
leaf_message_id=4,
current_turn_ordinal=3,
fresh_attachment_records=[],
fresh_notebook_records=[],
fresh_book_context_text="",
fresh_book_references=[],
fresh_history_session_ids=[],
fresh_question_entry_ids=[],
)
sids = [e.sid for e in inv.entries]
assert "at-Y" in sids, sids
assert "at-X" not in sids, sids
@pytest.mark.asyncio
async def test_build_inventory_fresh_shadows_historical_on_same_sid() -> None:
"""If a notebook record is referenced both in a past turn and this
turn, the manifest shows it as fresh (with preview), not historical."""
msgs = [
{"id": 1, "role": "user", "content": "earlier",
"parent_message_id": None, "attachments": [],
"metadata": {"request_snapshot": {}}},
]
store = FakeStore(messages=msgs)
# Fresh record matching what historical *would have* added if it had
# one — but historical lineage has empty snap, so only fresh is added.
inv = await build_inventory(
store,
session_id="s1",
leaf_message_id=None,
current_turn_ordinal=2,
fresh_attachment_records=[
{"id": "att-1", "filename": "f.pdf", "extracted_text": "fresh body", "mime_type": "application/pdf"}
],
fresh_notebook_records=[],
fresh_book_context_text="",
fresh_book_references=[],
fresh_history_session_ids=[],
fresh_question_entry_ids=[],
)
assert inv.entries[0].fresh is True
assert inv.entries[0].full_text == "fresh body"
+10
View File
@@ -42,3 +42,13 @@ def test_validate_upload_safety_custom_policy_allows_supported_code_mimes() -> N
)
assert safe_name == "solver.py"
def test_validate_upload_safety_custom_policy_allows_images() -> None:
safe_name = DocumentValidator.validate_upload_safety(
"diagram.PNG",
1024,
allowed_extensions=FileTypeRouter.get_supported_extensions(),
)
assert safe_name == "diagram.png"
+10 -8
View File
@@ -3,9 +3,11 @@
import { Suspense, useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { useTranslation } from "react-i18next";
import { login, fetchAuthStatus, checkIsFirstUser } from "@/lib/auth";
function LoginPageContent() {
const { t } = useTranslation();
const router = useRouter();
const searchParams = useSearchParams();
const next = searchParams.get("next") ?? "/";
@@ -41,7 +43,7 @@ function LoginPageContent() {
if (result.ok) {
router.replace(next);
} else {
setError(result.error ?? "Login failed");
setError(result.error ?? t("Login failed"));
setLoading(false);
}
}
@@ -54,14 +56,14 @@ function LoginPageContent() {
DeepTutor
</h1>
<p className="mt-1 text-sm text-[var(--muted-foreground)]">
Sign in to your account
{t("Sign in to your account")}
</p>
</div>
{/* Registered success notice */}
{registered && (
<div className="mb-4 rounded-lg border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-600 dark:text-green-400">
Account created! Sign in to continue.
{t("Account created! Sign in to continue.")}
</div>
)}
@@ -74,7 +76,7 @@ function LoginPageContent() {
htmlFor="username"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
Email
{t("Email")}
</label>
<input
id="username"
@@ -98,7 +100,7 @@ function LoginPageContent() {
htmlFor="password"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
Password
{t("Password")}
</label>
<input
id="password"
@@ -133,18 +135,18 @@ function LoginPageContent() {
disabled:opacity-50 disabled:cursor-not-allowed
transition-opacity"
>
{loading ? "Signing in…" : "Sign in"}
{loading ? t("Signing in…") : t("Sign in")}
</button>
</form>
</div>
<p className="mt-6 text-center text-sm text-[var(--muted-foreground)]">
Don&apos;t have an account?{" "}
{t("Don't have an account?")}{" "}
<Link
href="/register"
className="text-[var(--primary)] hover:underline font-medium"
>
Create one
{t("Create one")}
</Link>
</p>
+16 -12
View File
@@ -3,9 +3,11 @@
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useTranslation } from "react-i18next";
import { register, checkIsFirstUser, fetchAuthStatus } from "@/lib/auth";
export default function RegisterPage() {
const { t } = useTranslation();
const router = useRouter();
const [username, setUsername] = useState("");
@@ -34,7 +36,7 @@ export default function RegisterPage() {
setError("");
if (password !== confirmPassword) {
setError("Passwords do not match");
setError(t("Passwords do not match"));
return;
}
@@ -44,7 +46,7 @@ export default function RegisterPage() {
if (result.ok) {
router.replace("/login?registered=1");
} else {
setError(result.error ?? "Registration failed");
setError(result.error ?? t("Registration failed"));
setLoading(false);
}
}
@@ -57,15 +59,17 @@ export default function RegisterPage() {
DeepTutor
</h1>
<p className="mt-1 text-sm text-[var(--muted-foreground)]">
Create your account
{t("Create your account")}
</p>
</div>
{/* First-user notice */}
{!checkingFirst && isFirst && (
<div className="mb-4 rounded-lg border border-blue-500/30 bg-blue-500/10 px-4 py-3 text-sm text-blue-600 dark:text-blue-400">
<strong>First user:</strong> You will be granted admin privileges and
can manage other users from the admin dashboard.
<strong>{t("First user:")}</strong>{" "}
{t(
"You will be granted admin privileges and can manage other users from the admin dashboard.",
)}
</div>
)}
@@ -78,7 +82,7 @@ export default function RegisterPage() {
htmlFor="username"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
Email
{t("Email")}
</label>
<input
id="username"
@@ -102,7 +106,7 @@ export default function RegisterPage() {
htmlFor="password"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
Password
{t("Password")}
</label>
<input
id="password"
@@ -119,7 +123,7 @@ export default function RegisterPage() {
placeholder="••••••••"
/>
<p className="mt-1 text-xs text-[var(--muted-foreground)]">
At least 8 characters
{t("At least 8 characters")}
</p>
</div>
@@ -129,7 +133,7 @@ export default function RegisterPage() {
htmlFor="confirmPassword"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
Confirm password
{t("Confirm password")}
</label>
<input
id="confirmPassword"
@@ -164,18 +168,18 @@ export default function RegisterPage() {
disabled:opacity-50 disabled:cursor-not-allowed
transition-opacity"
>
{loading ? "Creating account…" : "Create account"}
{loading ? t("Creating account…") : t("Create account")}
</button>
</form>
</div>
<p className="mt-6 text-center text-sm text-[var(--muted-foreground)]">
Already have an account?{" "}
{t("Already have an account?")}{" "}
<Link
href="/login"
className="text-[var(--primary)] hover:underline font-medium"
>
Sign in
{t("Sign in")}
</Link>
</p>
+6
View File
@@ -231,6 +231,7 @@ function formatContextWindowSource(
): string {
if (source === "manual") return t("Manual");
if (source === "metadata") return t("Auto");
if (source === "known_model") return t("Known");
if (source === "default") return t("Default");
return t("Unset");
}
@@ -1755,6 +1756,11 @@ function SettingsPageContent() {
? t(
"Detected from the provider during the latest LLM test and saved into model_catalog.json.",
)
: activeModel.context_window_source ===
"known_model"
? t(
"Matched built-in model metadata during the latest LLM test and saved into model_catalog.json.",
)
: activeModel.context_window_source ===
"default"
? t(
@@ -311,6 +311,8 @@ export default function ChatPage() {
cancelStreamingTurn,
regenerateLastMessage,
deleteTurn,
editMessage,
switchBranch,
newSession,
loadSession,
} = useUnifiedChat();
@@ -1647,6 +1649,9 @@ export default function ChatPage() {
onConfirmOutline={handleConfirmOutline}
onPreviewAttachment={handlePreviewMessageAttachment}
onDeleteTurn={deleteTurn}
selectedBranches={state.selectedBranches}
onEditMessage={editMessage}
onSwitchBranch={switchBranch}
/>
<div ref={messagesEndRef} className="h-px w-full shrink-0" />
</div>
+24
View File
@@ -673,3 +673,27 @@
opacity: 1;
}
}
/* ─── Reduced motion ──────────────────────────────────────────────────────
Honor the OS-level prefers-reduced-motion setting. We don't strip motion
entirely — interaction-critical transitions (drawer slide, menu reveal)
stay visible but are shortened to a near-imperceptible duration so the
UI still communicates state changes without vestibular jitter. Loop
animations (breathing, pulse, spin) are removed outright. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.001ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.001ms !important;
scroll-behavior: auto !important;
}
.dt-breathing-text,
.dt-mark-pulse,
.session-pulse,
.animate-spin {
animation: none !important;
}
}
+2
View File
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { Plus_Jakarta_Sans, Lora } from "next/font/google";
import "./globals.css";
import ThemeScript from "@/components/ThemeScript";
import ToastViewport from "@/components/common/ToastViewport";
import { AppShellProvider } from "@/context/AppShellContext";
import { I18nClientBridge } from "@/i18n/I18nClientBridge";
@@ -47,6 +48,7 @@ export default function RootLayout({
<body className="font-sans bg-[var(--background)] text-[var(--foreground)]">
<AppShellProvider>
<I18nClientBridge>{children}</I18nClientBridge>
<ToastViewport />
</AppShellProvider>
</body>
</html>
+57 -25
View File
@@ -2,6 +2,7 @@
import React, { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { subscribeToThemeChanges } from "@/lib/theme";
interface MermaidProps {
chart: string;
@@ -10,36 +11,58 @@ interface MermaidProps {
let mermaidLoader: Promise<(typeof import("mermaid"))["default"]> | null = null;
// Read a CSS custom property from :root. We re-derive these on every render
// so the diagram colors track the active theme rather than freezing to the
// first-render palette.
function cssVar(name: string, fallback: string): string {
if (typeof window === "undefined") return fallback;
const value = getComputedStyle(document.documentElement)
.getPropertyValue(name)
.trim();
return value || fallback;
}
function themeVariablesFromCss() {
// Mermaid expects opaque colors; we pull from the theme's --foreground /
// --card / --border / --primary tokens so diagrams blend with the chat
// surface in every theme (light, dark, snow, glass).
return {
primaryColor: cssVar("--card", "#ffffff"),
primaryTextColor: cssVar("--foreground", "#1f1d1b"),
primaryBorderColor: cssVar("--border", "#dbd4c8"),
lineColor: cssVar("--muted-foreground", "#6b655f"),
secondaryColor: cssVar("--muted", "#ece7dd"),
tertiaryColor: cssVar("--background", "#faf9f6"),
textColor: cssVar("--foreground", "#1f1d1b"),
mainBkg: cssVar("--card", "#ffffff"),
};
}
async function loadMermaid() {
if (!mermaidLoader) {
mermaidLoader = import("mermaid").then((module) => {
const mermaid = module.default;
mermaid.initialize({
startOnLoad: false,
theme: "neutral",
securityLevel: "strict",
fontFamily: "ui-sans-serif, system-ui, sans-serif",
flowchart: {
useMaxWidth: true,
htmlLabels: false,
curve: "basis",
},
themeVariables: {
primaryColor: "#6366f1",
primaryTextColor: "#1e293b",
primaryBorderColor: "#c7d2fe",
lineColor: "#94a3b8",
secondaryColor: "#f1f5f9",
tertiaryColor: "#f8fafc",
},
});
return mermaid;
});
mermaidLoader = import("mermaid").then((module) => module.default);
}
return mermaidLoader;
}
// Re-applied on every render so theme changes pick up. mermaid.initialize()
// is idempotent and cheap; the heavy work is the dynamic import which the
// loader above only runs once.
function applyMermaidTheme(mermaid: (typeof import("mermaid"))["default"]) {
mermaid.initialize({
startOnLoad: false,
theme: "base",
securityLevel: "strict",
fontFamily: "ui-sans-serif, system-ui, sans-serif",
flowchart: {
useMaxWidth: true,
htmlLabels: false,
curve: "basis",
},
themeVariables: themeVariablesFromCss(),
});
}
function cleanupMermaidOrphans(id: string) {
try {
document.getElementById(id)?.remove();
@@ -60,6 +83,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
const [error, setError] = useState<string | null>(null);
const [stable, setStable] = useState(false);
const [id] = useState(() => `mermaid-${++mermaidIdCounter}`);
const [themeToken, setThemeToken] = useState(0);
const lastChartRef = useRef(chart);
useEffect(() => {
@@ -73,6 +97,13 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
return () => window.clearTimeout(timer);
}, [chart]);
// Bump a token whenever the app's theme changes so the render effect below
// re-runs with fresh theme variables. Without this the diagram would keep
// its initial palette across light/dark/glass/snow switches.
useEffect(() => {
return subscribeToThemeChanges(() => setThemeToken((t) => t + 1));
}, []);
useEffect(() => {
if (!stable) return;
@@ -82,6 +113,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
try {
const mermaid = await loadMermaid();
applyMermaidTheme(mermaid);
cleanupMermaidOrphans(id);
const { svg: renderedSvg } = await mermaid.render(id, chart.trim());
if (!cancelled) {
@@ -102,7 +134,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
return () => {
cancelled = true;
};
}, [stable, chart, id, t]);
}, [stable, chart, id, t, themeToken]);
if (error) {
return (
+35 -44
View File
@@ -5,6 +5,11 @@ 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 {
formatRelativeTime,
getDayGroupKey,
type DayGroupKey,
} from "@/lib/relative-time";
type SessionRuntimeStatus =
| "idle"
@@ -80,38 +85,6 @@ function StatusIndicator({ status }: { status?: SessionRuntimeStatus }) {
return null;
}
function groupLabel(timestamp: number): string {
const now = new Date();
const date = new Date(timestamp * 1000);
const startOfToday = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
).getTime();
const startOfItemDay = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
).getTime();
const diffDays = Math.floor((startOfToday - startOfItemDay) / 86400000);
if (diffDays <= 0) return "Today";
if (diffDays === 1) return "Yesterday";
if (diffDays < 7) return "Last 7 days";
return "Earlier";
}
function relativeTime(timestamp: number): string {
const diffSeconds = Math.round(timestamp - Date.now() / 1000);
const formatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
const abs = Math.abs(diffSeconds);
if (abs < 60) return formatter.format(diffSeconds, "second");
if (abs < 3600)
return formatter.format(Math.round(diffSeconds / 60), "minute");
if (abs < 86400)
return formatter.format(Math.round(diffSeconds / 3600), "hour");
return formatter.format(Math.round(diffSeconds / 86400), "day");
}
export default function SessionList({
sessions,
activeSessionId,
@@ -121,17 +94,31 @@ export default function SessionList({
onRename,
onDelete,
}: SessionListProps) {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const [editingId, setEditingId] = useState<string | null>(null);
const [draftTitle, setDraftTitle] = useState("");
// The group-key tokens are stable across locales; the translated labels
// (and their ordering) are built once per language change. Memoizing on
// i18n.language so the labels recompute when the user flips the language
// switcher.
const groupLabels = useMemo<Record<DayGroupKey, string>>(
() => ({
today: t("Today"),
yesterday: t("Yesterday"),
last_7_days: t("Last 7 days"),
earlier: t("Earlier"),
}),
[t, i18n.language],
);
const grouped = useMemo(() => {
const buckets = new Map<string, SessionSummary[]>();
const buckets = new Map<DayGroupKey, SessionSummary[]>();
for (const session of sessions) {
const label = groupLabel(session.updated_at);
const current = buckets.get(label) ?? [];
const key = getDayGroupKey(session.updated_at);
const current = buckets.get(key) ?? [];
current.push(session);
buckets.set(label, current);
buckets.set(key, current);
}
return Array.from(buckets.entries());
}, [sessions]);
@@ -192,13 +179,13 @@ export default function SessionList({
if (compact) {
return (
<div className="ml-5 border-l border-[var(--border)]/30 py-1">
{grouped.map(([label, items], groupIdx) => (
<div key={label}>
{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">
{label}
{groupLabels[key]}
</div>
{items.map((session) => {
const active = activeSessionId === session.session_id;
@@ -298,10 +285,10 @@ export default function SessionList({
/* ---- Classic style ---- */
return (
<div className="space-y-4">
{grouped.map(([label, items]) => (
<div key={label}>
{grouped.map(([key, items]) => (
<div key={key}>
<div className="mb-1.5 px-2 text-[11px] font-semibold uppercase tracking-widest text-[var(--muted-foreground)]">
{label}
{groupLabels[key]}
</div>
<div className="divide-y divide-[var(--border)]/45 overflow-hidden rounded-lg border border-[var(--border)]/45 bg-[var(--card)]/50">
{items.map((session) => {
@@ -365,7 +352,11 @@ export default function SessionList({
{truncateText(
normalizeMessageContent(session.last_message),
120,
) || relativeTime(session.updated_at)}
) ||
formatRelativeTime(
session.updated_at,
i18n.language,
)}
</div>
)}
</div>
+13 -5
View File
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import PickerShell from "@/components/common/PickerShell";
import { bookApi } from "@/lib/book-api";
import type { Book, BookDetail, Chapter, Page } from "@/lib/book-types";
import type {
@@ -210,10 +211,14 @@ export default function BookReferencePicker({
0,
);
if (!open) return null;
return (
<div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
<PickerShell
open={open}
onClose={onClose}
labelledBy="book-picker-title"
className="p-4 backdrop-blur-md"
backdropClass="bg-[var(--background)]/65"
>
<div className="surface-card flex h-[78vh] w-full max-w-5xl 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">
@@ -221,7 +226,10 @@ export default function BookReferencePicker({
<BookOpen className="h-3 w-3" />
{t("Book Reference")}
</div>
<h2 className="text-lg font-semibold text-[var(--foreground)]">
<h2
id="book-picker-title"
className="text-lg font-semibold text-[var(--foreground)]"
>
{t("Select Book Chapters")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -439,6 +447,6 @@ export default function BookReferencePicker({
</div>
</div>
</div>
</div>
</PickerShell>
);
}
+13 -5
View File
@@ -10,6 +10,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import PickerShell from "@/components/common/PickerShell";
import { listSessions, type SessionSummary } from "@/lib/session-api";
import { normalizeMessageContent, truncateText } from "@/lib/message-content";
@@ -102,10 +103,14 @@ export default function HistorySessionPicker({
onClose();
};
if (!open) return null;
return (
<div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
<PickerShell
open={open}
onClose={onClose}
labelledBy="history-picker-title"
className="p-4 backdrop-blur-md"
backdropClass="bg-[var(--background)]/65"
>
<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">
@@ -113,7 +118,10 @@ export default function HistorySessionPicker({
<HistoryIcon className="h-3 w-3" />
{t("Chat History Reference")}
</div>
<h2 className="text-lg font-semibold text-[var(--foreground)]">
<h2
id="history-picker-title"
className="text-lg font-semibold text-[var(--foreground)]"
>
{t("Select History Sessions")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -234,6 +242,6 @@ export default function HistorySessionPicker({
</div>
</div>
</div>
</div>
</PickerShell>
);
}
+13 -5
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
import { Brain, Check, FileText, ScrollText, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { LucideIcon } from "lucide-react";
import PickerShell from "@/components/common/PickerShell";
import type { SpaceMemoryFile } from "@/lib/space-items";
interface MemoryPickerProps {
@@ -70,10 +71,14 @@ export default function MemoryPicker({
onClose();
};
if (!open) return null;
return (
<div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
<PickerShell
open={open}
onClose={onClose}
labelledBy="memory-picker-title"
className="p-4 backdrop-blur-md"
backdropClass="bg-[var(--background)]/65"
>
<div className="surface-card w-full max-w-xl 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">
@@ -81,7 +86,10 @@ export default function MemoryPicker({
<Brain className="h-3 w-3" />
{t("Memory Reference")}
</div>
<h2 className="text-lg font-semibold text-[var(--foreground)]">
<h2
id="memory-picker-title"
className="text-lg font-semibold text-[var(--foreground)]"
>
{t("Select Memory")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -167,6 +175,6 @@ export default function MemoryPicker({
</div>
</div>
</div>
</div>
</PickerShell>
);
}
+13 -5
View File
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import PickerShell from "@/components/common/PickerShell";
import {
listCategories,
listNotebookEntries,
@@ -128,10 +129,14 @@ export default function QuestionBankPicker({
onClose();
};
if (!open) return null;
return (
<div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
<PickerShell
open={open}
onClose={onClose}
labelledBy="question-bank-picker-title"
className="p-4 backdrop-blur-md"
backdropClass="bg-[var(--background)]/65"
>
<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">
@@ -139,7 +144,10 @@ export default function QuestionBankPicker({
<ClipboardList className="h-3 w-3" />
{t("Question Bank Reference")}
</div>
<h2 className="text-lg font-semibold text-[var(--foreground)]">
<h2
id="question-bank-picker-title"
className="text-lg font-semibold text-[var(--foreground)]"
>
{t("Select Question Bank Entries")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -323,6 +331,6 @@ export default function QuestionBankPicker({
</div>
</div>
</div>
</div>
</PickerShell>
);
}
+13 -5
View File
@@ -3,6 +3,7 @@
import { useEffect, useMemo, useState } from "react";
import { Check, Loader2, Search, Sparkles, Wand2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import PickerShell from "@/components/common/PickerShell";
import { listSkills, type SkillInfo } from "@/lib/skills-api";
export interface SkillsPickerSelection {
@@ -111,12 +112,16 @@ export default function SkillsPicker({
setSelected([]);
};
if (!open) return null;
const totalCount = auto ? 1 : selected.length;
return (
<div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
<PickerShell
open={open}
onClose={onClose}
labelledBy="skills-picker-title"
className="p-4 backdrop-blur-md"
backdropClass="bg-[var(--background)]/65"
>
<div className="surface-card w-full max-w-3xl 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">
@@ -124,7 +129,10 @@ export default function SkillsPicker({
<Wand2 className="h-3 w-3" />
{t("Skills Reference")}
</div>
<h2 className="text-lg font-semibold text-[var(--foreground)]">
<h2
id="skills-picker-title"
className="text-lg font-semibold text-[var(--foreground)]"
>
{t("Select Skills")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -280,6 +288,6 @@ export default function SkillsPicker({
</div>
</div>
</div>
</div>
</PickerShell>
);
}
+3 -6
View File
@@ -312,8 +312,6 @@ export default memo(function ChatComposer({
[onAddFiles],
);
const activeCapabilityKey = activeCap.value || "chat";
useEffect(() => {
if (!hasMessages) textareaRef.current?.focus();
}, [hasMessages]);
@@ -456,7 +454,6 @@ export default memo(function ChatComposer({
<ComposerInput
ref={inputHandleRef}
textareaRef={textareaRef}
activeCapabilityKey={activeCapabilityKey}
isMathAnimatorMode={isMathAnimatorMode}
isVisualizeMode={isVisualizeMode}
canSendEmpty={hasReferences}
@@ -998,7 +995,7 @@ export default memo(function ChatComposer({
<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)]"
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_color-mix(in_srgb,var(--primary)_18%,transparent)] transition-[background-color,box-shadow] hover:bg-[var(--primary)]/90 hover:shadow-[0_6px_16px_color-mix(in_srgb,var(--primary)_28%,transparent)]"
aria-label={t("Stop generating")}
title={t("Stop generating")}
>
@@ -1033,10 +1030,10 @@ export default memo(function ChatComposer({
: undefined
}
aria-disabled={!canSend}
className={`rounded-full p-[7px] shadow-[0_4px_12px_rgba(195,90,44,0.15)] transition-[transform,opacity,box-shadow] disabled:opacity-25 disabled:shadow-none ${
className={`rounded-full p-[7px] shadow-[0_4px_12px_color-mix(in_srgb,var(--primary)_15%,transparent)] transition-[transform,opacity,box-shadow] disabled:opacity-25 disabled:shadow-none ${
isConfigBlocked
? "bg-[var(--muted-foreground)]/30 text-white hover:bg-[var(--muted-foreground)]/45"
: "bg-[var(--primary)] text-white hover:shadow-[0_6px_16px_rgba(195,90,44,0.22)]"
: "bg-[var(--primary)] text-white hover:shadow-[0_6px_16px_color-mix(in_srgb,var(--primary)_22%,transparent)]"
}`}
aria-label={t("Send")}
>
+250 -63
View File
@@ -5,10 +5,13 @@ import { memo, useCallback, useMemo, useState } from "react";
import {
BookOpen,
Brain,
ChevronLeft,
ChevronRight,
ClipboardList,
Coins,
Copy,
MessageSquare,
Pencil,
RefreshCcw,
Wand2,
X,
@@ -32,6 +35,10 @@ import { extractVisualizeResult } from "@/lib/visualize-types";
import type { StreamEvent } from "@/lib/unified-ws";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
import type { SelectedBookReference } from "@/lib/book-references";
import {
buildVisiblePath,
type SiblingInfo,
} from "@/lib/message-branches";
import type { SpaceMemoryFile } from "@/lib/space-items";
import AutoModeAssistantMessage from "./AutoModeAssistantMessage";
import { TraceSurface } from "./TracePanels";
@@ -60,6 +67,7 @@ interface ChatMessageItem {
events?: StreamEvent[];
attachments?: MessageAttachment[];
requestSnapshot?: MessageRequestSnapshot;
parentMessageId?: number | null;
}
interface NotebookReferenceGroup {
@@ -334,61 +342,137 @@ function RoughActionButton({
);
}
function BranchNavigator({
info,
onSwitch,
}: {
info: SiblingInfo;
onSwitch: (childId: number) => void;
}) {
const { t } = useTranslation();
const prevIdx = info.index - 2; // 0-based prev index
const nextIdx = info.index; // 0-based next index
const prevId = prevIdx >= 0 ? info.siblingIds[prevIdx] : null;
const nextId =
nextIdx < info.siblingIds.length ? info.siblingIds[nextIdx] : null;
return (
<div className="inline-flex items-center gap-0.5 text-[10.5px] text-[var(--muted-foreground)]">
<button
type="button"
onClick={() => prevId !== null && onSwitch(prevId)}
disabled={prevId === null}
aria-label={t("Previous branch")}
className="rounded p-0.5 transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-30"
>
<ChevronLeft size={12} strokeWidth={1.8} />
</button>
<span className="select-none tabular-nums">
{info.index} / {info.total}
</span>
<button
type="button"
onClick={() => nextId !== null && onSwitch(nextId)}
disabled={nextId === null}
aria-label={t("Next branch")}
className="rounded p-0.5 transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-30"
>
<ChevronRight size={12} strokeWidth={1.8} />
</button>
</div>
);
}
function DeleteTurnButton({ onDelete }: { onDelete: () => void }) {
const { t } = useTranslation();
const [confirm, setConfirm] = useState(false);
if (!confirm) {
return (
<RoughActionButton
icon={Trash2}
label={t("Delete")}
onClick={() => setConfirm(true)}
/>
);
}
return (
<div className="inline-flex items-center gap-1.5 text-[11px]">
<span className="text-[var(--muted-foreground)]">
{t("Delete this turn?")}
</span>
<button
type="button"
onClick={() => {
onDelete();
setConfirm(false);
}}
className="rounded-md px-1.5 py-0.5 font-medium text-[var(--destructive)] hover:bg-[var(--destructive)]/10"
>
{t("Delete")}
</button>
<button
type="button"
onClick={() => setConfirm(false)}
className="rounded-md px-1.5 py-0.5 font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"
>
{t("Cancel")}
</button>
</div>
);
}
const UserMessage = memo(function UserMessage({
msg,
index,
onPreviewAttachment,
onDeleteTurn,
onCopy,
onEdit,
editDisabled,
siblingInfo,
onSwitchBranch,
}: {
msg: ChatMessageItem;
index: number;
onPreviewAttachment?: (attachment: MessageAttachment) => void;
onDeleteTurn?: (messageId: number) => void;
onCopy?: (content: string) => void | Promise<void>;
onEdit?: (messageId: number, newContent: string) => void;
editDisabled?: boolean;
siblingInfo?: SiblingInfo;
onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;
}) {
const { t } = useTranslation();
const [confirmDelete, setConfirmDelete] = useState(false);
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(msg.content);
if (msg.content.startsWith("[Quiz Performance]")) return null;
// ``msg.id`` can be a negative client-side sentinel for optimistic
// (just-sent, not yet reconciled with the server) rows. We still allow
// the Edit button to surface — ``editMessage`` in the context handles
// the optimistic case by triggering a session reload to resolve the
// real id before submitting the branch.
const canEdit =
Boolean(onEdit) && typeof msg.id === "number" && !editDisabled;
const startEdit = () => {
if (!canEdit) return;
setDraft(msg.content);
setEditing(true);
};
const cancelEdit = () => {
setEditing(false);
setDraft(msg.content);
};
const submitEdit = () => {
const trimmed = draft.trim();
if (!trimmed || trimmed === msg.content) {
cancelEdit();
return;
}
if (typeof msg.id !== "number") return;
onEdit?.(msg.id, trimmed);
setEditing(false);
};
return (
<div key={`${msg.role}-${index}`} className="group flex justify-end">
<div className="max-w-[75%] space-y-1.5">
<div className="flex justify-end">
<div className="relative">
{!confirmDelete ? (
<button
type="button"
onClick={() => setConfirmDelete(true)}
className="rounded-md p-1 text-[var(--muted-foreground)] opacity-0 transition-opacity group-hover:opacity-100 hover:text-[var(--destructive)]"
title={t("Delete")}
>
<Trash2 size={14} strokeWidth={1.5} />
</button>
) : (
<div className="flex items-center gap-1.5 text-[12px]">
<span className="text-[var(--muted-foreground)]">
{t("Delete this turn?")}
</span>
<button
type="button"
onClick={() => {
if (msg.id != null) onDeleteTurn?.(msg.id);
setConfirmDelete(false);
}}
className="rounded-md px-2 py-0.5 font-medium text-[var(--destructive)] hover:bg-[var(--destructive)]/10"
>
{t("Delete")}
</button>
<button
type="button"
onClick={() => setConfirmDelete(false)}
className="rounded-md px-2 py-0.5 font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"
>
{t("Cancel")}
</button>
</div>
)}
</div>
</div>
<div className="flex max-w-[75%] flex-col items-end gap-1.5">
<div className="flex justify-end pr-1">
<span className="text-[10px] tracking-wide text-[var(--muted-foreground)]">
{t(getModeBadgeLabel(msg.capability))}
@@ -454,6 +538,48 @@ const UserMessage = memo(function UserMessage({
})}
</div>
)}
{editing ? (
<div className="w-[min(620px,75vw)] rounded-2xl border border-[var(--primary)]/40 bg-[var(--secondary)] px-3 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">
<textarea
autoFocus
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Escape") {
e.preventDefault();
cancelEdit();
} else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
submitEdit();
}
}}
rows={Math.min(8, Math.max(2, draft.split("\n").length))}
className="w-full resize-none border-0 bg-transparent text-[14px] leading-relaxed text-[var(--foreground)] outline-none focus:outline-none"
/>
<div className="mt-1 flex items-center justify-between gap-2">
<span className="text-[10.5px] text-[var(--muted-foreground)]/80">
{t("Use the arrows below to switch between branches.")}
</span>
<div className="flex shrink-0 items-center gap-1.5">
<button
type="button"
onClick={cancelEdit}
className="rounded-md px-2 py-0.5 text-[11px] font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"
>
{t("Cancel")}
</button>
<button
type="button"
onClick={submitEdit}
disabled={!draft.trim() || draft.trim() === msg.content}
className="rounded-md bg-[var(--primary)] px-2.5 py-0.5 text-[11px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
>
{t("Send")}
</button>
</div>
</div>
</div>
) : (
<div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">
{(() => {
const snap = msg.requestSnapshot;
@@ -534,6 +660,33 @@ const UserMessage = memo(function UserMessage({
})()}
<div className="whitespace-pre-wrap">{msg.content}</div>
</div>
)}
{!editing && (onCopy || canEdit || siblingInfo) && msg.content && (
<div className="flex h-5 items-center justify-end gap-2 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
{siblingInfo && siblingInfo.total > 1 && (
<BranchNavigator
info={siblingInfo}
onSwitch={(childId) =>
onSwitchBranch?.(siblingInfo.parentId, childId)
}
/>
)}
{onCopy && (
<RoughActionButton
icon={Copy}
label={t("Copy")}
onClick={() => void onCopy(msg.content)}
/>
)}
{canEdit && (
<RoughActionButton
icon={Pencil}
label={t("Edit")}
onClick={startEdit}
/>
)}
</div>
)}
</div>
</div>
);
@@ -729,6 +882,9 @@ export const ChatMessageList = memo(function ChatMessageList({
onPreviewAttachment,
onSwitchToManualMode,
onDeleteTurn,
selectedBranches,
onEditMessage,
onSwitchBranch,
}: {
messages: ChatMessageItem[];
isStreaming: boolean;
@@ -751,24 +907,36 @@ export const ChatMessageList = memo(function ChatMessageList({
// have to wire it.
onSwitchToManualMode?: () => void;
onDeleteTurn?: (messageId: number) => void;
/** Edit-branching: selected sibling at each branch point. */
selectedBranches?: Record<string, number>;
onEditMessage?: (messageId: number, newContent: string) => void;
onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;
}) {
const { t } = useTranslation();
// Visible path: when no branching has happened the result is identical
// to the input. After an edit, sibling branches are filtered out so the
// UI shows exactly one continuous thread, with arrow nav exposed on the
// user message where branching diverges.
const { messages: visibleMessages, siblingsByMessageId } = useMemo(
() => buildVisiblePath(messages, selectedBranches),
[messages, selectedBranches],
);
const outlineStatusByIndex = useMemo(() => {
const map = new Map<number, "editing" | "researching" | "done">();
for (let i = 0; i < messages.length; i++) {
const msg = messages[i];
for (let i = 0; i < visibleMessages.length; i++) {
const msg = visibleMessages[i];
if (msg.role !== "assistant" || msg.capability !== "deep_research")
continue;
const resultEv = msg.events?.find((e) => e.type === "result");
const meta = resultEv?.metadata as Record<string, unknown> | undefined;
if (!meta?.outline_preview) continue;
const hasFollowup = messages
const hasFollowup = visibleMessages
.slice(i + 1)
.some(
(m) => m.role === "assistant" && m.capability === "deep_research",
);
if (hasFollowup) {
const followup = messages
const followup = visibleMessages
.slice(i + 1)
.find(
(m) => m.role === "assistant" && m.capability === "deep_research",
@@ -784,13 +952,13 @@ export const ChatMessageList = memo(function ChatMessageList({
}
}
return map;
}, [messages, isStreaming]);
}, [visibleMessages, isStreaming]);
const messageRows = useMemo(() => {
// 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
return visibleMessages
.map((msg, index) => ({ msg, originalIndex: index }))
.filter(({ msg }) => msg.role !== "system")
.map(({ msg, originalIndex }) => {
@@ -802,37 +970,44 @@ export const ChatMessageList = memo(function ChatMessageList({
};
}
const pairedUserMessage =
[...messages.slice(0, originalIndex)]
[...visibleMessages.slice(0, originalIndex)]
.reverse()
.find((previous) => previous.role === "user") ?? null;
return { msg, originalIndex, pairedUserMessage };
});
}, [messages]);
}, [visibleMessages]);
const lastAssistantIndex = useMemo(() => {
for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
if (messages[idx].role === "assistant") return idx;
for (let idx = visibleMessages.length - 1; idx >= 0; idx -= 1) {
if (visibleMessages[idx].role === "assistant") return idx;
}
return -1;
}, [messages]);
}, [visibleMessages]);
return (
<>
{messageRows.map(({ msg, originalIndex, pairedUserMessage }) => {
const i = originalIndex;
if (msg.role === "user") {
const sib =
msg.id !== undefined ? siblingsByMessageId.get(msg.id) : undefined;
return (
<UserMessage
key={`${msg.role}-${i}`}
msg={msg}
index={i}
onPreviewAttachment={onPreviewAttachment}
onDeleteTurn={onDeleteTurn}
onCopy={onCopyAssistantMessage}
onEdit={onEditMessage}
editDisabled={isStreaming}
siblingInfo={sib}
onSwitchBranch={onSwitchBranch}
/>
);
}
const isActiveAssistant = isStreaming && i === messages.length - 1;
const isActiveAssistant =
isStreaming && i === visibleMessages.length - 1;
const msgDone = !isActiveAssistant;
const showActions = msgDone && hasVisibleMarkdownContent(msg.content);
const isLastAssistant = i === lastAssistantIndex;
@@ -843,6 +1018,11 @@ export const ChatMessageList = memo(function ChatMessageList({
Boolean(pairedUserMessage) &&
(!pairedUserMessage?.capability ||
pairedUserMessage?.capability === "chat");
const deletableTurnUserId =
msgDone && pairedUserMessage?.id != null && onDeleteTurn
? pairedUserMessage.id
: null;
const showDelete = deletableTurnUserId != null;
// The "Answer now" affordance lives inside the trace panel for the
// currently-streaming assistant turn. We hand the panel a thin
@@ -887,22 +1067,29 @@ export const ChatMessageList = memo(function ChatMessageList({
onRetry={onRegenerateMessage}
onSwitchToManual={onSwitchToManualMode}
/>
{(showActions || costSummary) && (
{(showActions || costSummary || showDelete) && (
<div className="mt-2 flex items-center">
{showActions && (
<div className="flex gap-2">
<RoughActionButton
icon={Copy}
label={t("Copy")}
onClick={() => void onCopyAssistantMessage(msg.content)}
/>
{showRegenerate && (
{(showActions || showDelete) && (
<div className="flex items-center gap-2">
{showActions && (
<RoughActionButton
icon={Copy}
label={t("Copy")}
onClick={() => void onCopyAssistantMessage(msg.content)}
/>
)}
{showActions && showRegenerate && (
<RoughActionButton
icon={RefreshCcw}
label={t("Regenerate")}
onClick={() => onRegenerateMessage()}
/>
)}
{showDelete && (
<DeleteTurnButton
onDelete={() => onDeleteTurn?.(deletableTurnUserId)}
/>
)}
</div>
)}
{costSummary && (
+31 -13
View File
@@ -4,8 +4,8 @@ import {
forwardRef,
memo,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
type RefObject,
@@ -15,10 +15,10 @@ import ChatSpaceMenu, {
type ChatSpaceSelectionCounts,
} from "@/components/chat/space/ChatSpaceMenu";
import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";
interface ComposerInputProps {
textareaRef: RefObject<HTMLTextAreaElement | null>;
activeCapabilityKey: string;
isMathAnimatorMode: boolean;
isVisualizeMode: boolean;
// When true, parent has attachments/references queued and will accept a
@@ -55,7 +55,6 @@ export const ComposerInput = memo(
forwardRef<ComposerInputHandle, ComposerInputProps>(function ComposerInput(
{
textareaRef,
activeCapabilityKey,
isMathAnimatorMode,
isVisualizeMode,
canSendEmpty,
@@ -101,15 +100,7 @@ export const ComposerInput = memo(
[setInputBoth, onInputChange],
);
useLayoutEffect(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = "28px";
const next = Math.max(el.scrollHeight, 28);
const bounded = Math.min(next, 200);
el.style.height = `${bounded}px`;
el.style.overflowY = next > 200 ? "auto" : "hidden";
}, [input, activeCapabilityKey, textareaRef]);
useAutoSizedTextarea(textareaRef, input, { min: 28, max: 200 });
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
@@ -207,10 +198,31 @@ export const ComposerInput = memo(
],
);
// Close the @-popup on outside click. Without this, clicking anywhere
// outside the popup or textarea left the menu hovering indefinitely.
// We bind on mousedown so the close fires before a synthetic click on
// a sibling button (e.g. the Tools menu) can re-open something else.
const popupRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!showAtPopup) return;
const handler = (e: MouseEvent) => {
const target = e.target as Node | null;
if (!target) return;
if (popupRef.current?.contains(target)) return;
if (textareaRef.current?.contains(target)) return;
setShowAtPopup(false);
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, [showAtPopup, textareaRef]);
return (
<div className="px-4 pt-3.5 pb-2">
{showAtPopup && (
<div className="absolute bottom-full left-0 z-[70] mb-2">
<div
ref={popupRef}
className="absolute bottom-full left-0 z-[70] mb-2"
>
<ChatSpaceMenu
variant="mention"
selectedCounts={selectedCounts}
@@ -228,6 +240,12 @@ export const ComposerInput = memo(
onClick={handleTextareaClick}
onPaste={onPaste}
rows={1}
// Cap input at 32k chars. A bigger paste (e.g. an entire textbook
// dumped via Cmd+V) would force a layout reflow on every keystroke
// and lock the page; the cap is a defensive guard, not a real
// product limit. Users hit by this cap should be using the
// attachment path, not the composer body.
maxLength={32000}
suppressHydrationWarning
placeholder={
isMathAnimatorMode
@@ -3,13 +3,13 @@
import {
memo,
useCallback,
useLayoutEffect,
useRef,
useState,
type RefObject,
} from "react";
import { useTranslation } from "react-i18next";
import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";
interface SimpleComposerInputProps {
textareaRef: RefObject<HTMLTextAreaElement | null>;
@@ -26,13 +26,7 @@ export const SimpleComposerInput = memo(function SimpleComposerInput({
const [input, setInput] = useState("");
const isComposingRef = useRef(false);
useLayoutEffect(() => {
const el = textareaRef.current;
if (!el) return;
el.style.height = "auto";
const next = Math.max(el.scrollHeight, 42);
el.style.height = `${Math.min(next, 200)}px`;
}, [input, textareaRef]);
useAutoSizedTextarea(textareaRef, input, { min: 42, max: 200 });
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
@@ -77,6 +71,9 @@ export const SimpleComposerInput = memo(function SimpleComposerInput({
onCompositionEnd={handleCompositionEnd}
placeholder={t("Type a message...")}
rows={1}
// Defensive cap — see ComposerInput for the same guard. Anything beyond
// this size belongs in an attachment, not in the textarea body.
maxLength={32000}
disabled={disabled}
className="flex-1 resize-none rounded-xl border border-[var(--border)] bg-transparent px-4 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] disabled:opacity-50 placeholder:text-[var(--muted-foreground)]/40"
style={{ minHeight: 42 }}
+86 -93
View File
@@ -20,6 +20,10 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import {
formatTurnDuration,
getTurnDurationSeconds,
} from "@/lib/trace-timing";
import type { StreamEvent } from "@/lib/unified-ws";
type TraceMetadata = {
@@ -32,6 +36,10 @@ type TraceMetadata = {
trace_kind?: string;
trace_id?: string;
call_state?: string;
// Set by the chat pipeline on the final iteration's reasoning sub-trace.
// Marks "this sub-trace's text has been re-emitted as the final-response
// CONTENT event in the same turn, so don't render it as a duplicate row."
absorbed_into_final?: boolean;
step_id?: string;
round?: number;
query?: string;
@@ -142,37 +150,6 @@ function getTraceGroup(events: StreamEvent[]) {
return "";
}
function getTraceDurationLabel(events: StreamEvent[]) {
let start: number | null = null;
let end: number | null = null;
for (const event of events) {
const state = String(getTraceMeta(event).call_state || "");
if (state === "running" && start === null) start = event.timestamp;
if ((state === "complete" || state === "error") && end === null)
end = event.timestamp;
}
if (start === null || end === null) return "";
const seconds = Math.max(1, Math.round(end - start));
return `${seconds}s`;
}
function getTraceStartTimestamp(events: StreamEvent[]) {
for (const event of events) {
const state = String(getTraceMeta(event).call_state || "");
if (state === "running") return event.timestamp;
}
return null;
}
function getActiveTraceDurationSeconds(
events: StreamEvent[],
nowSeconds: number,
) {
const start = getTraceStartTimestamp(events);
if (start === null) return null;
return Math.max(1, Math.round(nowSeconds - start));
}
function isTracePending(events: StreamEvent[]) {
let hasRunning = false;
let hasTerminal = false;
@@ -186,7 +163,6 @@ function isTracePending(events: StreamEvent[]) {
function getTraceHeader(
events: StreamEvent[],
nowSeconds?: number,
nested?: boolean,
t: (key: string, opts?: Record<string, unknown>) => string = (k) => k,
) {
@@ -195,10 +171,6 @@ function getTraceHeader(
const group = getTraceGroup(events);
const kind = getTraceCallKind(events);
const meta = getTraceMeta(events[0]);
const duration =
kind === "math_render_output" && isTracePending(events) && nowSeconds
? `${getActiveTraceDurationSeconds(events, nowSeconds) ?? 1}s`
: getTraceDurationLabel(events);
let title = label;
if (
@@ -244,9 +216,7 @@ function getTraceHeader(
}
}
return duration
? t("{{title}} for {{duration}}", { title, duration })
: title;
return title;
}
function getTraceText(
@@ -302,6 +272,14 @@ function buildDisplayItems(traceGroups: TraceItem[]): DisplayItem[] {
const kind = getTraceCallKind(group.events);
if (kind === "llm_final_response") continue;
// The chat pipeline streams the final iteration's prose as ``thinking``
// events into a sub-trace AND re-emits it as a ``llm_final_response``
// content event. The sub-trace itself is tagged ``absorbed_into_final``
// on its terminal progress event so we drop it here — otherwise the
// final answer would appear twice (once in the trace box, once in the
// body).
if (group.events.some((e) => getTraceMeta(e).absorbed_into_final === true))
continue;
if (groupType === "react_round" && stepId) {
if (stepId_ === stepId) {
@@ -322,25 +300,6 @@ function buildDisplayItems(traceGroups: TraceItem[]): DisplayItem[] {
return items;
}
function getStepGroupDuration(traces: TraceItem[]): string {
let start: number | null = null;
let end: number | null = null;
for (const trace of traces) {
for (const event of trace.events) {
const state = String(getTraceMeta(event).call_state || "");
if (state === "running" && (start === null || event.timestamp < start))
start = event.timestamp;
if (
(state === "complete" || state === "error") &&
(end === null || event.timestamp > end)
)
end = event.timestamp;
}
}
if (start === null || end === null) return "";
return `${Math.max(1, Math.round(end - start))}s`;
}
/* ------------------------------------------------------------------ */
/* Primitive UI pieces */
/* ------------------------------------------------------------------ */
@@ -714,7 +673,6 @@ export function CallTracePanel({
nested?: boolean;
}) {
const { t } = useTranslation();
const [nowSeconds, setNowSeconds] = useState(() => Date.now() / 1000);
// Sticky-bottom auto-scroll for the outer trace card. While the user is
// pinned near the bottom we keep them there as new trace events stream in;
@@ -740,15 +698,6 @@ export function CallTracePanel({
stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 30;
}, []);
useEffect(() => {
if (!isStreaming) return;
const timer = window.setInterval(
() => setNowSeconds(Date.now() / 1000),
1000,
);
return () => window.clearInterval(timer);
}, [isStreaming]);
const traceGroups = useMemo(() => {
const groups: TraceItem[] = [];
const indexById = new Map<string, number>();
@@ -773,7 +722,12 @@ export function CallTracePanel({
[traceGroups],
);
if (!traceGroups.length) return null;
// Hide the outer container entirely when no sub-trace ends up being
// rendered. ``traceGroups`` can be non-empty even when every group is
// filtered out by ``buildDisplayItems`` (final-response groups and groups
// tagged ``absorbed_into_final``) — in that case we used to draw an
// empty bordered box. Check the materialised displayItems instead.
if (!displayItems.length) return null;
function renderTraceRow(
{ callId, events: callEvents }: TraceItem,
@@ -786,7 +740,7 @@ export function CallTracePanel({
const role = getTraceRole(callEvents);
const group = getTraceGroup(callEvents);
const kind = getTraceCallKind(callEvents);
const header = getTraceHeader(callEvents, nowSeconds, nested, t);
const header = getTraceHeader(callEvents, nested, t);
const active =
Boolean(isStreaming) && isGloballyLast && isTracePending(callEvents);
const isFinalResponse = kind === "llm_final_response";
@@ -876,9 +830,6 @@ export function CallTracePanel({
Boolean(isStreaming) &&
isLastDisplayItem &&
isTracePending(lastTrace.events);
const stepDuration = isActiveStep
? ""
: getStepGroupDuration(item.traces);
return (
<ExpandableDetails
@@ -891,10 +842,9 @@ export function CallTracePanel({
className="shrink-0 transition-transform group-open/step:rotate-180"
/>
<Sparkles size={12} strokeWidth={1.6} className="shrink-0" />
<span>Step {item.stepId}</span>
<span>{t("Step {{n}}", { n: item.stepId })}</span>
<span className="text-[11px] opacity-60">
{roundCount} {roundCount === 1 ? "round" : "rounds"}
{stepDuration ? ` · ${stepDuration}` : ""}
{t("{{count}} round", { count: roundCount })}
</span>
{isActiveStep && (
<Loader2 size={11} className="animate-spin" />
@@ -917,7 +867,6 @@ export function CallTracePanel({
if (trGroup === "react_round") {
const roundNum = trMeta.round;
const duration = getTraceDurationLabel(trace.events);
const thoughtText = getTraceText(trace.events, [
"thinking",
]);
@@ -942,13 +891,8 @@ export function CallTracePanel({
)}
<div className="mb-1 flex items-center gap-1.5 not-italic text-[11px]">
<span className="font-bold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">
Round {roundNum}
{t("Round {{n}}", { n: roundNum })}
</span>
{duration && (
<span className="font-normal text-[var(--muted-foreground)]/40">
{duration}
</span>
)}
{roundActive && (
<Loader2 size={10} className="animate-spin" />
)}
@@ -1018,12 +962,7 @@ export function CallTracePanel({
}
/* Non-round trace (retrieve, tool, etc.) — inline within the step */
const inlineHeader = getTraceHeader(
trace.events,
nowSeconds,
true,
t,
);
const inlineHeader = getTraceHeader(trace.events, true, t);
const progressEvts = trace.events.filter(
(e) =>
e.type === "progress" &&
@@ -1287,6 +1226,16 @@ export function StreamingStatus({
}) {
const { t } = useTranslation();
const hasFinalContent = Boolean(content && content.trim().length > 0);
const [nowSeconds, setNowSeconds] = useState(() => Date.now() / 1000);
useEffect(() => {
if (!isStreaming) return;
const timer = window.setInterval(
() => setNowSeconds(Date.now() / 1000),
1000,
);
return () => window.clearInterval(timer);
}, [isStreaming]);
// Only render once we either have a streaming turn OR a completed turn that
// produced visible content — empty placeholders (e.g. system message
// shells) shouldn't show a status row.
@@ -1305,6 +1254,18 @@ export function StreamingStatus({
: mode === "responded"
? t("DeepTutor responded.")
: t("DeepTutor reasoning…");
// Single turn-level clock. Ticks every second while the turn is in
// flight and freezes on the final elapsed time once the answer ends —
// replaces the per-sub-trace duration chips that used to live inside
// the trace card.
const turnSeconds = getTurnDurationSeconds(
events,
nowSeconds,
Boolean(isStreaming),
);
const durationLabel =
turnSeconds != null ? formatTurnDuration(turnSeconds) : null;
// Static label after the answer is done — no breathing animation. The other
// three states are live so they pulse to signal ongoing work. The icon also
// stretches/contracts on its own cycle (out of phase with the opacity fade)
@@ -1332,6 +1293,11 @@ export function StreamingStatus({
className={`${breathingClass} ${markPulseClass} shrink-0 text-[var(--primary)]/90`}
/>
<span className={breathingClass}>{label}</span>
{durationLabel ? (
<span className="text-[12px] font-medium tabular-nums text-[var(--muted-foreground)]/55">
· {durationLabel}
</span>
) : null}
{collapsible ? (
<ChevronDown
size={14}
@@ -1344,12 +1310,19 @@ export function StreamingStatus({
</>
);
// role="status" + aria-live="polite" surfaces mode transitions
// (reasoning → tool using → responding → responded) to screen readers
// without barging in on the user. aria-atomic="false" so only the changed
// label is announced rather than the whole row each tick.
if (collapsible && onToggle) {
return (
<button
type="button"
onClick={onToggle}
aria-expanded={expanded ? "true" : "false"}
role="status"
aria-live="polite"
aria-atomic="false"
className={`mb-3 -ml-1 flex items-center gap-2.5 rounded-md px-1 py-0.5 text-[14px] font-semibold leading-none transition-colors hover:bg-[var(--muted)]/40 ${textColor}`}
>
{rowContent}
@@ -1359,6 +1332,9 @@ export function StreamingStatus({
return (
<div
role="status"
aria-live="polite"
aria-atomic="false"
className={`mb-3 flex items-center gap-2.5 text-[14px] font-semibold leading-none ${textColor}`}
>
{rowContent}
@@ -1381,10 +1357,27 @@ export function TraceSurface({
isStreaming?: boolean;
content?: string;
}) {
const hasCallTrace = useMemo(
() => events.some((event) => Boolean(event.metadata?.call_id)),
[events],
);
// ``hasCallTrace`` decides whether the status row gets a clickable
// chevron AND whether the trace panel below is mounted. We must filter
// out groups that CallTracePanel itself would discard — otherwise the
// chevron toggles a panel that's intentionally empty (final-response
// only, or all reasoning sub-traces absorbed into the final answer).
const hasCallTrace = useMemo(() => {
const seen = new Map<string, { hasFinal: boolean; hasAbsorbed: boolean }>();
for (const event of events) {
const meta = (event.metadata ?? {}) as Record<string, unknown>;
const cid = String(meta.call_id || "");
if (!cid) continue;
const entry = seen.get(cid) ?? { hasFinal: false, hasAbsorbed: false };
if (meta.call_kind === "llm_final_response") entry.hasFinal = true;
if (meta.absorbed_into_final === true) entry.hasAbsorbed = true;
seen.set(cid, entry);
}
for (const { hasFinal, hasAbsorbed } of seen.values()) {
if (!hasFinal && !hasAbsorbed) return true;
}
return false;
}, [events]);
const [expanded, setExpanded] = useState(true);
const toggle = useCallback(() => setExpanded((prev) => !prev), []);
+64 -3
View File
@@ -1,6 +1,6 @@
"use client";
import { memo } from "react";
import { memo, useEffect, useRef, useState } from "react";
import { BookOpen } from "lucide-react";
import { useTranslation } from "react-i18next";
import { SPACE_ITEMS } from "@/lib/space-items";
@@ -66,6 +66,7 @@ export default memo(function ChatSpaceMenu({
}: ChatSpaceMenuProps) {
const { t } = useTranslation();
const compact = variant === "toolbar";
const isMention = variant === "mention";
// Render the items in a fixed, hand-tuned order so the menu always reads
// the same regardless of how SPACE_ITEMS may be reordered for navigation.
@@ -80,21 +81,81 @@ export default memo(function ChatSpaceMenu({
: SPACE_ITEMS.find((it) => it.key === key)!,
).filter(Boolean);
// Active row index for keyboard navigation. Only meaningful in the
// mention variant — the toolbar variant is mouse/click driven.
const [activeIdx, setActiveIdx] = useState(0);
// The keydown handler closes over `activeIdx`/`items`/`onSelectItem`;
// stash them in refs so the document-level listener identity stays
// stable and we don't re-attach it on every render. Refs are synced
// in an effect (not during render) to satisfy `react-hooks/refs`.
const activeIdxRef = useRef(activeIdx);
const itemsRef = useRef(items);
const onSelectItemRef = useRef(onSelectItem);
useEffect(() => {
activeIdxRef.current = activeIdx;
}, [activeIdx]);
useEffect(() => {
itemsRef.current = items;
}, [items]);
useEffect(() => {
onSelectItemRef.current = onSelectItem;
}, [onSelectItem]);
// Reset to the top whenever the menu first mounts (i.e. user typed `@`
// and the popup appeared). The parent unmounts/remounts this component
// on each open, so a fresh `useState(0)` initial value already gives us
// the right behavior — no extra effect needed.
// Attach a document-level keydown so Arrow/Enter while the textarea
// still has focus drive the menu. The textarea's own handleKeyDown
// continues to handle Escape and submit.
useEffect(() => {
if (!isMention) return;
const handler = (e: KeyboardEvent) => {
const list = itemsRef.current;
if (list.length === 0) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setActiveIdx((i) => (i + 1) % list.length);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActiveIdx((i) => (i - 1 + list.length) % list.length);
} else if (e.key === "Enter") {
const item = list[activeIdxRef.current];
if (!item) return;
e.preventDefault();
onSelectItemRef.current(item.key as SelectableSpaceKey);
}
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
}, [isMention]);
return (
<div
role={isMention ? "listbox" : undefined}
aria-label={isMention ? t("Reference space") : undefined}
className={`rounded-xl border border-[var(--border)] bg-[var(--popover)] shadow-lg backdrop-blur-md ${
compact ? "w-[260px] py-1.5" : "w-64 p-2"
}`}
>
<div className={compact ? "space-y-0.5" : "space-y-1"}>
{items.map(({ key, label, description, icon: Icon }) => {
{items.map(({ key, label, description, icon: Icon }, idx) => {
const count = countFor(key as SelectableSpaceKey, selectedCounts);
const isActive = isMention && idx === activeIdx;
return (
<button
key={key}
type="button"
role={isMention ? "option" : undefined}
aria-selected={isMention ? isActive : undefined}
onMouseEnter={
isMention ? () => setActiveIdx(idx) : undefined
}
onClick={() => onSelectItem(key as SelectableSpaceKey)}
className={`flex w-full items-center gap-2.5 text-left transition-colors hover:bg-[var(--muted)]/40 ${
className={`flex w-full items-center gap-2.5 text-left transition-colors ${
isActive ? "bg-[var(--muted)]/60" : "hover:bg-[var(--muted)]/40"
} ${
compact
? "px-3 py-1.5 text-[12px]"
: "rounded-xl px-3 py-2.5 text-[13px]"
+11 -1
View File
@@ -34,8 +34,18 @@ export default function AssistantResponse({
if (!hasRenderableSegment) return null;
// role="article" lets screen-reader users locate each assistant turn as a
// structured landmark. aria-live="polite" + aria-atomic="false" announces
// streamed-in content as the user pauses, without re-reading the whole
// bubble each token. Together this is the minimal pattern that turns a
// silent stream into an audible one.
return (
<div className={className}>
<div
role="article"
aria-live="polite"
aria-atomic="false"
className={className}
>
{segments.map((segment, index) => {
if (segment.kind === "think") {
return (
+17 -2
View File
@@ -23,8 +23,15 @@ export interface MarkdownRendererProps {
trackSourceLines?: boolean;
}
// Detection during streaming has a subtle correctness requirement: it must
// be monotonic. Once `true`, it should stay `true` as more tokens arrive so
// the renderer never downgrades from Rich back to Simple (which would cause
// a full subtree remount and a visible flash). The patterns below match
// *opening* tokens — `$$`, `\(`, `\[`, ` ``` ` — rather than requiring a
// matched close. A partial fence still gets the rich treatment, then the
// closer arriving later is just more append-only content with no swap.
function detectMathContent(content: string): boolean {
if (/(^|[^\\])\$\$[\s\S]+?\$\$/.test(content)) return true;
if (/(^|[^\\])\$\$/.test(content)) return true;
if (/\\\(|\\\[/.test(content)) return true;
// Single-dollar inline math containing LaTeX commands (\cmd) or math operators ({}_^)
if (
@@ -37,7 +44,10 @@ function detectMathContent(content: string): boolean {
}
function detectCodeContent(content: string): boolean {
return /```[A-Za-z0-9_+#.-]+/.test(content);
// Match any opening triple-backtick, even before the language identifier
// arrives. Otherwise streaming flips Simple→Rich the moment the language
// tag lands a few tokens after the fence.
return /```/.test(content);
}
function detectMermaidContent(content: string): boolean {
@@ -65,6 +75,11 @@ export default function MarkdownRenderer({
const resolvedEnableCode = enableCode ?? detectCodeContent(content);
const resolvedEnableMermaid = enableMermaid ?? detectMermaidContent(content);
const resolvedAllowHtml = allowHtml ?? detectHtmlContent(content);
// Detection above is intentionally monotonic — once any of the rich
// triggers fire, more tokens never un-fire them. Combined with the
// append-only nature of streaming content this gives us a stable
// Simple→Rich one-way transition (the Rich subtree mounts once and
// stays). No additional lock state is needed.
const shouldUseRich =
variant !== "trace" &&
(trackSourceLines ||
+94 -23
View File
@@ -1,7 +1,8 @@
"use client";
import { useEffect, useCallback } from "react";
import { useEffect, useId, useRef } from "react";
import { X } from "lucide-react";
import { useTranslation } from "react-i18next";
interface ModalProps {
isOpen: boolean;
@@ -23,8 +24,18 @@ const widthClasses = {
xl: "w-[800px]",
};
const FOCUSABLE_SELECTOR =
'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
/**
* Shared Modal base component
* Shared Modal base component.
*
* Provides the full dialog-behavior contract: Escape close, optional
* backdrop click close, body scroll lock, role=dialog + aria-modal, initial
* focus into the dialog, focus restoration on close, and a focus trap that
* keeps Tab cycling inside the dialog. The contract matches PickerShell so
* Modal and the picker overlays behave the same way from an a11y / keyboard
* perspective.
*/
export default function Modal({
isOpen,
@@ -38,54 +49,114 @@ export default function Modal({
closeOnEscape = true,
showCloseButton = true,
}: ModalProps) {
// Handle escape key
const handleEscape = useCallback(
(e: KeyboardEvent) => {
if (closeOnEscape && e.key === "Escape") {
onClose();
}
},
[closeOnEscape, onClose],
);
const { t } = useTranslation();
const dialogRef = useRef<HTMLDivElement>(null);
const previouslyFocusedRef = useRef<HTMLElement | null>(null);
const titleId = useId();
// Body scroll lock + remember trigger for focus restoration on close.
useEffect(() => {
if (isOpen) {
document.addEventListener("keydown", handleEscape);
// Prevent body scroll when modal is open
document.body.style.overflow = "hidden";
}
if (!isOpen) return;
previouslyFocusedRef.current =
(document.activeElement as HTMLElement | null) ?? null;
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.removeEventListener("keydown", handleEscape);
document.body.style.overflow = "";
document.body.style.overflow = prev;
};
}, [isOpen, handleEscape]);
}, [isOpen]);
// Initial focus on the next frame so the dialog DOM is settled.
useEffect(() => {
if (!isOpen) return;
const id = window.requestAnimationFrame(() => {
const node = dialogRef.current;
if (!node) return;
const explicit = node.querySelector<HTMLElement>("[data-autofocus]");
const target =
explicit ?? node.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);
target?.focus();
});
return () => window.cancelAnimationFrame(id);
}, [isOpen]);
// Restore focus to the trigger on close.
useEffect(() => {
if (isOpen) return;
const trigger = previouslyFocusedRef.current;
if (trigger && document.contains(trigger)) {
trigger.focus();
}
previouslyFocusedRef.current = null;
}, [isOpen]);
if (!isOpen) return null;
const handleBackdropClick = (e: React.MouseEvent) => {
const handleKeyDown = (e: React.KeyboardEvent) => {
if (closeOnEscape && e.key === "Escape") {
e.stopPropagation();
onClose();
return;
}
if (e.key !== "Tab") return;
const node = dialogRef.current;
if (!node) return;
const focusables = Array.from(
node.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
);
if (focusables.length === 0) return;
const first = focusables[0];
const last = focusables[focusables.length - 1];
const active = document.activeElement as HTMLElement | null;
if (e.shiftKey && active === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
};
const handleBackdropMouseDown = (e: React.MouseEvent) => {
if (closeOnBackdrop && e.target === e.currentTarget) {
onClose();
}
};
const hasTitle = !!title || !!titleIcon;
return (
<div
// mousedown rather than click so dragging out of an input doesn't
// accidentally close on mouseup.
onMouseDown={handleBackdropMouseDown}
className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 animate-in fade-in"
onClick={handleBackdropClick}
>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={hasTitle ? titleId : undefined}
aria-label={hasTitle ? undefined : (title ?? t("Dialog"))}
onKeyDown={handleKeyDown}
onMouseDown={(e) => e.stopPropagation()}
className={`bg-[var(--card)] border border-[var(--border)] rounded-2xl shadow-2xl ${widthClasses[width]} max-h-[90vh] flex flex-col animate-in zoom-in-95`}
>
{/* Header */}
{(title || titleIcon || showCloseButton) && (
{(hasTitle || showCloseButton) && (
<div className="p-4 border-b border-[var(--border)] flex items-center justify-between shrink-0">
<h3 className="font-bold text-[var(--foreground)] flex items-center gap-2">
<h3
id={titleId}
className="font-bold text-[var(--foreground)] flex items-center gap-2"
>
{titleIcon}
{title}
</h3>
{showCloseButton ? (
<button
type="button"
onClick={onClose}
aria-label={t("Close")}
className="p-1 hover:bg-[var(--muted)] rounded-lg transition-colors"
>
<X className="w-5 h-5 text-[var(--muted-foreground)]" />
+198
View File
@@ -0,0 +1,198 @@
"use client";
import { useCallback, useEffect, useRef } from "react";
/**
* Behavioral wrapper for fullscreen pickers (NotebookRecordPicker,
* HistorySessionPicker, MemoryPicker, QuestionBankPicker, SkillsPicker,
* BookReferencePicker, SaveToNotebookModal, …). Each of those was rolled
* by hand and skipped the basic dialog-behavior contract — Escape, backdrop
* click, body scroll lock, focus trap, ARIA roles. This component lifts
* that contract into one place so the pickers themselves only have to
* render their *content*.
*
* Design notes:
* - The shell renders the centered backdrop. Callers render the picker
* card as `children` — they keep full control over the card's chrome,
* width, padding, etc. (see existing pickers).
* - `onClose` fires on Escape, on backdrop click, and is reachable
* programmatically (e.g. a Cancel button inside the card).
* - Focus management: on open we move focus to the first focusable element
* inside the dialog (typically the search input). On close we restore
* focus to wherever it was when the picker opened. This is what users
* expect from a modal but every hand-rolled picker had skipped it.
* - Focus trap: Tab from the last focusable element wraps to the first,
* Shift+Tab from the first wraps to the last. The dialog is the only
* thing screen-reader / keyboard users can interact with while open.
*/
export interface PickerShellProps {
open: boolean;
onClose: () => void;
children: React.ReactNode;
/**
* id of an element inside `children` that names the dialog. Required for
* proper `aria-labelledby`. If the picker has no visible title, pass an
* `aria-label` instead via `ariaLabel`.
*/
labelledBy?: string;
ariaLabel?: string;
/**
* Z-index for the backdrop. Defaults to 85 to match the existing
* picker convention; raise it if stacking under another picker.
*/
zIndex?: number;
/**
* Outer container layout. Most pickers center their card; some use a
* full-bleed layout. Defaults to centered.
*/
align?: "center" | "start";
/**
* Extra classes applied to the inner backdrop wrapper. Allows pickers
* to opt out of the default `flex items-center justify-center` for
* bespoke layouts.
*/
className?: string;
/**
* Override the default `bg-black/40` backdrop. Pass any opacity / blur /
* tint combo. Useful for pickers that want a frosted-glass look or a
* lighter scrim.
*/
backdropClass?: string;
}
const FOCUSABLE_SELECTOR =
'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
export default function PickerShell({
open,
onClose,
children,
labelledBy,
ariaLabel,
zIndex = 85,
align = "center",
className,
backdropClass = "bg-black/40",
}: PickerShellProps) {
const dialogRef = useRef<HTMLDivElement>(null);
const previouslyFocusedRef = useRef<HTMLElement | null>(null);
// Stash the focused element when the picker opens so we can return focus
// there on close. Reset on every open so reopening returns to the latest
// trigger.
useEffect(() => {
if (!open) return;
previouslyFocusedRef.current =
(document.activeElement as HTMLElement | null) ?? null;
}, [open]);
// Body scroll lock. Preserve the user's prior overflow so we don't trample
// a parent that already had a lock in place.
useEffect(() => {
if (!open) return;
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.body.style.overflow = prev;
};
}, [open]);
// Move initial focus into the dialog on open. We defer to the next frame
// so the rendered card has measured + focusable elements are in the DOM.
useEffect(() => {
if (!open) return;
const id = window.requestAnimationFrame(() => {
const node = dialogRef.current;
if (!node) return;
// Prefer an explicit autofocus marker, then the first focusable child.
const explicit = node.querySelector<HTMLElement>("[data-autofocus]");
const target =
explicit ?? node.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);
target?.focus();
});
return () => window.cancelAnimationFrame(id);
}, [open]);
// Restore focus to the trigger on close. Guarded by document.contains so
// we never call focus() on a detached element (e.g. the trigger was
// unmounted while the picker was open).
useEffect(() => {
if (open) return;
const trigger = previouslyFocusedRef.current;
if (trigger && document.contains(trigger)) {
trigger.focus();
}
previouslyFocusedRef.current = null;
}, [open]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Escape") {
e.stopPropagation();
onClose();
return;
}
if (e.key !== "Tab") return;
// Focus trap. Cycle within the dialog so Tab can never escape into
// the page chrome behind us.
const node = dialogRef.current;
if (!node) return;
const focusables = Array.from(
node.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
).filter((el) => !el.hasAttribute("data-focus-skip"));
if (focusables.length === 0) return;
const first = focusables[0];
const last = focusables[focusables.length - 1];
const active = document.activeElement as HTMLElement | null;
if (e.shiftKey && active === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
},
[onClose],
);
const handleBackdropMouseDown = useCallback(
(e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
onClose();
}
},
[onClose],
);
if (!open) return null;
const alignmentClass =
align === "center" ? "items-center justify-center" : "items-start";
return (
<div
// Backdrop. mousedown rather than click so dragging out of a search
// input doesn't dismiss the picker on the eventual mouseup.
onMouseDown={handleBackdropMouseDown}
className={`fixed inset-0 flex ${backdropClass} ${alignmentClass} ${
className ?? ""
}`}
style={{ zIndex }}
>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={labelledBy}
aria-label={labelledBy ? undefined : ariaLabel}
onKeyDown={handleKeyDown}
// Stop propagation so a click *inside* the dialog never reaches the
// backdrop's mousedown handler above. Width/layout decisions stay
// with the picker that renders the card inside.
onMouseDown={(e) => e.stopPropagation()}
>
{children}
</div>
</div>
);
}
@@ -310,11 +310,15 @@ export default function SimpleMarkdownRenderer({
const raw = String(children).replace(/\n$/, "");
if (raw.includes("\n")) {
// Use the same #1f2937 / #e5e7eb palette as RichMarkdownRenderer and
// RichCodeBlock so any stream-time fallback from Rich → Simple (or
// first-paint via Simple before the rich lock engages) looks visually
// identical to its rich counterpart.
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]`}
>
<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 className="md-code-block__code" {...props}>
{raw}
</code>
+81
View File
@@ -0,0 +1,81 @@
"use client";
import { X } from "lucide-react";
import { useEffect, useState } from "react";
import {
subscribeNotifications,
type Notification,
} from "@/lib/notifications";
/**
* Renders the toast stack in the bottom-right. Mounted once at the
* workspace layout level — every call to `notify()` from anywhere in the
* app appears here.
*
* Each toast lives for its own `durationMs`, then auto-dismisses. Users
* can also dismiss manually via the X button. The viewport itself is
* `aria-live="polite"` so assistive tech announces new toasts as they
* arrive, without barging in on whatever the user was reading.
*/
export default function ToastViewport() {
const [toasts, setToasts] = useState<Notification[]>([]);
useEffect(() => {
return subscribeNotifications((toast) => {
setToasts((prev) => [...prev, toast]);
const timer = window.setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== toast.id));
}, toast.durationMs);
// No cleanup needed — listener stays alive for the component's life;
// individual setTimeouts are GC'd after they fire.
void timer;
});
}, []);
const dismiss = (id: number) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
};
if (toasts.length === 0) return null;
return (
<div
role="status"
aria-live="polite"
aria-atomic="false"
className="pointer-events-none fixed bottom-6 right-6 z-[200] flex flex-col gap-2"
>
{toasts.map((toast) => (
<div
key={toast.id}
className={`pointer-events-auto flex max-w-sm items-start gap-3 rounded-xl border px-4 py-3 shadow-lg backdrop-blur-md ${toneClass(
toast.tone,
)}`}
>
<span className="flex-1 text-[13px] leading-relaxed">
{toast.message}
</span>
<button
type="button"
onClick={() => dismiss(toast.id)}
className="rounded p-0.5 opacity-60 transition-opacity hover:opacity-100"
aria-label="Dismiss"
>
<X size={14} strokeWidth={1.8} />
</button>
</div>
))}
</div>
);
}
function toneClass(tone: Notification["tone"]): string {
switch (tone) {
case "error":
return "border-[var(--destructive)]/30 bg-[var(--destructive)]/10 text-[var(--destructive)]";
case "success":
return "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300";
default:
return "border-[var(--border)] bg-[var(--card)]/95 text-[var(--foreground)]";
}
}
@@ -3,6 +3,7 @@
import { useEffect } from "react";
import { Layers, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import PickerShell from "@/components/common/PickerShell";
import NotebookSelector from "@/components/notebook/NotebookSelector";
import { useNotebookSelection } from "@/components/notebook/useNotebookSelection";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
@@ -41,10 +42,14 @@ export default function NotebookRecordPicker({
void fetchNotebooks();
}, [fetchNotebooks, open]);
if (!open) return null;
return (
<div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
<PickerShell
open={open}
onClose={onClose}
labelledBy="notebook-picker-title"
className="p-4 backdrop-blur-md"
backdropClass="bg-[var(--background)]/65"
>
<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">
@@ -52,7 +57,10 @@ export default function NotebookRecordPicker({
<Layers className="h-3 w-3" />
{t("Notebook Reference")}
</div>
<h2 className="text-lg font-semibold text-[var(--foreground)]">
<h2
id="notebook-picker-title"
className="text-lg font-semibold text-[var(--foreground)]"
>
{t("Select Notebook Records")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -91,6 +99,6 @@ export default function NotebookRecordPicker({
/>
</div>
</div>
</div>
</PickerShell>
);
}
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import PickerShell from "@/components/common/PickerShell";
import { apiFetch, apiUrl } from "@/lib/api";
import {
listNotebooks,
@@ -369,7 +370,9 @@ export default function SaveToNotebookModal({
}
};
if (!open || !payload) return null;
// payload may be null while the parent is preparing the save context.
// Treat that as "not open" so the shell never renders without content.
const isOpen = open && !!payload;
const totalMessages = messages?.length ?? 0;
const selectedMessageCount = selectedMessageIdx.size;
@@ -377,14 +380,24 @@ export default function SaveToNotebookModal({
totalMessages > 0 && selectedMessageCount === totalMessages;
return (
<div className="fixed inset-0 z-[80] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
<PickerShell
open={isOpen}
onClose={onClose}
labelledBy="save-to-notebook-title"
zIndex={80}
className="p-4 backdrop-blur-md"
backdropClass="bg-[var(--background)]/65"
>
<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-[var(--foreground)]">
<h2
id="save-to-notebook-title"
className="text-lg font-semibold text-[var(--foreground)]"
>
{t("Save to Notebook")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -635,6 +648,6 @@ export default function SaveToNotebookModal({
</button>
</div>
</div>
</div>
</PickerShell>
);
}
+7 -13
View File
@@ -2,7 +2,9 @@
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 RecentBook {
id: string;
@@ -24,24 +26,13 @@ const STATUS_DOT: Record<string, string> = {
error: "bg-rose-400",
};
function relativeTime(seconds: number): string {
if (!seconds || Number.isNaN(seconds)) return "";
const diff = Date.now() / 1000 - seconds;
if (diff < 60) return "now";
const mins = Math.floor(diff / 60);
if (mins < 60) return `${mins}m`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h`;
const days = Math.floor(hrs / 24);
return `${days}d`;
}
interface BookRecentProps {
collapsed?: boolean;
limit?: number;
}
export function BookRecent({ collapsed = false, limit = 4 }: BookRecentProps) {
const { i18n } = useTranslation();
const [books, setBooks] = useState<RecentBook[]>([]);
useEffect(() => {
@@ -89,7 +80,10 @@ export function BookRecent({ collapsed = false, limit = 4 }: BookRecentProps) {
{book.title || "Untitled book"}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
{relativeTime(Number(book.updated_at) || 0)}
{formatRelativeTime(
Number(book.updated_at) || 0,
i18n.language,
)}
</span>
</Link>
);
+7 -13
View File
@@ -3,23 +3,13 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
listCoWriterDocuments,
type CoWriterDocumentSummary,
} from "@/lib/co-writer-api";
import { subscribeCoWriterChanges } from "@/lib/co-writer-events";
function relativeTime(seconds: number): string {
if (!seconds || Number.isNaN(seconds)) return "";
const diff = Date.now() / 1000 - seconds;
if (diff < 60) return "now";
const mins = Math.floor(diff / 60);
if (mins < 60) return `${mins}m`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h`;
const days = Math.floor(hrs / 24);
return `${days}d`;
}
import { formatRelativeTime } from "@/lib/relative-time";
interface CoWriterRecentProps {
collapsed?: boolean;
@@ -30,6 +20,7 @@ export function CoWriterRecent({
collapsed = false,
limit = 4,
}: CoWriterRecentProps) {
const { i18n } = useTranslation();
const [docs, setDocs] = useState<CoWriterDocumentSummary[]>([]);
const pathname = usePathname();
const limitRef = useRef(limit);
@@ -71,7 +62,10 @@ export function CoWriterRecent({
{doc.title || "Untitled draft"}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
{relativeTime(Number(doc.updated_at) || 0)}
{formatRelativeTime(
Number(doc.updated_at) || 0,
i18n.language,
)}
</span>
</Link>
))}
+7 -12
View File
@@ -2,7 +2,9 @@
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;
@@ -12,18 +14,8 @@ interface RecentBot {
updated_at: string;
}
function relativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h`;
const days = Math.floor(hrs / 24);
return `${days}d`;
}
export function TutorBotRecent({ collapsed = false }: { collapsed?: boolean }) {
const { i18n } = useTranslation();
const [bots, setBots] = useState<RecentBot[]>([]);
useEffect(() => {
@@ -66,7 +58,10 @@ export function TutorBotRecent({ collapsed = false }: { collapsed?: boolean }) {
{bot.name}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
{relativeTime(bot.updated_at)}
{formatRelativeTime(
Math.floor(new Date(bot.updated_at).getTime() / 1000),
i18n.language,
)}
</span>
</Link>
))}
@@ -115,7 +115,7 @@ function HtmlRenderer({ html }: { html: string }) {
ref={iframeRef}
title="HTML visualization"
sandbox="allow-scripts"
className="w-full rounded-lg border border-[var(--border)] bg-white"
className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)]"
style={{ minHeight: 480, height: 560 }}
/>
</div>
@@ -269,13 +269,15 @@ export default function VisualizationViewer({
</span>
</div>
{/* Code panel */}
{/* Code panel — matches the always-dark .md-code-block style used by the
markdown renderers so a "Show code" toggle inside a chart message
looks identical to a fenced code block in the assistant response. */}
{showCode && (
<div className="overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]">
<div className="md-code-block overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]">
<div className="border-b border-white/10 px-3 py-2 text-[11px] font-medium uppercase tracking-wider text-[#9ca3af]">
{result.code.language}
</div>
<pre className="max-h-80 overflow-auto p-4 text-[13px] leading-relaxed text-[#d1d5db]">
<pre className="max-h-80 overflow-auto p-4 text-[13px] leading-relaxed text-[#e5e7eb]">
<code>{result.code.content}</code>
</pre>
</div>
@@ -316,7 +318,7 @@ export default function VisualizationViewer({
</button>
</div>
<div
className="flex flex-1 items-center justify-center overflow-auto rounded-xl bg-white p-6 shadow-2xl"
className="flex flex-1 items-center justify-center overflow-auto rounded-xl bg-[var(--card)] p-6 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="w-full max-w-[1600px]">
+323 -26
View File
@@ -22,11 +22,15 @@ import { UnifiedWSClient } from "@/lib/unified-ws";
import {
getSession,
deleteMessage,
updateBranchSelection,
type SessionMessage,
} from "@/lib/session-api";
import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";
import { normalizeMessageContent } from "@/lib/message-content";
import { buildVisiblePath, tipMessageId } from "@/lib/message-branches";
import { shouldAppendEventContent } from "@/lib/stream";
import { notify } from "@/lib/notifications";
import i18n from "i18next";
import {
normalizeBookReferences,
type BookReferencePayload,
@@ -64,6 +68,10 @@ export interface SendMessageOptions {
persistUserMessage?: boolean;
requestSnapshotOverride?: MessageRequestSnapshot;
bookReferences?: BookReferencePayload[];
/** Edit-branching: when set, the new user message is inserted as a
* sibling under this parent rather than appended to the session tail.
* ``null`` means "explicitly attach to the session root". */
parentMessageId?: number | null;
// Surface that originated the turn. The backend stamps this onto the
// session row when ``ensure_session`` first creates it, then it never
// changes. Callers from /co-learn must pass ``"co_learn"`` so the auto
@@ -81,6 +89,9 @@ export interface ChatState {
isStreaming: boolean;
currentStage: string;
language: string;
/** Edit-branching: keyed by stringified parent_message_id (or "null"
* for the root). Empty means "default to latest sibling everywhere". */
selectedBranches: Record<string, number>;
}
interface SessionStatusSnapshot {
@@ -128,6 +139,8 @@ export interface MessageItem {
events?: StreamEvent[];
attachments?: MessageAttachment[];
requestSnapshot?: MessageRequestSnapshot;
/** Edit-branching: id of the message this row continues. */
parentMessageId?: number | null;
}
interface SessionEntry extends ChatState {
@@ -136,6 +149,9 @@ interface SessionEntry extends ChatState {
activeTurnId: string | null;
lastSeq: number;
updatedAt: number;
/** Edit-branching: maps a parent_message_id (stringified, or "null" for
* the session root) to the chosen child id at that branch point. */
selectedBranches: Record<string, number>;
}
interface ProviderState {
@@ -157,6 +173,7 @@ type Action =
capability?: string | null;
attachments?: MessageAttachment[];
requestSnapshot?: MessageRequestSnapshot;
parentMessageId?: number | null;
}
| { type: "POP_LAST_ASSISTANT"; key: string }
| { type: "RESTORE_ASSISTANT"; key: string; message: MessageItem }
@@ -186,9 +203,21 @@ type Action =
knowledgeBases?: string[];
llmSelection?: LLMSelection | null;
language?: string;
selectedBranches?: Record<string, number>;
}
| { type: "DELETE_TURN"; key: string; messageId: number }
| { type: "NEW_SESSION"; key: string };
| { type: "NEW_SESSION"; key: string }
| {
type: "SET_SELECTED_BRANCH";
key: string;
parentKey: string;
childId: number;
}
| {
type: "REPLACE_SELECTED_BRANCHES";
key: string;
selectedBranches: Record<string, number>;
};
function createSessionEntry(
key: string,
@@ -209,6 +238,7 @@ function createSessionEntry(
activeTurnId: null,
lastSeq: 0,
updatedAt: Date.now(),
selectedBranches: {},
};
}
@@ -279,6 +309,10 @@ function reducer(state: ProviderState, action: Action): ProviderState {
role: "user",
content: action.content,
capability: action.capability || "",
parentMessageId:
action.parentMessageId === undefined
? null
: action.parentMessageId,
...(action.attachments?.length
? { attachments: action.attachments }
: {}),
@@ -338,34 +372,46 @@ function reducer(state: ProviderState, action: Action): ProviderState {
},
};
}
case "STREAM_START":
case "STREAM_START": {
const session =
state.sessions[action.key] ?? createSessionEntry(action.key);
const existing = session.messages ?? [];
// Chain the placeholder assistant onto whatever message currently
// sits at the tip — this is normally the user row just added by
// ADD_USER_MSG (possibly an optimistic negative id during an edit).
const tip = existing.length > 0 ? existing[existing.length - 1] : null;
return {
...state,
sessions: {
...state.sessions,
[action.key]: {
...(state.sessions[action.key] ?? createSessionEntry(action.key)),
...session,
isStreaming: true,
status: "running",
messages: [
...(state.sessions[action.key]?.messages ?? []),
...existing,
{
id: -Date.now(),
role: "assistant",
content: "",
events: [],
capability:
(state.sessions[action.key] ?? createSessionEntry(action.key))
.activeCapability || "",
capability: session.activeCapability || "",
parentMessageId: tip?.id ?? null,
},
],
updatedAt: Date.now(),
},
},
};
}
case "STREAM_EVENT": {
const session =
state.sessions[action.key] ?? createSessionEntry(action.key);
// If the session entry has been removed (e.g., BIND_SERVER_SESSION
// just renamed ``draft_X`` to a real id but a stray event still
// targets the old key), drop the event rather than synthesise an
// orphan session with no user message — that would scrub the
// user's just-sent bubble from view.
if (!state.sessions[action.key]) return state;
const session = state.sessions[action.key];
const msgs = [...session.messages];
let last = msgs[msgs.length - 1];
if (last?.role !== "assistant") {
@@ -375,6 +421,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {
content: "",
events: [],
capability: session.activeCapability || "",
parentMessageId: last?.id ?? null,
});
last = msgs[msgs.length - 1];
}
@@ -484,6 +531,41 @@ function reducer(state: ProviderState, action: Action): ProviderState {
activeTurnId: action.activeTurnId || null,
status: action.status || "idle",
language: action.language ?? existing.language,
selectedBranches:
action.selectedBranches ?? existing.selectedBranches,
updatedAt: Date.now(),
},
},
};
}
case "SET_SELECTED_BRANCH": {
const session = state.sessions[action.key];
if (!session) return state;
return {
...state,
sessions: {
...state.sessions,
[action.key]: {
...session,
selectedBranches: {
...session.selectedBranches,
[action.parentKey]: action.childId,
},
updatedAt: Date.now(),
},
},
};
}
case "REPLACE_SELECTED_BRANCHES": {
const session = state.sessions[action.key];
if (!session) return state;
return {
...state,
sessions: {
...state.sessions,
[action.key]: {
...session,
selectedBranches: { ...action.selectedBranches },
updatedAt: Date.now(),
},
},
@@ -577,6 +659,13 @@ interface ChatContextValue {
cancelStreamingTurn: () => void;
regenerateLastMessage: () => void;
deleteTurn: (messageId: number) => Promise<void>;
/** Re-send a user message under a new branch (sibling of the original).
* Uses the composer's current capability / refs — only the text is
* taken from ``newContent``. Re-runs the turn from the original's
* parent context. */
editMessage: (messageId: number, newContent: string) => Promise<void>;
/** Switch which sibling is currently visible at a branch point. */
switchBranch: (parentMessageId: number | null, childId: number) => void;
newSession: () => void;
loadSession: (sessionId: string) => Promise<void>;
selectedSessionId: string | null;
@@ -627,6 +716,16 @@ function asLLMSelection(value: unknown): LLMSelection | null {
: null;
}
function normalizeSelectedBranches(value: unknown): Record<string, number> {
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const result: Record<string, number> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
const n = typeof v === "number" ? v : Number(v);
if (Number.isInteger(n) && n > 0) result[k] = n;
}
return result;
}
function asMemoryReferences(value: unknown): MemoryReferencePayload {
return asStringArray(value).filter(
(item): item is "summary" | "profile" =>
@@ -727,6 +826,12 @@ export function UnifiedChatProvider({
// assistant message if the server rejects the request (e.g. ``regenerate_busy``
// or ``nothing_to_regenerate``). Keyed by session entry key.
const pendingRegenerateRef = useRef<Map<string, MessageItem>>(new Map());
// Forward-declared so ``handleRunnerEvent`` (created above
// ``loadSession`` in source order) can trigger a server refresh after
// a turn finishes without taking a stale closure of ``loadSession``.
const loadSessionRef = useRef<((sessionId: string) => Promise<void>) | null>(
null,
);
useLayoutEffect(() => {
stateRef.current = state;
@@ -769,6 +874,10 @@ export function UnifiedChatProvider({
capability: message.capability || "",
events: Array.isArray(message.events) ? message.events : [],
attachments,
parentMessageId:
message.parent_message_id === undefined
? null
: message.parent_message_id,
...(requestSnapshot ? { requestSnapshot } : {}),
};
});
@@ -824,6 +933,21 @@ export function UnifiedChatProvider({
const runner = runnersRef.current.get(effectiveKey);
runner?.client.disconnect();
runnersRef.current.delete(effectiveKey);
// Reconcile optimistic client-side message ids with the
// server's real ids after the turn finishes. Without this the
// Edit button (which needs a real id to attach the new branch
// under) and branch navigation (which keys off real ids) would
// stay disabled until the user navigates away and back.
if (status === "completed") {
const finishedSession =
stateRef.current.sessions[effectiveKey];
const sessionId = finishedSession?.sessionId;
if (sessionId) {
loadSessionRef.current?.(sessionId).catch(() => {
/* non-fatal — local state remains usable */
});
}
}
return;
}
dispatch({ type: "STREAM_EVENT", key: effectiveKey, event });
@@ -892,6 +1016,15 @@ export function UnifiedChatProvider({
key: record.key,
status: "failed",
});
// Surface the disconnect to the user. The WS client already
// logs to console — we add a toast so non-debugging users
// don't see streaming silently flatline.
notify(
i18n.t(
"Connection lost while generating. Please retry your message.",
),
{ tone: "error", durationMs: 6000 },
);
}
},
),
@@ -910,6 +1043,15 @@ export function UnifiedChatProvider({
if (attempt >= 10) {
console.error("WebSocket failed to connect after retries");
dispatch({ type: "STREAM_END", key, status: "failed" });
// Surfaces the dead-after-N-retries case (different code path
// from the close-while-streaming handler above). Same user
// mental model, so same toast copy.
notify(
i18n.t(
"Couldn't reach the server. Please check your connection and retry.",
),
{ tone: "error", durationMs: 6000 },
);
return;
}
const timerId = setTimeout(() => {
@@ -951,6 +1093,9 @@ export function UnifiedChatProvider({
// have stale persisted preferences, so new turns follow the current
// app language rather than the language saved when the session began.
language: readStoredLanguage(),
selectedBranches: normalizeSelectedBranches(
session.preferences?.selected_branches,
),
});
if (activeTurn?.turn_id || activeTurn?.id) {
const key = session.session_id || session.id;
@@ -964,6 +1109,10 @@ export function UnifiedChatProvider({
[hydrateMessages, sendThroughRunner],
);
useLayoutEffect(() => {
loadSessionRef.current = loadSession;
}, [loadSession]);
useEffect(() => {
if (typeof window === "undefined") return;
const current = state.selectedKey
@@ -1111,6 +1260,27 @@ export function UnifiedChatProvider({
? { llmSelection: effectiveLLMSelection }
: {}),
};
// Default the new message's parent to the tip of the currently-
// visible path so the local chat tree stays connected during
// streaming. The wire-level ``parent_message_id`` is computed
// separately further down: only persisted (positive) ids or an
// explicit ``null`` (root edit) are sent — optimistic negative ids
// would be meaningless to the server.
const visible = buildVisiblePath(
session.messages,
session.selectedBranches,
).messages;
const tipId = tipMessageId(visible);
const localParentId =
options?.parentMessageId !== undefined
? options.parentMessageId
: tipId;
const wireParentId: number | null | undefined =
options?.parentMessageId !== undefined
? options.parentMessageId
: tipId !== null && tipId > 0
? tipId
: undefined;
if (options?.displayUserMessage !== false) {
dispatch({
type: "ADD_USER_MSG",
@@ -1119,6 +1289,7 @@ export function UnifiedChatProvider({
capability: effectiveCapability,
attachments: msgAttachments,
requestSnapshot,
parentMessageId: localParentId,
});
}
dispatch({ type: "STREAM_START", key });
@@ -1158,6 +1329,15 @@ export function UnifiedChatProvider({
...(effectiveConfig && Object.keys(effectiveConfig).length > 0
? { config: effectiveConfig }
: {}),
// Send ``parent_message_id`` only when we have a real (positive)
// server id to chain under, or when the caller explicitly pinned
// a parent (incl. ``null`` for editing the session's first
// message). When the visible tip is still an optimistic
// negative id, omit the key and let the backend auto-append to
// the latest persisted row.
...(wireParentId !== undefined
? { parent_message_id: wireParentId }
: {}),
});
},
[makeDraftKey, sendThroughRunner],
@@ -1222,6 +1402,7 @@ export function UnifiedChatProvider({
isStreaming: current.isStreaming,
currentStage: current.currentStage,
language: current.language,
selectedBranches: current.selectedBranches,
};
}, [state]);
@@ -1263,6 +1444,93 @@ export function UnifiedChatProvider({
dispatch({ type: "NEW_SESSION", key: makeDraftKey() });
}, [makeDraftKey]);
const editMessage = useCallback(
async (messageId: number, newContent: string) => {
const trimmed = newContent.trim();
if (!trimmed) return;
const currentState = stateRef.current;
const key = currentState.selectedKey;
if (!key) return;
const session = currentState.sessions[key];
if (!session) return;
// Edits create a new branch via a fresh turn — block while one is
// already running so we don't queue against an in-flight stream
// (matches the delete-turn guard).
if (session.isStreaming) return;
const idx = session.messages.findIndex(
(m) => m.id === messageId && m.role === "user",
);
if (idx === -1) return;
let original = session.messages[idx];
// Optimistic in-flight rows have a negative client-side id — we
// need a real server id to hang the new sibling under. Refresh
// from the server, then re-resolve the row by its position in the
// (now-persisted) thread before continuing.
if (typeof original.id === "number" && original.id < 0) {
if (!session.sessionId) return;
try {
await loadSession(session.sessionId);
} catch {
return;
}
const refreshed = stateRef.current.sessions[key];
const candidate = refreshed?.messages[idx];
if (
!candidate ||
candidate.role !== "user" ||
typeof candidate.id !== "number" ||
candidate.id < 0
) {
return;
}
original = candidate;
}
if (typeof original.id !== "number" || original.id < 0) return;
const parentId = original.parentMessageId ?? null;
sendMessage(
trimmed,
undefined,
undefined,
undefined,
undefined,
{ parentMessageId: parentId },
undefined,
undefined,
undefined,
);
},
[loadSession, sendMessage],
);
const switchBranch = useCallback(
(parentMessageId: number | null, childId: number) => {
const currentState = stateRef.current;
const key = currentState.selectedKey;
if (!key) return;
const session = currentState.sessions[key];
if (!session) return;
const parentKey = parentMessageId == null ? "null" : String(parentMessageId);
dispatch({
type: "SET_SELECTED_BRANCH",
key,
parentKey,
childId,
});
const sessionId = session.sessionId;
if (!sessionId) return;
const nextSelections = {
...session.selectedBranches,
[parentKey]: childId,
};
// Fire-and-forget — local state is the source of truth for the UI;
// the server copy only matters for reload-time hydration.
updateBranchSelection(sessionId, nextSelections).catch((err) => {
console.warn("Failed to persist branch selection:", err);
});
},
[],
);
const deleteTurn = useCallback(
async (messageId: number) => {
const currentState = stateRef.current;
@@ -1295,23 +1563,52 @@ export function UnifiedChatProvider({
[loadSession],
);
const value: ChatContextValue = {
state: derivedState,
setTools,
setCapability,
setKBs,
setLLMSelection,
setLanguage,
sendMessage,
cancelStreamingTurn,
regenerateLastMessage,
deleteTurn,
newSession,
loadSession,
selectedSessionId: derivedState.sessionId,
sessionStatuses,
sidebarRefreshToken: state.sidebarRefreshToken,
};
// Memoize the context value so consumers don't re-render on every render of
// this provider. Without this wrap, every stream-event-driven reducer
// dispatch produced a fresh object identity, cascading a re-render through
// every `useUnifiedChat()` consumer (chat page, composer, sidebar) on each
// token. The callbacks below are already stable via useCallback; the only
// things that should change identity are derivedState, sessionStatuses,
// and sidebarRefreshToken.
const value = useMemo<ChatContextValue>(
() => ({
state: derivedState,
setTools,
setCapability,
setKBs,
setLLMSelection,
setLanguage,
sendMessage,
cancelStreamingTurn,
regenerateLastMessage,
deleteTurn,
editMessage,
switchBranch,
newSession,
loadSession,
selectedSessionId: derivedState.sessionId,
sessionStatuses,
sidebarRefreshToken: state.sidebarRefreshToken,
}),
[
derivedState,
setTools,
setCapability,
setKBs,
setLLMSelection,
setLanguage,
sendMessage,
cancelStreamingTurn,
regenerateLastMessage,
deleteTurn,
editMessage,
switchBranch,
newSession,
loadSession,
sessionStatuses,
state.sidebarRefreshToken,
],
);
return <ChatCtx.Provider value={value}>{children}</ChatCtx.Provider>;
}
+15 -3
View File
@@ -90,9 +90,14 @@ export function useChatAutoScroll({
// After streaming ends, dynamically-loaded components (e.g. MathAnimatorViewer
// via next/dynamic) may render and grow the content height. Detect that and
// scroll to bottom so the user can see the full result.
// hasMessages is in deps so the observer attaches once the messages
// container mounts on session reopen — without it, the container ref is null
// on initial mount and the observer is never set up.
//
// This observer used to run for the entire lifetime of the conversation,
// which meant any post-stream DOM change — including the user expanding a
// trace `<details>` row to read it — was treated as "new content arrived"
// and pulled the user back to the bottom. We now gate it to a short window
// right after `isStreaming` flips false, which is when late-mounting
// dynamic components actually settle.
const POST_STREAM_AUTOSCROLL_WINDOW_MS = 4000;
useEffect(() => {
if (isStreaming) return;
if (!hasMessages) return;
@@ -102,11 +107,13 @@ export function useChatAutoScroll({
let prevHeight = container.scrollHeight;
let rafId = 0;
const deadline = performance.now() + POST_STREAM_AUTOSCROLL_WINDOW_MS;
const check = () => {
if (rafId) return;
rafId = requestAnimationFrame(() => {
rafId = 0;
if (performance.now() > deadline) return;
const curHeight = container.scrollHeight;
if (curHeight > prevHeight && shouldAutoScrollRef.current) {
scrollToBottom("instant");
@@ -117,8 +124,13 @@ export function useChatAutoScroll({
const mo = new MutationObserver(check);
mo.observe(container, { childList: true, subtree: true });
const stopTimer = window.setTimeout(() => {
mo.disconnect();
if (rafId) cancelAnimationFrame(rafId);
}, POST_STREAM_AUTOSCROLL_WINDOW_MS);
return () => {
window.clearTimeout(stopTimer);
mo.disconnect();
if (rafId) cancelAnimationFrame(rafId);
};

Some files were not shown because too many files have changed in this diff Show More