Skip to content

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

fix pageindex & minor bugs

Bingxi Zhao (Frank)fb3c56869780
diff --git a/assets/figs/chat-loop.png b/assets/figs/chat-loop.png
new file mode 100644
index 000000000..1895fc551
Binary files /dev/null and b/assets/figs/chat-loop.png differ
diff --git a/deeptutor/agents/_shared/json_output.py b/deeptutor/agents/_shared/json_output.py
new file mode 100644
index 000000000..a8ec9ca92
--- /dev/null
+++ b/deeptutor/agents/_shared/json_output.py
@@ -0,0 +1,62 @@
+"""Parsing helpers shared by agents that consume structured model output."""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any
+
+
+def extract_json_object(text: str) -> dict[str, Any]:
+ """Extract the first usable JSON object from raw model output."""
+ raw = (text or "").strip()
+ if not raw:
+ return {}
+
+ fenced = re.findall(r"```(?:json)?\s*([\s\S]*?)\s*```", raw)
+ for candidate in [*fenced, raw]:
+ try:
+ parsed = json.loads(candidate)
+ if isinstance(parsed, dict):
+ return parsed
+ except json.JSONDecodeError:
+ parsed = _decode_first_json_object(candidate)
+ if parsed is not None:
+ return parsed
+
+ start = raw.find("{")
+ end = raw.rfind("}")
+ if start != -1 and end > start:
+ snippet = raw[start : end + 1]
+ try:
+ return json.loads(snippet)
+ except json.JSONDecodeError:
+ parsed = _decode_first_json_object(snippet)
+ if parsed is not None:
+ return parsed
+
+ raise json.JSONDecodeError("No JSON object found", raw, 0)
+
+
+def _decode_first_json_object(text: str) -> dict[str, Any] | None:
+ decoder = json.JSONDecoder()
+ stripped = (text or "").lstrip()
+ if not stripped:
+ return None
+
+ starts = [0]
+ brace_index = stripped.find("{")
+ if brace_index > 0:
+ starts.append(brace_index)
+
+ for start in starts:
+ try:
+ parsed, _end = decoder.raw_decode(stripped[start:])
+ except json.JSONDecodeError:
+ continue
+ if isinstance(parsed, dict):
+ return parsed
+ return None
+
+
+__all__ = ["extract_json_object"]
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.py
index d1c6a5047..aaf7870d3 100644
--- a/deeptutor/agents/chat/agent_loop.py
+++ b/deeptutor/agents/chat/agent_loop.py
@@ -31,12 +31,18 @@ import re
from typing import TYPE_CHECKING, Any
from deeptutor.agents._shared.capability_result import emit_capability_result
+from deeptutor.core.agentic.messages import assistant_message_with_tool_calls
from deeptutor.core.agentic.tool_dispatch import DispatchOutcome
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id
from deeptutor.services.llm import clean_thinking_tags
from deeptutor.services.llm.multimodal import should_degrade_to_text, strip_image_parts_inplace
+from deeptutor.services.llm.request_compat import (
+ is_image_input_unsupported,
+ is_stream_options_unsupported,
+ is_tool_schema_unsupported,
+)
if TYPE_CHECKING: # pragma: no cover
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
@@ -298,7 +304,7 @@ class AgentLoop:
# Finish: the text streamed live this round IS the answer.
return await self._finalize_finish(final_text)
- messages.append(_assistant_message_with_tool_calls(result.text, result.tool_calls))
+ messages.append(assistant_message_with_tool_calls(result.text, result.tool_calls))
dispatch = await self.pipeline._dispatch_tool_calls(
tool_calls=result.tool_calls,
context=self.context,
@@ -588,11 +594,11 @@ class AgentLoop:
try:
return await self.client.chat.completions.create(**kwargs)
except Exception as exc:
- if "stream_options" in kwargs and _is_stream_options_unsupported(exc):
+ if "stream_options" in kwargs and is_stream_options_unsupported(exc):
retry_kwargs = dict(kwargs)
retry_kwargs.pop("stream_options", None)
return await self.client.chat.completions.create(**retry_kwargs)
- if kwargs.get("tools") and _is_tool_schema_unsupported(exc):
+ if kwargs.get("tools") and is_tool_schema_unsupported(exc):
await self.stream.progress(
self.pipeline._t(
"notices.tool_schema_fallback",
@@ -610,7 +616,7 @@ class AgentLoop:
retry_kwargs.pop("tool_choice", None)
self.tool_schemas = None
return await self.client.chat.completions.create(**retry_kwargs)
- if _is_image_input_unsupported(exc) and should_degrade_to_text(
+ if is_image_input_unsupported(exc) and should_degrade_to_text(
self.pipeline.binding,
self.pipeline.model,
kwargs.get("messages") or [],
@@ -632,27 +638,6 @@ class AgentLoop:
raise
-def _assistant_message_with_tool_calls(
- content: str,
- tool_calls: list[dict[str, Any]],
-) -> dict[str, Any]:
- return {
- "role": "assistant",
- "content": content or None,
- "tool_calls": [
- {
- "id": tc["id"],
- "type": "function",
- "function": {
- "name": tc["name"],
- "arguments": tc.get("arguments") or "{}",
- },
- }
- for tc in tool_calls
- ],
- }
-
-
def _message_content_chars(message: dict[str, Any]) -> int:
content = message.get("content")
if isinstance(content, str):
@@ -682,69 +667,6 @@ def _last_context_checkpoint_summary(dispatch: DispatchOutcome) -> str:
return summary
-def _error_text(exc: Exception) -> str:
- response = getattr(exc, "response", None)
- body = (
- getattr(exc, "body", None)
- or getattr(exc, "doc", None)
- or getattr(response, "text", None)
- or getattr(exc, "message", None)
- or str(exc)
- )
- return str(body).lower()
-
-
-def _is_stream_options_unsupported(exc: Exception) -> bool:
- text = _error_text(exc)
- return any(
- marker in text
- for marker in (
- "stream_options",
- "stream options",
- "unknown parameter",
- "unrecognized request argument",
- "unsupported parameter",
- "extra inputs are not permitted",
- "unexpected keyword",
- )
- )
-
-
-def _is_tool_schema_unsupported(exc: Exception) -> bool:
- text = _error_text(exc)
- return any(
- marker in text
- for marker in (
- "tool",
- "function_declaration",
- "function declaration",
- "function_declarations",
- "tool_choice",
- "parameters.properties",
- "404_not_found",
- "404 not_found",
- )
- )
-
-
-def _is_image_input_unsupported(exc: Exception) -> bool:
- text = _error_text(exc)
- return any(
- marker in text
- for marker in (
- "image",
- "vision",
- "multimodal",
- "image_url",
- "content type",
- "must be a string",
- "expected a string",
- "expected string",
- "invalid type for 'messages",
- )
- )
-
-
__all__ = [
"AgentLoop",
"AgentLoopState",
diff --git a/deeptutor/agents/math_animator/utils.py b/deeptutor/agents/math_animator/utils.py
index a379a8f0a..267df78fb 100644
--- a/deeptutor/agents/math_animator/utils.py
+++ b/deeptutor/agents/math_animator/utils.py
@@ -2,63 +2,9 @@
from __future__ import annotations
-import json
import re
-from typing import Any
-
-def extract_json_object(text: str) -> dict[str, Any]:
- """Extract a JSON object from raw model output."""
- raw = (text or "").strip()
- if not raw:
- return {}
-
- fenced = re.findall(r"```(?:json)?\s*([\s\S]*?)\s*```", raw)
- candidates = fenced + [raw]
-
- for candidate in candidates:
- try:
- parsed = json.loads(candidate)
- if isinstance(parsed, dict):
- return parsed
- except json.JSONDecodeError:
- parsed = _decode_first_json_object(candidate)
- if parsed is not None:
- return parsed
-
- start = raw.find("{")
- end = raw.rfind("}")
- if start != -1 and end != -1 and end > start:
- snippet = raw[start : end + 1]
- try:
- return json.loads(snippet)
- except json.JSONDecodeError:
- parsed = _decode_first_json_object(snippet)
- if parsed is not None:
- return parsed
-
- raise json.JSONDecodeError("No JSON object found", raw, 0)
-
-
-def _decode_first_json_object(text: str) -> dict[str, Any] | None:
- decoder = json.JSONDecoder()
- stripped = (text or "").lstrip()
- if not stripped:
- return None
-
- starts = [0]
- brace_index = stripped.find("{")
- if brace_index > 0:
- starts.append(brace_index)
-
- for start in starts:
- try:
- parsed, _end = decoder.raw_decode(stripped[start:])
- except json.JSONDecodeError:
- continue
- if isinstance(parsed, dict):
- return parsed
- return None
+from deeptutor.agents._shared.json_output import extract_json_object
def slugify_filename(value: str, fallback: str) -> str:
diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py
index f799239bc..42f4e4d2e 100644
--- a/deeptutor/agents/question/pipeline.py
+++ b/deeptutor/agents/question/pipeline.py
@@ -1956,28 +1956,6 @@ class _BaseLoopHost:
# No quiz tool is wired to terminate the loop with content.
return
- def assistant_message_with_tool_calls(
- self,
- *,
- content: str,
- tool_calls: list[dict[str, Any]],
- ) -> dict[str, Any]:
- return {
- "role": "assistant",
- "content": content or None,
- "tool_calls": [
- {
- "id": tc["id"],
- "type": "function",
- "function": {
- "name": tc["name"],
- "arguments": tc.get("arguments") or "{}",
- },
- }
- for tc in tool_calls
- ],
- }
-
def protocol_retry_notice(self) -> str:
return self._pipeline._t(
"notices.protocol_retry",
diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.py
index eba91a9f4..f79ad08c1 100644
--- a/deeptutor/agents/research/pipeline.py
+++ b/deeptutor/agents/research/pipeline.py
@@ -2429,28 +2429,6 @@ class _BlockLoopHost:
# actual report begins.
return None
- def assistant_message_with_tool_calls(
- self,
- *,
- content: str,
- tool_calls: list[dict[str, Any]],
- ) -> dict[str, Any]:
- return {
- "role": "assistant",
- "content": content or None,
- "tool_calls": [
- {
- "id": tc["id"],
- "type": "function",
- "function": {
- "name": tc["name"],
- "arguments": tc.get("arguments") or "{}",
- },
- }
- for tc in tool_calls
- ],
- }
-
def protocol_retry_notice(self) -> str:
return self._pipeline._t(
"notices.protocol_retry",
@@ -2774,28 +2752,6 @@ class _RephraseLoopHost:
# The refined topic is internal; not streamed as user content.
return None
- def assistant_message_with_tool_calls(
- self,
- *,
- content: str,
- tool_calls: list[dict[str, Any]],
- ) -> dict[str, Any]:
- return {
- "role": "assistant",
- "content": content or None,
- "tool_calls": [
- {
- "id": tc["id"],
- "type": "function",
- "function": {
- "name": tc["name"],
- "arguments": tc.get("arguments") or "{}",
- },
- }
- for tc in tool_calls
- ],
- }
-
def protocol_retry_notice(self) -> str:
return self._pipeline._t(
"notices.protocol_retry",
diff --git a/deeptutor/agents/visualize/utils.py b/deeptutor/agents/visualize/utils.py
index 1552fb79e..42dcf41da 100644
--- a/deeptutor/agents/visualize/utils.py
+++ b/deeptutor/agents/visualize/utils.py
@@ -4,10 +4,11 @@ from __future__ import annotations
import json
import re
-from typing import Any
import defusedxml.ElementTree as ET
+from deeptutor.agents._shared.json_output import extract_json_object
+
_MERMAID_KEYWORDS = (
"graph",
"flowchart",
@@ -31,60 +32,6 @@ _MERMAID_KEYWORDS = (
)
-def extract_json_object(text: str) -> dict[str, Any]:
- """Extract a JSON object from raw model output."""
- raw = (text or "").strip()
- if not raw:
- return {}
-
- fenced = re.findall(r"```(?:json)?\s*([\s\S]*?)\s*```", raw)
- candidates = fenced + [raw]
-
- for candidate in candidates:
- try:
- parsed = json.loads(candidate)
- if isinstance(parsed, dict):
- return parsed
- except json.JSONDecodeError:
- parsed = _decode_first_json_object(candidate)
- if parsed is not None:
- return parsed
-
- start = raw.find("{")
- end = raw.rfind("}")
- if start != -1 and end != -1 and end > start:
- snippet = raw[start : end + 1]
- try:
- return json.loads(snippet)
- except json.JSONDecodeError:
- parsed = _decode_first_json_object(snippet)
- if parsed is not None:
- return parsed
-
- raise json.JSONDecodeError("No JSON object found", raw, 0)
-
-
-def _decode_first_json_object(text: str) -> dict[str, Any] | None:
- decoder = json.JSONDecoder()
- stripped = (text or "").lstrip()
- if not stripped:
- return None
-
- starts = [0]
- brace_index = stripped.find("{")
- if brace_index > 0:
- starts.append(brace_index)
-
- for start in starts:
- try:
- parsed, _end = decoder.raw_decode(stripped[start:])
- except json.JSONDecodeError:
- continue
- if isinstance(parsed, dict):
- return parsed
- return None
-
-
def extract_code_block(text: str, language: str = "") -> str:
"""Extract a fenced code block from LLM output.
diff --git a/deeptutor/book/storage.py b/deeptutor/book/storage.py
index ba2afdfb3..ec6dddb69 100644
--- a/deeptutor/book/storage.py
+++ b/deeptutor/book/storage.py
@@ -24,11 +24,11 @@ import asyncio
from datetime import datetime, timezone
import json
import logging
-import os
from pathlib import Path
import shutil
from typing import Any
+from deeptutor.services.file_io import atomic_write_text as _atomic_write_text
from deeptutor.services.path_service import get_path_service
from .models import Book, BookInputs, ExplorationReport, Page, Progress, Spine
@@ -41,20 +41,6 @@ logger = logging.getLogger(__name__)
# ─────────────────────────────────────────────────────────────────────────────
-def _atomic_write_text(path: Path, text: str) -> None:
- """Write *text* to *path* atomically (write-temp + rename)."""
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_suffix(path.suffix + ".tmp")
- with open(tmp, "w", encoding="utf-8") as f:
- f.write(text)
- f.flush()
- try:
- os.fsync(f.fileno())
- except OSError:
- pass
- os.replace(tmp, path)
-
-
def _atomic_write_json(path: Path, payload: Any) -> None:
text = json.dumps(payload, ensure_ascii=False, indent=2, default=str)
_atomic_write_text(path, text)
diff --git a/deeptutor/capabilities/explore_context/explorer.py b/deeptutor/capabilities/explore_context/explorer.py
index db89c9574..af23cd747 100644
--- a/deeptutor/capabilities/explore_context/explorer.py
+++ b/deeptutor/capabilities/explore_context/explorer.py
@@ -36,6 +36,7 @@ from deeptutor.core.agentic import (
can_use_native_tool_calling,
dispatch_tool_calls,
)
+from deeptutor.core.agentic.messages import assistant_message_with_tool_calls
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id
@@ -213,7 +214,7 @@ class ContextExplorer:
if not result.tool_calls:
investigation = result.text
break
- messages.append(_assistant_with_tool_calls(result.text, result.tool_calls))
+ messages.append(assistant_message_with_tool_calls(result.text, result.tool_calls))
dispatch = await dispatch_tool_calls(
tool_calls=result.tool_calls,
context=context,
@@ -527,19 +528,4 @@ def _content_chars(message: dict[str, Any]) -> int:
return 0
-def _assistant_with_tool_calls(content: str, tool_calls: list[dict[str, Any]]) -> dict[str, Any]:
- return {
- "role": "assistant",
- "content": content or None,
- "tool_calls": [
- {
- "id": tc["id"],
- "type": "function",
- "function": {"name": tc["name"], "arguments": tc.get("arguments") or "{}"},
- }
- for tc in tool_calls
- ],
- }
-
-
__all__ = ["ContextExplorer", "EXPLORE_STAGE"]
diff --git a/deeptutor/co_writer/storage.py b/deeptutor/co_writer/storage.py
index 22897b1ed..7b582e7cd 100644
--- a/deeptutor/co_writer/storage.py
+++ b/deeptutor/co_writer/storage.py
@@ -17,7 +17,6 @@ from __future__ import annotations
import json
import logging
-import os
from pathlib import Path
import shutil
import time
@@ -26,6 +25,7 @@ import uuid
from pydantic import BaseModel, Field
+from deeptutor.services.file_io import atomic_write_text as _atomic_write_text
from deeptutor.services.path_service import get_path_service
logger = logging.getLogger(__name__)
@@ -51,20 +51,6 @@ class CoWriterDocumentSummary(BaseModel):
preview: str = ""
-def _atomic_write_text(path: Path, text: str) -> None:
- """Write *text* to *path* atomically (write-temp + rename)."""
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_suffix(path.suffix + ".tmp")
- with open(tmp, "w", encoding="utf-8") as f:
- f.write(text)
- f.flush()
- try:
- os.fsync(f.fileno())
- except OSError:
- pass
- os.replace(tmp, path)
-
-
def _atomic_write_json(path: Path, payload: Any) -> None:
text = json.dumps(payload, ensure_ascii=False, indent=2, default=str)
_atomic_write_text(path, text)
diff --git a/deeptutor/core/agentic/labeled_step.py b/deeptutor/core/agentic/labeled_step.py
index b35b71858..7c240c880 100644
--- a/deeptutor/core/agentic/labeled_step.py
+++ b/deeptutor/core/agentic/labeled_step.py
@@ -49,6 +49,11 @@ from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import merge_trace_metadata
from deeptutor.services.llm import clean_thinking_tags
from deeptutor.services.llm.multimodal import should_degrade_to_text, strip_image_parts_inplace
+from deeptutor.services.llm.request_compat import (
+ is_image_input_unsupported,
+ is_stream_options_unsupported,
+ is_tool_schema_unsupported,
+)
# Reasoning models (Qwen, Deepseek-R1 via certain proxies, etc.) sometimes
# inline a literal ``<think>...</think>`` block in the content stream before
@@ -120,80 +125,6 @@ def _message_content_chars(message: dict[str, Any]) -> int:
return len(str(content))
-def _error_text(exc: Exception) -> str:
- """Best-effort lowercase error body for provider-capability detection."""
- response = getattr(exc, "response", None)
- body = (
- getattr(exc, "body", None)
- or getattr(exc, "doc", None)
- or getattr(response, "text", None)
- or getattr(exc, "message", None)
- or str(exc)
- )
- return str(body).lower()
-
-
-def _is_stream_options_unsupported(exc: Exception) -> bool:
- """Detect providers that reject OpenAI's ``stream_options`` parameter."""
- text = _error_text(exc)
- return any(
- marker in text
- for marker in (
- "stream_options",
- "stream options",
- "unknown parameter",
- "unrecognized request argument",
- "unsupported parameter",
- "extra inputs are not permitted",
- "unexpected keyword",
- )
- )
-
-
-def _is_tool_schema_unsupported(exc: Exception) -> bool:
- """Detect providers that reject native tool/function-calling schemas."""
- text = _error_text(exc)
- return any(
- marker in text
- for marker in (
- "tool",
- "function_declaration",
- "function declaration",
- "function_declarations",
- "tool_choice",
- "parameters.properties",
- "404_not_found",
- "404 not_found",
- )
- )
-
-
-def _is_image_input_unsupported(exc: Exception) -> bool:
- """Detect providers/models that reject image (multimodal) content.
-
- Covers both explicit "no vision" rejections and the structural errors a
- text-only OpenAI-compatible model raises when it receives the content
- *array* the image injection produced (it expected a plain string).
- Transient errors (rate limit / 5xx) never mention these markers, so they
- don't trigger the image fallback.
- """
- text = _error_text(exc)
- return any(
- marker in text
- for marker in (
- "image",
- "vision",
- "multimodal",
- "image_url",
- "content type",
- "must be a string",
- "expected a string",
- "expected string",
- "invalid type for 'messages",
- )
- )
-
-
async def run_labeled_step(
*,
client: Any,
@@ -475,11 +406,11 @@ async def run_labeled_step(
try:
return await client.chat.completions.create(**kwargs)
except Exception as exc:
- if auto_stream_options_added and _is_stream_options_unsupported(exc):
+ if auto_stream_options_added and is_stream_options_unsupported(exc):
retry_kwargs = dict(kwargs)
retry_kwargs.pop("stream_options", None)
return await client.chat.completions.create(**retry_kwargs)
- if tool_schemas and _is_tool_schema_unsupported(exc):
+ if tool_schemas and is_tool_schema_unsupported(exc):
await stream.progress(
"Provider rejected native tool schemas; retrying without tools.",
source=source,
@@ -497,7 +428,7 @@ async def run_labeled_step(
# it is not in the known-vision allowlist. Strip images in place
# (so they aren't re-sent on later loop iterations) and retry the
# turn text-only rather than hard-failing.
- if _is_image_input_unsupported(exc) and should_degrade_to_text(
+ if is_image_input_unsupported(exc) and should_degrade_to_text(
binding, model, kwargs.get("messages") or []
):
strip_image_parts_inplace(kwargs["messages"])
diff --git a/deeptutor/core/agentic/loop.py b/deeptutor/core/agentic/loop.py
index c0882eaab..e34e9bc33 100644
--- a/deeptutor/core/agentic/loop.py
+++ b/deeptutor/core/agentic/loop.py
@@ -30,6 +30,7 @@ from typing import Any, Protocol
from deeptutor.core.agentic.labeled_step import LabeledStepResult, run_labeled_step
from deeptutor.core.agentic.labels import LABEL_UNKNOWN, find_inline_labels
+from deeptutor.core.agentic.messages import assistant_message_with_tool_calls
from deeptutor.core.agentic.tool_dispatch import DispatchOutcome
from deeptutor.core.agentic.usage import UsageTracker
from deeptutor.core.stream_bus import StreamBus
@@ -113,14 +114,6 @@ class LoopHost(Protocol):
"""
return None
- def assistant_message_with_tool_calls(
- self,
- *,
- content: str,
- tool_calls: list[dict[str, Any]],
- ) -> dict[str, Any]:
- """Format the assistant turn that carries this iteration's tool calls."""
-
def protocol_retry_notice(self) -> str:
"""Notice text shown when a protocol violation triggers a retry."""
@@ -302,12 +295,7 @@ async def run_agentic_loop(
break
if protocol.tool_label is not None and step.label == protocol.tool_label:
- messages.append(
- host.assistant_message_with_tool_calls(
- content=step.text,
- tool_calls=step.tool_calls,
- )
- )
+ messages.append(assistant_message_with_tool_calls(step.text, step.tool_calls))
outcome = await host.dispatch_tools(
iteration=iteration,
tool_calls=step.tool_calls,
diff --git a/deeptutor/core/agentic/messages.py b/deeptutor/core/agentic/messages.py
new file mode 100644
index 000000000..853f15804
--- /dev/null
+++ b/deeptutor/core/agentic/messages.py
@@ -0,0 +1,30 @@
+"""Canonical message builders for agentic conversations."""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+def assistant_message_with_tool_calls(
+ content: str,
+ tool_calls: list[dict[str, Any]],
+) -> dict[str, Any]:
+ """Build the assistant message that precedes tool result messages."""
+ return {
+ "role": "assistant",
+ "content": content or None,
+ "tool_calls": [
+ {
+ "id": tool_call["id"],
+ "type": "function",
+ "function": {
+ "name": tool_call["name"],
+ "arguments": tool_call.get("arguments") or "{}",
+ },
+ }
+ for tool_call in tool_calls
+ ],
+ }
+
+
+__all__ = ["assistant_message_with_tool_calls"]
diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.py
index 3665089c5..a710a8230 100644
--- a/deeptutor/learning/storage.py
+++ b/deeptutor/learning/storage.py
@@ -4,27 +4,15 @@ import json
from pathlib import Path
import threading
import time
-import uuid
from deeptutor.learning.models import LearningProgress
+from deeptutor.services.file_io import atomic_write_text as _atomic_write_text
from deeptutor.services.path_service import get_path_service
# Module-level lock so CAS semantics hold across all store instances.
_cas_lock = threading.Lock()
-def _atomic_write_text(path: Path, text: str) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_suffix(path.suffix + f".tmp.{uuid.uuid4().hex}")
- try:
- tmp.write_text(text, encoding="utf-8")
- tmp.replace(path)
- except BaseException:
- # Don't leave an orphaned temp file behind on write/replace failure.
- tmp.unlink(missing_ok=True)
- raise
-
-
class LearningStore:
def __init__(self, root: Path | None = None) -> None:
self._root = root or (get_path_service().get_workspace_dir() / "learning")
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index 929251fb6..c75f5c025 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -4,9 +4,9 @@ from copy import deepcopy
import json
import os
from pathlib import Path
-import tempfile
from typing import Any, Callable
+from deeptutor.services.file_io import atomic_write_json as _atomic_write_json
from deeptutor.services.path_service import get_path_service
from .origins import normalize_origins
@@ -283,20 +283,6 @@ def _json_object(path: Path) -> dict[str, Any]:
return loaded if isinstance(loaded, dict) else {}
-def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(
- "w",
- encoding="utf-8",
- dir=str(path.parent),
- delete=False,
- ) as handle:
- json.dump(payload, handle, indent=2, ensure_ascii=False)
- handle.write("\n")
- tmp_path = Path(handle.name)
- tmp_path.replace(path)
-
-
def _string(value: Any) -> str:
return "" if value is None else str(value).strip()
diff --git a/deeptutor/services/file_io.py b/deeptutor/services/file_io.py
new file mode 100644
index 000000000..b895914d6
--- /dev/null
+++ b/deeptutor/services/file_io.py
@@ -0,0 +1,58 @@
+"""Small, dependency-free helpers for durable service files."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import tempfile
+from typing import Any
+
+
+def atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
+ """Write *payload* as UTF-8 JSON without exposing a partial target file."""
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary_path: Path | None = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ "w",
+ encoding="utf-8",
+ dir=str(path.parent),
+ delete=False,
+ ) as handle:
+ temporary_path = Path(handle.name)
+ json.dump(payload, handle, indent=2, ensure_ascii=False)
+ handle.write("\n")
+ temporary_path.replace(path)
+ finally:
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
+
+
+def atomic_write_text(path: Path, text: str) -> None:
+ """Write UTF-8 text with a same-directory atomic replacement."""
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary_path: Path | None = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ "w",
+ encoding="utf-8",
+ dir=str(path.parent),
+ delete=False,
+ ) as handle:
+ temporary_path = Path(handle.name)
+ handle.write(text)
+ handle.flush()
+ try:
+ os.fsync(handle.fileno())
+ except OSError:
+ pass
+ temporary_path.replace(path)
+ finally:
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
+
+
+__all__ = ["atomic_write_json", "atomic_write_text"]
diff --git a/deeptutor/services/llm/request_compat.py b/deeptutor/services/llm/request_compat.py
new file mode 100644
index 000000000..3ac08ac0a
--- /dev/null
+++ b/deeptutor/services/llm/request_compat.py
@@ -0,0 +1,78 @@
+"""Provider-error classifiers used by retry and graceful-degradation paths."""
+
+from __future__ import annotations
+
+
+def error_text(exc: Exception) -> str:
+ """Return the best available lowercase provider error body."""
+ response = getattr(exc, "response", None)
+ body = (
+ getattr(exc, "body", None)
+ or getattr(exc, "doc", None)
+ or getattr(response, "text", None)
+ or getattr(exc, "message", None)
+ or str(exc)
+ )
+ return str(body).lower()
+
+
+def is_stream_options_unsupported(exc: Exception) -> bool:
+ """Whether a provider rejected OpenAI's ``stream_options`` parameter."""
+ text = error_text(exc)
+ return any(
+ marker in text
+ for marker in (
+ "stream_options",
+ "stream options",
+ "unknown parameter",
+ "unrecognized request argument",
+ "unsupported parameter",
+ "extra inputs are not permitted",
+ "unexpected keyword",
+ )
+ )
+
+
+def is_tool_schema_unsupported(exc: Exception) -> bool:
+ """Whether a provider rejected native tool/function-calling schemas."""
+ text = error_text(exc)
+ return any(
+ marker in text
+ for marker in (
+ "tool",
+ "function_declaration",
+ "function declaration",
+ "function_declarations",
+ "tool_choice",
+ "parameters.properties",
+ "404_not_found",
+ "404 not_found",
+ )
+ )
+
+
+def is_image_input_unsupported(exc: Exception) -> bool:
+ """Whether a provider or model rejected multimodal message content."""
+ text = error_text(exc)
+ return any(
+ marker in text
+ for marker in (
+ "image",
+ "vision",
+ "multimodal",
+ "image_url",
+ "content type",
+ "must be a string",
+ "expected a string",
+ "expected string",
+ "invalid type for 'messages",
+ )
+ )
+
+
+__all__ = [
+ "error_text",
+ "is_image_input_unsupported",
+ "is_stream_options_unsupported",
+ "is_tool_schema_unsupported",
+]
diff --git a/deeptutor/services/rag/pipelines/graphrag/storage.py b/deeptutor/services/rag/pipelines/graphrag/storage.py
index aaef7e7d0..690de9c02 100644
--- a/deeptutor/services/rag/pipelines/graphrag/storage.py
+++ b/deeptutor/services/rag/pipelines/graphrag/storage.py
@@ -20,11 +20,10 @@ manager about GraphRAG internals.
from __future__ import annotations
from datetime import datetime, timezone
-import json
import logging
from pathlib import Path
-import tempfile
-from typing import Any
+
+from deeptutor.services.file_io import atomic_write_json
logger = logging.getLogger(__name__)
@@ -45,17 +44,6 @@ OUTPUT_TABLES = (
)
-def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(
- "w", encoding="utf-8", dir=str(path.parent), delete=False
- ) as handle:
- json.dump(payload, handle, indent=2, ensure_ascii=False)
- handle.write("\n")
- tmp_path = Path(handle.name)
- tmp_path.replace(path)
-
-
def input_dir(root_dir: Path) -> Path:
return Path(root_dir) / INPUT_DIRNAME
@@ -94,7 +82,7 @@ def write_meta(root_dir: Path) -> None:
"created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
**embedding_meta_fields(),
}
- _atomic_write_json(target / META_FILENAME, payload)
+ atomic_write_json(target / META_FILENAME, payload)
__all__ = [
diff --git a/deeptutor/services/rag/pipelines/lightrag/storage.py b/deeptutor/services/rag/pipelines/lightrag/storage.py
index a91bc7af5..eb4941156 100644
--- a/deeptutor/services/rag/pipelines/lightrag/storage.py
+++ b/deeptutor/services/rag/pipelines/lightrag/storage.py
@@ -23,9 +23,10 @@ from datetime import datetime, timezone
import json
import logging
from pathlib import Path
-import tempfile
from typing import Any
+from deeptutor.services.file_io import atomic_write_json
+
logger = logging.getLogger(__name__)
META_FILENAME = "meta.json"
@@ -40,17 +41,6 @@ _SUCCESS_STATUSES = {"processed", "completed", "done", "success", "indexed"}
_FAILED_STATUSES = {"failed", "error"}
-def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(
- "w", encoding="utf-8", dir=str(path.parent), delete=False
- ) as handle:
- json.dump(payload, handle, indent=2, ensure_ascii=False)
- handle.write("\n")
- tmp_path = Path(handle.name)
- tmp_path.replace(path)
-
-
def working_dir(root_dir: Path) -> Path:
"""LightRAG's working dir == the version-N root."""
return Path(root_dir)
@@ -172,7 +162,7 @@ def write_meta(root_dir: Path) -> None:
"created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
**embedding_meta_fields(),
}
- _atomic_write_json(target / META_FILENAME, payload)
+ atomic_write_json(target / META_FILENAME, payload)
__all__ = [
diff --git a/deeptutor/services/rag/pipelines/pageindex/storage.py b/deeptutor/services/rag/pipelines/pageindex/storage.py
index 1884b2c82..2eeb83566 100644
--- a/deeptutor/services/rag/pipelines/pageindex/storage.py
+++ b/deeptutor/services/rag/pipelines/pageindex/storage.py
@@ -14,9 +14,10 @@ from datetime import datetime, timezone
import json
import logging
from pathlib import Path
-import tempfile
from typing import Any
+from deeptutor.services.file_io import atomic_write_json
+
logger = logging.getLogger(__name__)
MANIFEST_FILENAME = "pageindex_docs.json"
@@ -28,17 +29,6 @@ def _empty_manifest() -> dict[str, Any]:
return {"provider": PROVIDER, "docs": {}}
-def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(
- "w", encoding="utf-8", dir=str(path.parent), delete=False
- ) as handle:
- json.dump(payload, handle, indent=2, ensure_ascii=False)
- handle.write("\n")
- tmp_path = Path(handle.name)
- tmp_path.replace(path)
-
-
def manifest_path(storage_dir: Path) -> Path:
return Path(storage_dir) / MANIFEST_FILENAME
@@ -63,7 +53,7 @@ def read_manifest(storage_dir: Path | None) -> dict[str, Any]:
def write_manifest(storage_dir: Path, manifest: dict[str, Any]) -> None:
- _atomic_write_json(manifest_path(storage_dir), manifest)
+ atomic_write_json(manifest_path(storage_dir), manifest)
def write_meta(storage_dir: Path) -> None:
@@ -80,7 +70,7 @@ def write_meta(storage_dir: Path) -> None:
"layout": "flat",
"created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
}
- _atomic_write_json(target / META_FILENAME, payload)
+ atomic_write_json(target / META_FILENAME, payload)
def doc_entries(manifest: dict[str, Any]) -> dict[str, Any]:
diff --git a/tests/agents/test_shared_json_output.py b/tests/agents/test_shared_json_output.py
new file mode 100644
index 000000000..517a53408
--- /dev/null
+++ b/tests/agents/test_shared_json_output.py
@@ -0,0 +1,26 @@
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from deeptutor.agents._shared.json_output import extract_json_object
+
+
+ ("text", "expected"),
+ [
+ ("", {}),
+ ('{"value": 1}', {"value": 1}),
+ ('Result:\n```json\n{"value": 2}\n```', {"value": 2}),
+ ('Model preface\n{"value": 3}', {"value": 3}),
+ ('{"value": 4}\nTrailing explanation', {"value": 4}),
+ ],
+)
+def test_extract_json_object(text: str, expected: dict[str, int]) -> None:
+ assert extract_json_object(text) == expected
+
+
+def test_extract_json_object_rejects_output_without_an_object() -> None:
+ with pytest.raises(json.JSONDecodeError, match="No JSON object found"):
+ extract_json_object("No structured output")
diff --git a/tests/core/test_agentic_messages.py b/tests/core/test_agentic_messages.py
new file mode 100644
index 000000000..5c9da91c2
--- /dev/null
+++ b/tests/core/test_agentic_messages.py
@@ -0,0 +1,39 @@
+from __future__ import annotations
+
+from deeptutor.core.agentic.messages import assistant_message_with_tool_calls
+
+
+def test_assistant_message_with_tool_calls_normalizes_empty_values() -> None:
+ message = assistant_message_with_tool_calls(
+ content="",
+ tool_calls=[{"id": "call-1", "name": "search"}],
+ )
+
+ assert message == {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call-1",
+ "type": "function",
+ "function": {"name": "search", "arguments": "{}"},
+ }
+ ],
+ }
+
+
+def test_assistant_message_with_tool_calls_preserves_order_and_arguments() -> None:
+ message = assistant_message_with_tool_calls(
+ content="I will inspect both sources.",
+ tool_calls=[
+ {"id": "call-1", "name": "search", "arguments": '{"q":"one"}'},
+ {"id": "call-2", "name": "read", "arguments": '{"id":2}'},
+ ],
+ )
+
+ assert message["content"] == "I will inspect both sources."
+ assert [call["id"] for call in message["tool_calls"]] == ["call-1", "call-2"]
+ assert message["tool_calls"][1]["function"] == {
+ "name": "read",
+ "arguments": '{"id":2}',
+ }
diff --git a/tests/knowledge/test_manager_delete.py b/tests/knowledge/test_manager_delete.py
index f1f4ace3a..d98d7eeca 100644
--- a/tests/knowledge/test_manager_delete.py
+++ b/tests/knowledge/test_manager_delete.py
@@ -49,20 +49,23 @@ def test_delete_knowledge_base_clears_config_when_rmtree_fails(
manager = KnowledgeBaseManager(base_dir=str(tmp_path))
_create_kb(manager, "broken")
- import shutil as _shutil
+ from deeptutor.knowledge import manager as manager_module
def _rmtree_always_errors(path, onerror=None, **_kwargs):
# Simulate a persistent OSError that chmod-retry cannot recover from.
if onerror is not None:
- onerror(_shutil.rmtree, str(path), (OSError, OSError("busy"), None))
-
- monkeypatch.setattr(_shutil, "rmtree", _rmtree_always_errors)
- # The manager imports shutil at module level, so patch there too.
- from deeptutor.knowledge import manager as manager_mod
-
- monkeypatch.setattr(manager_mod.shutil, "rmtree", _rmtree_always_errors)
-
- assert manager.delete_knowledge_base("broken", confirm=True) is True
+ onerror(
+ manager_module.shutil.rmtree,
+ str(path),
+ (OSError, OSError("busy"), None),
+ )
+
+ # manager_module.shutil is the global stdlib module object. Restore it
+ # immediately after the behavior under test so pytest's tmp cleanup keeps
+ # the real rmtree implementation.
+ with monkeypatch.context() as scoped_patch:
+ scoped_patch.setattr(manager_module.shutil, "rmtree", _rmtree_always_errors)
+ assert manager.delete_knowledge_base("broken", confirm=True) is True
assert "broken" not in _read_config(manager.config_file).get("knowledge_bases", {})
diff --git a/tests/services/llm/test_request_compat.py b/tests/services/llm/test_request_compat.py
new file mode 100644
index 000000000..9f1b34374
--- /dev/null
+++ b/tests/services/llm/test_request_compat.py
@@ -0,0 +1,36 @@
+from __future__ import annotations
+
+from deeptutor.services.llm.request_compat import (
+ error_text,
+ is_image_input_unsupported,
+ is_stream_options_unsupported,
+ is_tool_schema_unsupported,
+)
+
+
+class _Response:
+ text = "Unsupported parameter: stream_options"
+
+
+class _ProviderError(Exception):
+ response = _Response()
+
+
+def test_error_text_prefers_provider_response_body() -> None:
+ assert error_text(_ProviderError("generic message")) == (
+ "unsupported parameter: stream_options"
+ )
+
+
+def test_request_compatibility_classifiers_match_known_provider_errors() -> None:
+ assert is_stream_options_unsupported(ValueError("unknown parameter: stream_options"))
+ assert is_tool_schema_unsupported(ValueError("function_declaration is unsupported"))
+ assert is_image_input_unsupported(ValueError("content must be a string"))
+
+
+def test_request_compatibility_classifiers_ignore_unrelated_errors() -> None:
+ error = RuntimeError("rate limit exceeded")
+
+ assert not is_stream_options_unsupported(error)
+ assert not is_tool_schema_unsupported(error)
+ assert not is_image_input_unsupported(error)
diff --git a/tests/services/test_file_io.py b/tests/services/test_file_io.py
new file mode 100644
index 000000000..1163419db
--- /dev/null
+++ b/tests/services/test_file_io.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from deeptutor.services import file_io
+from deeptutor.services.file_io import atomic_write_json, atomic_write_text
+
+
+def test_atomic_write_json_creates_parent_and_replaces_content(tmp_path: Path) -> None:
+ path = tmp_path / "nested" / "settings.json"
+
+ atomic_write_json(path, {"greeting": "你好"})
+
+ assert path.read_text(encoding="utf-8") == '{\n "greeting": "你好"\n}\n'
+
+ atomic_write_json(path, {"value": 2})
+
+ assert json.loads(path.read_text(encoding="utf-8")) == {"value": 2}
+ assert list(path.parent.iterdir()) == [path]
+
+
+def test_atomic_write_json_cleans_up_temporary_file_on_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ path = tmp_path / "nested" / "settings.json"
+
+ def fail_dump(*_args: object, **_kwargs: object) -> None:
+ raise RuntimeError("serialization failed")
+
+ monkeypatch.setattr(file_io.json, "dump", fail_dump)
+
+ with pytest.raises(RuntimeError, match="serialization failed"):
+ atomic_write_json(path, {"value": 1})
+
+ assert list(path.parent.iterdir()) == []
+
+
+def test_atomic_write_text_creates_parent_and_replaces_content(tmp_path: Path) -> None:
+ path = tmp_path / "nested" / "note.md"
+
+ atomic_write_text(path, "first")
+ atomic_write_text(path, "second")
+
+ assert path.read_text(encoding="utf-8") == "second"
+ assert list(path.parent.iterdir()) == [path]
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index 17d5bfee0..40bf62642 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -1407,6 +1407,31 @@ export default function ChatPage() {
[fileToAttachment, filterAndReportFiles],
);
+ // Connected subagents are stored as ``type: subagent`` KBs. Derive the
+ // selected one before the send callback so the callback can depend on the
+ // current selection instead of capturing an undeclared-later value.
+ const agentNameSet = useMemo(
+ () =>
+ new Set(
+ knowledgeBases
+ .filter((kb) => kb.metadata?.type === "subagent")
+ .map((kb) => kb.name),
+ ),
+ [knowledgeBases],
+ );
+ const selectedAgent = useMemo(
+ () => state.knowledgeBases.find((name) => agentNameSet.has(name)) ?? null,
+ [state.knowledgeBases, agentNameSet],
+ );
+ // How many times DeepTutor may consult the selected agent this turn. Seeded
+ // from the configured default; the composer's stepper overrides it per turn.
+ const [subagentBudget, setSubagentBudget] = useState<number | null>(null);
+ useEffect(() => {
+ void getSubagentSettings()
+ .then((settings) => setSubagentBudget(settings.consult_budget))
+ .catch(() => undefined);
+ }, []);
+
const handleSend = useCallback(
async (content: string) => {
if (
@@ -1508,6 +1533,7 @@ export default function ChatPage() {
quizPdf,
researchConfig,
researchValidation,
+ selectedAgent,
selectedHistorySessions.length,
selectedAgentSessions.length,
selectedMemoryFiles.length,
@@ -1517,6 +1543,7 @@ export default function ChatPage() {
sendMessage,
shouldAutoScrollRef,
state.isStreaming,
+ subagentBudget,
t,
visualizeConfig,
],
@@ -1582,18 +1609,8 @@ export default function ChatPage() {
[setKBs, state.knowledgeBases],
);
- // Connected subagents are stored as ``type: subagent`` KBs (so selection
- // rides the same knowledge_bases path), but in the composer they get their
- // own single-select Bot chip — distinct from real knowledge bases.
- const agentNameSet = useMemo(
- () =>
- new Set(
- knowledgeBases
- .filter((kb) => kb.metadata?.type === "subagent")
- .map((kb) => kb.name),
- ),
- [knowledgeBases],
- );
+ // Real knowledge bases and connected subagents render as separate composer
+ // controls even though both travel through the knowledge_bases request path.
const kbOptions = useMemo(
() => knowledgeBases.filter((kb) => kb.metadata?.type !== "subagent"),
[knowledgeBases],
@@ -1609,10 +1626,6 @@ export default function ChatPage() {
() => state.knowledgeBases.filter((n) => !agentNameSet.has(n)),
[state.knowledgeBases, agentNameSet],
);
- const selectedAgent = useMemo(
- () => state.knowledgeBases.find((n) => agentNameSet.has(n)) ?? null,
- [state.knowledgeBases, agentNameSet],
- );
const handleSelectAgent = useCallback(
(name: string | null) => {
// Single-select: clear any selected agent, then set the new one (if any).
@@ -1632,15 +1645,6 @@ export default function ChatPage() {
agentPreselectDoneRef.current = true;
handleSelectAgent(name);
}, [agentNameSet, handleSelectAgent]);
- // How many times DeepTutor may consult the selected agent this turn. Seeded
- // from the configured default; the composer's stepper overrides it per turn
- // (sent in the request config, read by the subagent capability).
- const [subagentBudget, setSubagentBudget] = useState<number | null>(null);
- useEffect(() => {
- void getSubagentSettings()
- .then((s) => setSubagentBudget(s.consult_budget))
- .catch(() => undefined);
- }, []);
const handleSelectNotebookPicker = useCallback(() => {
setShowNotebookPicker(true);
}, []);
diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsx
index 7c43041bf..707493e3e 100644
--- a/web/components/chat/home/ComposerInput.tsx
+++ b/web/components/chat/home/ComposerInput.tsx
@@ -6,6 +6,7 @@ import {
useCallback,
useEffect,
useImperativeHandle,
+ useMemo,
useRef,
useState,
type RefObject,
@@ -161,11 +162,15 @@ export const ComposerInput = memo(
// Main chat passes ``onSelectAgent`` → ``@`` picks a connected agent. Other
// surfaces (quiz follow-up) omit it and keep the @ Space menu.
const agentMentionMode = Boolean(onSelectAgent);
- const filteredAgents = agentMentionMode
- ? connectedAgents.filter((a) =>
- a.name.toLowerCase().includes(atQuery.toLowerCase()),
- )
- : [];
+ const filteredAgents = useMemo(
+ () =>
+ agentMentionMode
+ ? connectedAgents.filter((agent) =>
+ agent.name.toLowerCase().includes(atQuery.toLowerCase()),
+ )
+ : [],
+ [agentMentionMode, atQuery, connectedAgents],
+ );
// Latest text mirrored into a ref by the change handlers (never updated
// during render). The @space handlers and the imperative handle read
diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsx
index dfccb8c3e..896e1d48d 100644
--- a/web/components/settings/SettingsContext.tsx
+++ b/web/components/settings/SettingsContext.tsx
@@ -501,11 +501,10 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
useState<EmbeddingCapabilities | null>(null);
const [tourStepIndex, setTourStepIndex] = useState(-1);
const eventSourceRef = useRef<EventSource | null>(null);
- // Extensions register their latest dirty/save on each render. We track
- // a "version" counter to trigger re-renders for `hasUnsavedChanges`
- // when an extension's dirty flag flips.
+ // Extensions register their latest dirty/save on each render. Keep the
+ // derived dirty state explicit instead of using an indirect version counter.
const extensionsRef = useRef<Map<string, SettingsExtension>>(new Map());
- const [extensionsVersion, setExtensionsVersion] = useState(0);
+ const [hasDirtyExtension, setHasDirtyExtension] = useState(false);
const registerExtension = useCallback(
(key: string, ext: SettingsExtension | null) => {
const map = extensionsRef.current;
@@ -513,17 +512,21 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
if (ext === null) {
if (prev === undefined) return;
map.delete(key);
- setExtensionsVersion((n) => n + 1);
+ setHasDirtyExtension(
+ Array.from(map.values()).some((extension) => extension.dirty),
+ );
return;
}
if (prev && prev.dirty === ext.dirty && prev.save === ext.save) {
return;
}
map.set(key, ext);
- // Only bump version when dirty flips — save fn changes every render
- // are common and should not re-render the toolbar.
+ // Only recompute the dirty summary when dirty flips — save fn changes
+ // every render are common and should not re-render the toolbar.
if (prev?.dirty !== ext.dirty) {
- setExtensionsVersion((n) => n + 1);
+ setHasDirtyExtension(
+ Array.from(map.values()).some((extension) => extension.dirty),
+ );
}
},
[],
@@ -933,22 +936,20 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
draft.services.embedding.active_model_id,
]);
+ const llmActiveProfileId = draft.services.llm.active_profile_id;
+ const llmActiveModelId = draft.services.llm.active_model_id;
useEffect(() => {
setLlmContextDetection((current) => {
if (!current) return null;
- const llm = draft.services.llm;
if (
- current.profileId === llm.active_profile_id &&
- current.modelId === llm.active_model_id
+ current.profileId === llmActiveProfileId &&
+ current.modelId === llmActiveModelId
) {
return current;
}
return null;
});
- }, [
- draft.services.llm.active_profile_id,
- draft.services.llm.active_model_id,
- ]);
+ }, [llmActiveProfileId, llmActiveModelId]);
const runDetailedTest = useCallback(
async (service: ServiceName) => {
@@ -1138,17 +1139,12 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
// ── Derived ─────────────────────────────────────────────────────────────
const hasUnsavedChanges = useMemo(() => {
- const catalogDirty =
- catalogEditable === true &&
- JSON.stringify(catalog) !== JSON.stringify(draft);
- if (catalogDirty) return true;
- // Any registered extension dirty also counts. Reading from the ref is
- // safe because `extensionsVersion` invalidates this memo on flip.
- for (const ext of extensionsRef.current.values()) {
- if (ext.dirty) return true;
- }
- return false;
- }, [catalog, catalogEditable, draft, extensionsVersion]);
+ return (
+ hasDirtyExtension ||
+ (catalogEditable === true &&
+ JSON.stringify(catalog) !== JSON.stringify(draft))
+ );
+ }, [catalog, catalogEditable, draft, hasDirtyExtension]);
const settingsLoading = catalogEditable === null;