diff --git a/README.md b/README.md index beb1a60de..9c15f1c64 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ ### 📦 Releases +> **[2026.4.11]** [v1.0.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.2) — Search consolidation simplification with SearXNG fallback, provider switch fix, explicit runtime config in test runner, and frontend resource leak fixes. + > **[2026.4.10]** [v1.0.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.1) — New Visualize capability with Chart.js/SVG rendering pipeline, quiz duplicate prevention with generation history, o4-mini model support, and server logging improvements. > **[2026.4.10]** [v1.0.0-beta.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.4) — Embedding progress tracking with HTTP 429 rate limit retry, cross-platform start tour dependency management, and case-insensitive MIME validation fix. diff --git a/assets/releases/ver1-0-2.md b/assets/releases/ver1-0-2.md new file mode 100644 index 000000000..178e2932d --- /dev/null +++ b/assets/releases/ver1-0-2.md @@ -0,0 +1,26 @@ +# DeepTutor v1.0.2 Release Notes + +**Release Date:** 2026.04.11 + +## Highlights + +### Search Consolidation Simplification & SearXNG Fallback +Removed the explicit `consolidation_type` parameter — consolidation now runs automatically for any provider that doesn't return its own answer. A new generic fallback formatter handles providers (e.g. SearXNG) that lack a dedicated Jinja2 template, fixing the "no template consolidation available" error. The `CONSOLIDATION_TYPES` constant and related config fields have been removed. + +### Provider Switch Fix +Settings page now always overwrites `base_url` when the user selects a different provider, instead of only filling it when the field was previously empty. This prevents stale base URLs from persisting across provider changes. + +### Explicit Runtime Config in Test Runner +`ConfigTestRunner` now builds LLM, Embedding, and Search configs directly from the resolved runtime catalog instead of relying on the global config cache, ensuring test runs always reflect the current active selection. + +### Frontend Resource Leak Fixes +- Added `AbortController` cleanup across all Playground testers (ToolExecutor, DeepQuestionTester, DeepResearchTester, CapabilityTester) and the SaveToNotebookModal, preventing orphaned fetch requests on unmount or re-execution. +- Introduced a `MAX_CACHED_SESSIONS = 20` eviction policy in UnifiedChatContext to prevent unbounded session memory growth. +- WebSocket runners and retry timers are now properly cleaned up on provider unmount. +- Fixed auto-scroll throttle timer leak by returning a cleanup function from the throttle effect. + +## Community Contributions + +- **@OlegSob-glitch** — SearXNG auto-fallback for search providers without templates (#286) + +**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.0.1...v1.0.2 diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.py index 2b5d8546b..164165077 100644 --- a/deeptutor/services/config/test_runner.py +++ b/deeptutor/services/config/test_runner.py @@ -13,7 +13,11 @@ from uuid import uuid4 from .env_store import get_env_store from .model_catalog import get_model_catalog_service -from .provider_runtime import resolve_search_runtime_config +from .provider_runtime import ( + resolve_embedding_runtime_config, + resolve_llm_runtime_config, + resolve_search_runtime_config, +) def _redact(value: str) -> str: @@ -115,11 +119,11 @@ class ConfigTestRunner: with temporary_env(env_values): if service == "llm": - asyncio.run(self._test_llm(run)) + asyncio.run(self._test_llm(run, catalog)) elif service == "embedding": - asyncio.run(self._test_embedding(run, model or {})) + asyncio.run(self._test_embedding(run, model or {}, catalog)) elif service == "search": - self._test_search(run) + self._test_search(run, catalog) else: raise ValueError(f"Unsupported service: {service}") if not run.cancelled and run.status == "running": @@ -129,13 +133,26 @@ class ConfigTestRunner: run.status = "failed" run.emit("failed", str(exc)) - async def _test_llm(self, run: TestRun) -> None: + async def _test_llm(self, run: TestRun, catalog: dict[str, Any]) -> None: from deeptutor.services.llm import clear_llm_config_cache, complete as llm_complete - from deeptutor.services.llm import get_llm_config, get_token_limit_kwargs + from deeptutor.services.llm import get_token_limit_kwargs + from deeptutor.services.llm.config import LLMConfig clear_llm_config_cache() run.emit("info", "Loading LLM config from the active catalog selection.") - llm_config = get_llm_config() + resolved = resolve_llm_runtime_config(catalog=catalog) + llm_config = LLMConfig( + model=resolved.model, + api_key=resolved.api_key, + base_url=resolved.base_url, + effective_url=resolved.effective_url, + binding=resolved.binding, + provider_name=resolved.provider_name, + provider_mode=resolved.provider_mode, + api_version=resolved.api_version, + extra_headers=resolved.extra_headers, + reasoning_effort=resolved.reasoning_effort, + ) run.emit("info", f"Resolved model `{llm_config.model}` with binding `{llm_config.binding}`.") run.emit("info", f"Request target: {llm_config.base_url}") token_kwargs = get_token_limit_kwargs(llm_config.model, max_tokens=200) @@ -155,14 +172,30 @@ class ConfigTestRunner: if not snippet: raise ValueError("LLM returned an empty response.") - async def _test_embedding(self, run: TestRun, model: dict[str, Any]) -> None: - from deeptutor.services.embedding import get_embedding_client, get_embedding_config + async def _test_embedding(self, run: TestRun, model: dict[str, Any], catalog: dict[str, Any]) -> None: + from deeptutor.services.embedding.client import EmbeddingClient + from deeptutor.services.embedding.config import EmbeddingConfig run.emit("info", "Loading embedding config from the active catalog selection.") - config = get_embedding_config() + resolved = resolve_embedding_runtime_config(catalog=catalog) + config = EmbeddingConfig( + model=resolved.model, + api_key=resolved.api_key, + base_url=resolved.base_url, + effective_url=resolved.effective_url, + binding=resolved.binding, + provider_name=resolved.provider_name, + provider_mode=resolved.provider_mode, + api_version=resolved.api_version, + extra_headers=resolved.extra_headers, + dim=resolved.dimension, + request_timeout=max(1, resolved.request_timeout), + batch_size=max(1, resolved.batch_size), + batch_delay=max(0.0, resolved.batch_delay), + ) run.emit("info", f"Resolved embedding model `{config.model}` with binding `{config.binding}`.") run.emit("info", f"Request target: {config.base_url}") - client = get_embedding_client() + client = EmbeddingClient(config) vectors = await client.embed(["DeepTutor embedding smoke test"]) if not vectors or not vectors[0]: raise ValueError("Embedding service returned an empty vector.") @@ -179,10 +212,10 @@ class ConfigTestRunner: f"Embedding dimension mismatch. expected={expected_dimension}, actual={actual_dimension}" ) - def _test_search(self, run: TestRun) -> None: + def _test_search(self, run: TestRun, catalog: dict[str, Any]) -> None: from deeptutor.services.search import web_search - resolved = resolve_search_runtime_config() + resolved = resolve_search_runtime_config(catalog=catalog) if not resolved.requested_provider: run.status = "completed" run.emit("completed", "Search skipped because no active provider is configured.") diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.py index 9463e3b16..69c996626 100644 --- a/deeptutor/services/search/__init__.py +++ b/deeptutor/services/search/__init__.py @@ -18,7 +18,7 @@ from deeptutor.services.config import ( ) from .base import SEARCH_API_KEY_ENV, BaseSearchProvider -from .consolidation import CONSOLIDATION_TYPES, PROVIDER_TEMPLATES, AnswerConsolidator +from .consolidation import PROVIDER_TEMPLATES, AnswerConsolidator from .providers import ( _DEPRECATED_UNSUPPORTED, get_available_providers, @@ -84,12 +84,16 @@ def web_search( output_dir: str | None = None, verbose: bool = False, provider: str | None = None, - consolidation: str | None = None, consolidation_custom_template: str | None = None, consolidation_llm_model: str | None = None, **provider_kwargs: Any, ) -> dict[str, Any]: - """Execute web search and return DeepTutor structured response shape.""" + """Execute web search and return DeepTutor structured response shape. + + Consolidation is automatic for providers that return raw SERP results + (``supports_answer=False``). Pass ``consolidation_llm_model`` to + upgrade from template formatting to LLM synthesis. + """ config = _get_web_search_config() if not config.get("enabled", True): _logger.warning("Web search is disabled in config") @@ -138,19 +142,16 @@ def web_search( _logger.error(f"[{search_provider.name}] Search failed: {exc}") raise Exception(f"{search_provider.name} search failed: {exc}") from exc - # Compatibility layer: only apply optional consolidation when requested. - if consolidation is None: - consolidation = config.get("consolidation") - if consolidation_custom_template is None: - consolidation_custom_template = config.get("consolidation_template") or None - if consolidation and not search_provider.supports_answer: - llm_config = {} - if consolidation_llm_model: - llm_config["model"] = consolidation_llm_model + # Auto-consolidate for providers that don't generate their own answers. + if not search_provider.supports_answer: + if consolidation_custom_template is None: + consolidation_custom_template = config.get("consolidation_template") or None + use_llm = bool(consolidation_llm_model) + llm_config = {"model": consolidation_llm_model} if consolidation_llm_model else None consolidator = AnswerConsolidator( - consolidation_type=consolidation, + use_llm=use_llm, custom_template=consolidation_custom_template, - llm_config=llm_config if llm_config else None, + llm_config=llm_config, ) response = consolidator.consolidate(response) @@ -184,9 +185,7 @@ def get_current_config() -> dict[str, Any]: "providers": get_providers_info(), "supported_providers": sorted(SUPPORTED_SEARCH_PROVIDERS), "deprecated_providers": sorted(DEPRECATED_SEARCH_PROVIDERS), - "consolidation": config.get("consolidation"), "consolidation_template": config.get("consolidation_template") or None, - "consolidation_types": CONSOLIDATION_TYPES, "template_providers": list(PROVIDER_TEMPLATES.keys()), } @@ -205,7 +204,6 @@ __all__ = [ "Citation", "SearchResult", "AnswerConsolidator", - "CONSOLIDATION_TYPES", "PROVIDER_TEMPLATES", "BaseSearchProvider", "SearchProvider", diff --git a/deeptutor/services/search/consolidation.py b/deeptutor/services/search/consolidation.py index e916eafef..972163d0a 100644 --- a/deeptutor/services/search/consolidation.py +++ b/deeptutor/services/search/consolidation.py @@ -1,9 +1,10 @@ """ Answer Consolidation - Generate answers from raw search results -Supports two strategies: -1. template: Fast Jinja2 template rendering -2. llm: LLM-based answer synthesis (uses project's LLM config from env vars) +Strategies (chosen automatically): +- Provider-specific Jinja2 template when available (serper, jina, serper_scholar) +- Generic fallback template for all other raw-SERP providers +- Optional LLM synthesis when ``use_llm=True`` """ from typing import Any @@ -15,14 +16,9 @@ from deeptutor.services.llm import get_llm_client from .types import WebSearchResponse -# Module logger _logger = get_logger("Search.Consolidation", level="INFO") -# Available consolidation types -CONSOLIDATION_TYPES = ["none", "template", "llm"] - - # ============================================================================= # PROVIDER-SPECIFIC TEMPLATES # ============================================================================= @@ -140,19 +136,13 @@ PROVIDER_TEMPLATES = { class AnswerConsolidator: - """ - Consolidate raw SERP results into formatted answers. + """Consolidate raw SERP results into a formatted answer. - IMPORTANT: Template consolidation only works for providers that have - specific templates defined (serper, jina, serper_scholar). - - For other providers, use: - - consolidation_type="llm" for LLM-based synthesis - - custom_template for a custom Jinja2 template + By default, uses Jinja2 templates (provider-specific when available, + generic fallback otherwise). Set ``use_llm=True`` to upgrade to + LLM-based synthesis instead. """ - # Map provider names to their specific templates - # Only these providers support template consolidation PROVIDER_TEMPLATE_MAP = { "serper": "serper", "jina": "jina", @@ -161,28 +151,17 @@ class AnswerConsolidator: def __init__( self, - consolidation_type: str = "template", + *, + use_llm: bool = False, custom_template: str | None = None, llm_config: dict[str, Any] | None = None, max_results: int = 5, autoescape: bool = True, ): - """ - Initialize consolidator. - - Args: - consolidation_type: "none", "template", or "llm" - custom_template: Custom Jinja2 template string - llm_config: Optional overrides (system_prompt, max_tokens, temperature) - max_results: Maximum results to include in answer - autoescape: Whether to enable Jinja2 autoescape for security (default: True) - """ - self.consolidation_type = consolidation_type + self.use_llm = use_llm self.custom_template = custom_template self.llm_config = llm_config or {} self.max_results = max_results - # Security: autoescape defaults to True (set in function signature above). - # When True, Jinja2 auto-escapes HTML to prevent XSS. self.jinja_env = Environment(loader=BaseLoader(), autoescape=autoescape) # nosec B701 if self.custom_template is not None and autoescape: @@ -193,71 +172,33 @@ class AnswerConsolidator: ) def consolidate(self, response: WebSearchResponse) -> WebSearchResponse: - """ - Consolidate search results into an answer. - - Args: - response: WebSearchResponse with search_results populated - - Returns: - WebSearchResponse with answer field populated - """ - if self.consolidation_type == "none": - _logger.debug("Consolidation disabled, returning raw response") - return response - + """Consolidate search results into an answer.""" results_count = len(response.search_results) - _logger.info( - f"Consolidating {results_count} results from {response.provider} using {self.consolidation_type}" - ) - if self.consolidation_type == "template": - response.answer = self._consolidate_with_template(response) - _logger.success(f"Template consolidation completed ({len(response.answer)} chars)") - elif self.consolidation_type == "llm": + if self.use_llm: + _logger.info(f"Consolidating {results_count} results from {response.provider} via LLM") response.answer = self._consolidate_with_llm(response) _logger.success(f"LLM consolidation completed ({len(response.answer)} chars)") else: - _logger.error(f"Unknown consolidation type: {self.consolidation_type}") - raise ValueError(f"Unknown consolidation type: {self.consolidation_type}") + _logger.info(f"Consolidating {results_count} results from {response.provider} via template") + response.answer = self._consolidate_with_template(response) + _logger.success(f"Template consolidation completed ({len(response.answer)} chars)") return response - def _get_template_for_provider(self, provider: str) -> str: - """ - Get the template for a specific provider. - - Only provider-specific templates exist because each provider has - different response schemas and metadata. No universal templates. - - Args: - provider: Provider name (e.g., "serper", "jina") - - Returns: - Template string for this provider - - Raises: - ValueError: If no template exists for this provider - """ - # 1. Custom template takes highest priority + def _get_template_for_provider(self, provider: str) -> str | None: + """Return the best Jinja2 template for *provider*, or ``None``.""" if self.custom_template: _logger.debug(f"Using custom template ({len(self.custom_template)} chars)") return self.custom_template - # 2. Get provider-specific template template_key = self.PROVIDER_TEMPLATE_MAP.get(provider.lower()) if template_key and template_key in PROVIDER_TEMPLATES: _logger.debug(f"Using provider-specific template: {template_key}") return PROVIDER_TEMPLATES[template_key] - # 3. No template exists for this provider - fail explicitly - available = list(PROVIDER_TEMPLATES.keys()) - _logger.error(f"No template for provider '{provider}'. Available: {available}") - raise ValueError( - f"No template consolidation available for provider '{provider}'. " - f"Template consolidation only works with: {available}. " - f"Use consolidation='llm' or provide a custom_template for other providers." - ) + _logger.debug(f"No specific template for '{provider}', using generic fallback") + return None def _build_provider_context(self, response: WebSearchResponse) -> dict[str, Any]: """ @@ -320,11 +261,17 @@ class AnswerConsolidator: return context def _consolidate_with_template(self, response: WebSearchResponse) -> str: - """Render results using Jinja2 template""" + """Render results using Jinja2 template or fallback to simple formatting""" _logger.debug(f"Building template context for {response.provider}") # Get template (auto-detect provider-specific if not explicitly set) template_str = self._get_template_for_provider(response.provider) + + # Fallback: if no template available, use simple result formatting + if template_str is None: + _logger.info(f"Using fallback simple formatting for {response.provider}") + return self._format_simple_results(response) + template = self.jinja_env.from_string(template_str) # Build context with provider-specific fields @@ -394,5 +341,31 @@ Consolidate these results into structured grounding context.""" return system_prompt, user_prompt + def _format_simple_results(self, response: WebSearchResponse) -> str: + """ + Format search results using a simple, provider-agnostic format. -__all__ = ["AnswerConsolidator", "CONSOLIDATION_TYPES", "PROVIDER_TEMPLATES"] + This is used as a fallback when no provider-specific template is available. + """ + lines = [f"### Search Results for \"{response.query}\"", ""] + + for i, result in enumerate(response.search_results[: self.max_results], 1): + lines.append(f"**[{i}] {result.title}**") + if result.snippet: + lines.append(f"{result.snippet}") + if result.source: + lines.append(f"*Source: {result.source}*") + lines.append(f"🔗 [{result.url}]({result.url})") + lines.append("") + + if response.search_results: + lines.append( + f"---\n*{len(response.search_results)} results via {response.provider}*" + ) + else: + lines.append("*No results found.*") + + return "\n".join(lines) + + +__all__ = ["AnswerConsolidator", "PROVIDER_TEMPLATES"] diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.py index 12c3cdc95..7feecc8ce 100644 --- a/deeptutor/services/setup/init.py +++ b/deeptutor/services/setup/init.py @@ -50,8 +50,6 @@ DEFAULT_MAIN_SETTINGS = { }, "web_search": { "enabled": True, - "consolidation": "template", - "consolidation_template": "", }, }, "capabilities": { diff --git a/deeptutor/tools/web_search.py b/deeptutor/tools/web_search.py index 5a14c9bed..5f247f214 100644 --- a/deeptutor/tools/web_search.py +++ b/deeptutor/tools/web_search.py @@ -28,7 +28,6 @@ Available Providers: # Re-export from services layer from deeptutor.services.search import ( - CONSOLIDATION_TYPES, PROVIDER_TEMPLATES, SEARCH_API_KEY_ENV, AnswerConsolidator, @@ -62,7 +61,6 @@ __all__ = [ "SearchResult", # Consolidation "AnswerConsolidator", - "CONSOLIDATION_TYPES", "PROVIDER_TEMPLATES", # Base class "BaseSearchProvider", diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx index d83dca4dc..dfbd0efcf 100644 --- a/web/app/(utility)/settings/page.tsx +++ b/web/app/(utility)/settings/page.tsx @@ -1030,7 +1030,7 @@ function SettingsPageContent() { const field = activeService === "search" ? "provider" : "binding"; updateProfileField(field, val); const match = (providers[activeService] || []).find((p) => p.value === val); - if (match?.base_url && !activeProfile.base_url) { + if (match?.base_url) { updateProfileField("base_url", match.base_url); } }} diff --git a/web/app/(workspace)/playground/page.tsx b/web/app/(workspace)/playground/page.tsx index c20adc2ad..1e9aabf74 100644 --- a/web/app/(workspace)/playground/page.tsx +++ b/web/app/(workspace)/playground/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { BrainCircuit, ChevronDown, @@ -292,6 +292,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases const [result, setResult] = useState(null); const [error, setError] = useState(null); const [processLogs, setProcessLogs] = useState([]); + const abortRef = useRef(null); useEffect(() => { setValues({}); @@ -300,12 +301,17 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases setProcessLogs([]); }, [tool.name]); + useEffect(() => () => { abortRef.current?.abort(); }, []); + const setParam = (name: string, val: string) => setValues((p) => ({ ...p, [name]: val })); const queryParam = params.find((p) => QUERY_PARAM_NAMES.has(p.name)); const otherParams = params.filter((p) => !QUERY_PARAM_NAMES.has(p.name)); const execute = async () => { + abortRef.current?.abort(); + const controller = new AbortController(); + abortRef.current = controller; setExecuting(true); setResult(null); setError(null); @@ -325,6 +331,7 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ params: coerced }), + signal: controller.signal, }); if (!res.ok) { @@ -372,9 +379,10 @@ function ToolExecutor({ tool, knowledgeBases }: { tool: ToolInfo; knowledgeBases } } } catch (err: unknown) { + if (controller.signal.aborted) return; setError(err instanceof Error ? err.message : String(err)); } finally { - setExecuting(false); + if (!controller.signal.aborted) setExecuting(false); } }; @@ -615,6 +623,9 @@ function DeepQuestionTester({ const [messages, setMessages] = useState([]); const [streaming, setStreaming] = useState(false); const [uploadedPdf, setUploadedPdf] = useState(null); + const abortRef = useRef(null); + + useEffect(() => () => { abortRef.current?.abort(); }, []); const updateLastAssistant = (updater: (msg: TesterMessage) => TesterMessage) => { setMessages((prev) => { @@ -651,6 +662,10 @@ function DeepQuestionTester({ const run = async () => { if (!canRun || streaming) return; + abortRef.current?.abort(); + const controller = new AbortController(); + abortRef.current = controller; + const userContent = config.mode === "custom" ? config.topic.trim() @@ -698,6 +713,7 @@ function DeepQuestionTester({ config: requestConfig, attachments, }), + signal: controller.signal, }, ); @@ -775,12 +791,13 @@ function DeepQuestionTester({ } } } catch (err: unknown) { + if (controller.signal.aborted) return; updateLastAssistant((last) => ({ ...last, error: err instanceof Error ? err.message : String(err), })); } finally { - setStreaming(false); + if (!controller.signal.aborted) setStreaming(false); } }; @@ -1003,6 +1020,9 @@ function DeepResearchTester({ const [messages, setMessages] = useState([]); const [streaming, setStreaming] = useState(false); const validation = useMemo(() => validateResearchConfig(config), [config]); + const abortRef = useRef(null); + + useEffect(() => () => { abortRef.current?.abort(); }, []); const updateLastAssistant = (updater: (msg: TesterMessage) => TesterMessage) => { setMessages((prev) => { @@ -1017,6 +1037,11 @@ function DeepResearchTester({ const run = async () => { const content = input.trim(); if (!content || streaming || !validation.valid) return; + + abortRef.current?.abort(); + const controller = new AbortController(); + abortRef.current = controller; + setMessages((prev) => [ ...prev, { role: "user", content }, @@ -1037,6 +1062,7 @@ function DeepResearchTester({ language: i18n.language, config: buildResearchWSConfig(config), }), + signal: controller.signal, }, ); @@ -1114,12 +1140,13 @@ function DeepResearchTester({ } } } catch (err: unknown) { + if (controller.signal.aborted) return; updateLastAssistant((last) => ({ ...last, error: err instanceof Error ? err.message : String(err), })); } finally { - setStreaming(false); + if (!controller.signal.aborted) setStreaming(false); } }; @@ -1241,6 +1268,9 @@ function CapabilityTester({ const [input, setInput] = useState(""); const [messages, setMessages] = useState([]); const [streaming, setStreaming] = useState(false); + const abortRef = useRef(null); + + useEffect(() => () => { abortRef.current?.abort(); }, []); const updateLastAssistant = (updater: (msg: TesterMessage) => TesterMessage) => { setMessages((prev) => { @@ -1255,6 +1285,11 @@ function CapabilityTester({ const send = async () => { const content = input.trim(); if (!content || streaming) return; + + abortRef.current?.abort(); + const controller = new AbortController(); + abortRef.current = controller; + setMessages((prev) => [ ...prev, { role: "user", content }, @@ -1275,6 +1310,7 @@ function CapabilityTester({ knowledge_bases: enabledTools.includes("rag") && knowledgeBase ? [knowledgeBase] : [], language: i18n.language, }), + signal: controller.signal, }, ); @@ -1352,12 +1388,13 @@ function CapabilityTester({ } } } catch (err: unknown) { + if (controller.signal.aborted) return; updateLastAssistant((last) => ({ ...last, error: err instanceof Error ? err.message : String(err), })); } finally { - setStreaming(false); + if (!controller.signal.aborted) setStreaming(false); } }; diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsx index 924ce616b..7755d494a 100644 --- a/web/components/notebook/SaveToNotebookModal.tsx +++ b/web/components/notebook/SaveToNotebookModal.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { Loader2, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { apiUrl } from "@/lib/api"; @@ -70,9 +70,13 @@ export default function SaveToNotebookModal({ const [summaryPreview, setSummaryPreview] = useState(""); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(""); + const abortRef = useRef(null); useEffect(() => { - if (!open) return; + if (!open) { + abortRef.current?.abort(); + return; + } setTitle(payload?.title || ""); setSummaryPreview(""); setError(""); @@ -105,6 +109,9 @@ export default function SaveToNotebookModal({ const handleSave = async () => { if (!payload || !canSave) return; + abortRef.current?.abort(); + const controller = new AbortController(); + abortRef.current = controller; setIsLoading(true); setError(""); setSummaryPreview(""); @@ -122,6 +129,7 @@ export default function SaveToNotebookModal({ metadata: payload.metadata || {}, kb_name: payload.kbName || null, }), + signal: controller.signal, }); if (!response.ok || !response.body) { @@ -165,6 +173,7 @@ export default function SaveToNotebookModal({ throw new Error("Notebook save stream ended unexpectedly."); } catch (err) { + if (controller.signal.aborted) return; setError(err instanceof Error ? err.message : "Failed to save to notebook."); setIsLoading(false); } diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx index 06d1ef3db..c2d2bd0fa 100644 --- a/web/context/UnifiedChatContext.tsx +++ b/web/context/UnifiedChatContext.tsx @@ -351,15 +351,19 @@ function reducer(state: ProviderState, action: Action): ProviderState { }, }; } - case "NEW_SESSION": - return { - ...state, - selectedKey: action.key, - sessions: { - ...state.sessions, - [action.key]: createSessionEntry(action.key), - }, - }; + case "NEW_SESSION": { + const MAX_CACHED_SESSIONS = 20; + let nextSessions = { ...state.sessions, [action.key]: createSessionEntry(action.key) }; + const keys = Object.keys(nextSessions); + if (keys.length > MAX_CACHED_SESSIONS) { + const evictable = keys + .filter((k) => k !== action.key && nextSessions[k].status !== "running") + .sort((a, b) => nextSessions[a].updatedAt - nextSessions[b].updatedAt); + const toRemove = evictable.slice(0, keys.length - MAX_CACHED_SESSIONS); + for (const k of toRemove) delete nextSessions[k]; + } + return { ...state, selectedKey: action.key, sessions: nextSessions }; + } default: return state; } @@ -409,11 +413,22 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode }) > >(new Map()); const draftCounterRef = useRef(0); + const retryTimersRef = useRef>>(new Set()); useEffect(() => { stateRef.current = state; }, [state]); + useEffect( + () => () => { + runnersRef.current.forEach(({ client }) => client.disconnect()); + runnersRef.current.clear(); + retryTimersRef.current.forEach((id) => clearTimeout(id)); + retryTimersRef.current.clear(); + }, + [], + ); + const makeDraftKey = useCallback(() => { draftCounterRef.current += 1; return `draft_${Date.now()}_${draftCounterRef.current}`; @@ -536,7 +551,11 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode }) dispatch({ type: "STREAM_END", key, status: "failed" }); return; } - window.setTimeout(() => dispatchToRunner(key, msg, attempt + 1), 200); + const timerId = window.setTimeout(() => { + retryTimersRef.current.delete(timerId); + dispatchToRunner(key, msg, attempt + 1); + }, 200); + retryTimersRef.current.add(timerId); return; } runner.client.send(msg); diff --git a/web/hooks/useChatAutoScroll.ts b/web/hooks/useChatAutoScroll.ts index e2193e9e5..63e548453 100644 --- a/web/hooks/useChatAutoScroll.ts +++ b/web/hooks/useChatAutoScroll.ts @@ -51,7 +51,12 @@ export function useChatAutoScroll({ lastScrollTimeRef.current = performance.now(); } }, THROTTLE_MS - elapsed); - return; + return () => { + if (pendingRafRef.current) { + clearTimeout(pendingRafRef.current); + pendingRafRef.current = 0; + } + }; } const raf = window.requestAnimationFrame(() => {