Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat(chat): step timeline with expandable detail for classic strategies (#5188)

LearningCircuitb41711e1c629
diff --git a/changelog.d/5188.feature.md b/changelog.d/5188.feature.md
new file mode 100644
index 0000000000..c4d42e77be
--- /dev/null
+++ b/changelog.d/5188.feature.md
@@ -0,0 +1 @@
+Chat research now shows a step timeline with click-to-expand detail for the classic strategies, which previously produced almost no steps (only the LangGraph agent strategy had expandable steps). Source-based and focused-iteration show planning → searching → results → synthesis; topic-organization shows its source-gathering steps (planning, searching, results). Question lists are shown in full instead of "… and N more". The LangGraph strategy's existing synthesis milestone now also appears as a step.
diff --git a/docs/enhancements/metrics/enhanced-token-tracking.md b/docs/enhancements/metrics/enhanced-token-tracking.md
index f2146f9cc7..8ce0157b82 100644
--- a/docs/enhancements/metrics/enhanced-token-tracking.md
+++ b/docs/enhancements/metrics/enhanced-token-tracking.md
@@ -29,7 +29,7 @@ The existing system tracks basic token usage:
- **research_mode** - `"quick"` or `"detailed"` research mode
- **research_phase** - Current stage of research:
- `init`, `setup`, `iteration_1`, `iteration_2`, etc.
- - `question_generation`, `parallel_search`, `search_complete`
+ - `search_planning`, `search`, `search_complete`
- `output_generation`, `report_generation`, `complete`, `error`
#### Performance Metrics
diff --git a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
index ad606a8fee..b6fd930e5d 100644
--- a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py
@@ -32,6 +32,45 @@ CHECK_CONTEXT_FALLBACK_SYNTHESIS = "fallback_synthesis"
NO_USABLE_SYNTHESIS_MESSAGE = "Final synthesis produced no usable text."
+# Bounds for progress events that carry an expandable detail in
+# ``metadata["content"]`` (chat renders it beneath the one-line message in
+# the click-to-expand step row; the chat route persists it per step, so it
+# must stay bounded). Shared by every strategy that emits step detail —
+# the LangGraph agent strategy imports these for its observation events.
+_OBSERVATION_PREVIEW_MAX_CHARS = 150
+_OBSERVATION_DETAIL_MAX_CHARS = 4000
+
+
+def _cap_detail(text: str) -> str:
+ """Bound an expandable-detail string, marking the cut with an ellipsis."""
+ if len(text) > _OBSERVATION_DETAIL_MAX_CHARS:
+ return text[:_OBSERVATION_DETAIL_MAX_CHARS] + " …"
+ return text
+
+
+def _flatten(text: str) -> str:
+ r"""Collapse every whitespace run in *text* to a single space.
+
+ Handles ``\n``, ``\r\n``, bare ``\r`` and tabs alike — text reaching
+ these emitters is externally sourced (scraped page titles, PDF
+ metadata, LLM-generated questions, pasted user queries) and any of
+ them would otherwise break a single-line contract.
+ """
+ return " ".join(str(text).split())
+
+
+def _bullet(item: str) -> str:
+ """Render one detail-list entry as exactly one ``•`` line.
+
+ The step message states a count ("Found 3 results", "Searching with
+ 5 questions") and the expandable detail lists that many bullets. An
+ embedded newline in a single entry would split it across two visual
+ lines — the second with no bullet marker, reading as a separate,
+ malformed entry — so the list no longer matches the stated count.
+ """
+ return f"• {_flatten(item)}"
+
+
class BaseSearchStrategy(ABC):
"""Abstract base class for all search strategies."""
@@ -254,6 +293,14 @@ class BaseSearchStrategy(ABC):
"""
Emit progress update for question generation phase.
+ Uses the ``search_planning`` step phase so the event becomes a
+ persisted, click-to-expand row in chat mode. The message stays one
+ line. For iterations after the first, the previous iteration's
+ questions (no "... and N more" sampling) ride in
+ ``metadata["content"]`` as the expandable detail, capped at
+ ``_OBSERVATION_DETAIL_MAX_CHARS`` with an ellipsis marker; the
+ first iteration has no detail.
+
Args:
iteration: Current iteration number
progress_percent: Current progress percentage
@@ -261,30 +308,42 @@ class BaseSearchStrategy(ABC):
query: The original research query (for iteration 1)
"""
if iteration == 1:
+ # Flatten whitespace (chat's textarea allows Shift+Enter) so
+ # the step row stays a genuine one-liner, then cap with a
+ # visible truncation marker.
+ flat_query = _flatten(query)
+ shown_query = (
+ flat_query
+ if len(flat_query) <= _OBSERVATION_PREVIEW_MAX_CHARS
+ else flat_query[:_OBSERVATION_PREVIEW_MAX_CHARS] + "…"
+ )
self._update_progress(
- f"Generating initial search questions:\n• {query}",
+ f'Planning initial search questions for: "{shown_query}"',
progress_percent,
{
- "phase": "question_generation",
+ "phase": "search_planning",
"type": "milestone",
"iteration": iteration,
},
)
else:
- # Show previous questions and source count
prev_questions = self.questions_by_iteration.get(iteration - 1, [])
- prev_display = "\n".join(f"• {q}" for q in prev_questions[:3])
- if len(prev_questions) > 3:
- prev_display += f"\n... and {len(prev_questions) - 3} more"
+ metadata = {
+ "phase": "search_planning",
+ "type": "milestone",
+ "iteration": iteration,
+ "source_count": source_count,
+ }
+ if prev_questions:
+ metadata["content"] = _cap_detail(
+ "Previous questions:\n"
+ + "\n".join(_bullet(q) for q in prev_questions)
+ )
self._update_progress(
- f"Generating questions from {source_count} sources:\n{prev_display}",
+ f"Generating search questions from {source_count} sources "
+ f"(iteration {iteration})",
progress_percent,
- {
- "phase": "question_generation",
- "type": "milestone",
- "iteration": iteration,
- "source_count": source_count,
- },
+ metadata,
)
def _create_error_response(self, error: str) -> dict[str, Any]:
@@ -352,21 +411,75 @@ class BaseSearchStrategy(ABC):
"""
Emit progress update for searching phase with questions as milestone.
+ Uses the ``search`` step phase so the event becomes a persisted,
+ click-to-expand row in chat mode. The message stays one line; the
+ question list (no "... and N more" sampling) rides in
+ ``metadata["content"]`` as the expandable detail, capped at
+ ``_OBSERVATION_DETAIL_MAX_CHARS`` with an ellipsis marker (no
+ detail when there are no questions).
+
Args:
iteration: Current iteration number
questions: List of questions being searched
progress_percent: Current progress percentage
"""
- questions_display = "\n".join(f"• {q}" for q in questions[:5])
- if len(questions) > 5:
- questions_display += f"\n... and {len(questions) - 5} more"
+ metadata = {
+ "phase": "search",
+ "type": "milestone",
+ "iteration": iteration,
+ "questions": questions,
+ }
+ if questions:
+ metadata["content"] = _cap_detail(
+ "\n".join(_bullet(q) for q in questions)
+ )
self._update_progress(
- f"Searching iteration {iteration}:\n{questions_display}",
+ f"Searching with {len(questions)} question"
+ f"{'s' if len(questions) != 1 else ''} (iteration {iteration})",
progress_percent,
- {
- "phase": "parallel_search",
- "type": "milestone",
- "iteration": iteration,
- "questions": questions,
- },
+ metadata,
+ )
+
+ def _emit_search_results_observation(
+ self,
+ iteration: int,
+ questions: list[str],
+ results: list[dict[str, Any]],
+ progress_percent: int,
+ ) -> None:
+ """
+ Emit an ``observation`` step summarizing what an iteration's
+ searches returned.
+
+ Mirrors the LangGraph strategy's per-tool-result observations: a
+ one-line message plus the found sources (title + URL bullets) in
+ ``metadata["content"]``, so the chat step row expands to show what
+ was actually found. No citation numbers — indices are assigned
+ later, after filtering/reindexing.
+
+ Args:
+ iteration: Current iteration number
+ questions: The questions that were searched
+ results: Raw search-result dicts from this iteration
+ progress_percent: Current progress percentage
+ """
+ metadata: dict[str, Any] = {
+ "phase": "observation",
+ "iteration": iteration,
+ }
+ lines = []
+ for r in results:
+ if not isinstance(r, dict):
+ continue
+ title = r.get("title") or "Untitled"
+ link = r.get("link", r.get("url", ""))
+ lines.append(_bullet(f"{title} ({link})" if link else title))
+ if lines:
+ metadata["content"] = _cap_detail("\n".join(lines))
+ self._update_progress(
+ f"📄 Found {len(results)} result{'s' if len(results) != 1 else ''} "
+ f"from {len(questions)} search"
+ f"{'es' if len(questions) != 1 else ''} (iteration {iteration})",
+ progress_percent,
+ metadata,
)
diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
index caa0f2beca..afcca02f46 100644
--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
@@ -179,9 +179,10 @@ class FocusedIterationStrategy(BaseSearchStrategy):
iteration_progress = 10 + (iteration - 1) * iteration_band
# Show context-aware progress message for question generation.
- # Stay inside this iteration's band so a large
- # max_iterations cannot push the last iteration past
- # synthesis (90).
+ # Every step event of this iteration (planning, searching,
+ # results) stays inside this iteration's band, in that
+ # order, so a large max_iterations cannot push the last
+ # iteration past synthesis (90) or make the bar step back.
self._emit_question_generation_progress(
iteration=iteration,
progress_percent=iteration_progress
@@ -254,6 +255,13 @@ class FocusedIterationStrategy(BaseSearchStrategy):
)
continue
+ self._emit_searching_progress(
+ iteration=iteration,
+ questions=questions,
+ progress_percent=iteration_progress
+ + min(4, iteration_band / 2),
+ )
+
# Execute searches
if self.explorer and self.use_browsecomp_optimization:
# Use progressive explorer for better tracking
@@ -302,6 +310,15 @@ class FocusedIterationStrategy(BaseSearchStrategy):
# Track result count for this iteration
self.results_by_iteration[iteration] = len(iteration_results)
+ self._emit_search_results_observation(
+ iteration=iteration,
+ questions=questions,
+ results=iteration_results,
+ progress_percent=iteration_progress
+ + iteration_band
+ - min(2, iteration_band / 4),
+ )
+
# Add iteration finding
finding = {
"phase": f"Iteration {iteration}",
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index 1aa16060f7..88ff383d3a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -79,6 +79,8 @@ from ..tools.fetch import (
make_library_resolver,
)
from .base_strategy import (
+ _OBSERVATION_DETAIL_MAX_CHARS,
+ _OBSERVATION_PREVIEW_MAX_CHARS,
BaseSearchStrategy,
CHECK_CONTEXT_AGENT_STREAM,
CHECK_CONTEXT_ENTRY,
@@ -1482,8 +1484,7 @@ _HEARTBEAT_TOOL_LABELS = {
# search or page fetch actually returned when the user expands the step.
# Detail is only attached when the output exceeds the preview, so short
# results ("No results.") aren't shown twice in the expanded step.
-_OBSERVATION_PREVIEW_MAX_CHARS = 150
-_OBSERVATION_DETAIL_MAX_CHARS = 4000
+# Shared with the classic strategies' step emitters — see base_strategy.
def _truncate_arg(value: str, limit: int = 80) -> str:
diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
index 4ea697166d..e1eeb5db4f 100644
--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
@@ -255,15 +255,22 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
# Run each iteration
for iteration in range(1, iterations_to_run + 1):
self.check_termination(CHECK_CONTEXT_ITERATION_START)
- iteration_progress_base = 5 + (iteration - 1) * (
- 70 / iterations_to_run
- )
+ # Every step event of this iteration (planning, searching,
+ # results) stays inside this iteration's band, in that
+ # order. The band narrows as search.iterations grows (it has
+ # no maximum), and fixed offsets would then make the stream
+ # step back or run into the post-loop filtering milestone
+ # (80). Bands of 17.5 or more (up to 4 iterations) keep the
+ # offsets 5 / 10 / band - 5.
+ iteration_band = 70 / iterations_to_run
+ iteration_progress_base = 5 + (iteration - 1) * iteration_band
# Step 1: Generate or use questions
# Show context-aware progress message (includes iteration info)
self._emit_question_generation_progress(
iteration=iteration,
- progress_percent=iteration_progress_base + 5,
+ progress_percent=iteration_progress_base
+ + min(5, iteration_band / 2),
source_count=len(
accumulated_search_results_across_all_iterations
)
@@ -401,6 +408,13 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
"error": "Search failed",
}
+ self._emit_searching_progress(
+ iteration=iteration,
+ questions=all_questions,
+ progress_percent=iteration_progress_base
+ + min(10, iteration_band * 0.6),
+ )
+
# Run searches in parallel. Research-context propagation is
# handled by the preserve_research_context decorator above;
# no app context is pushed into the workers (FastAPI has no
@@ -433,6 +447,15 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
filtered_search_results
)
+ self._emit_search_results_observation(
+ iteration=iteration,
+ questions=all_questions,
+ results=filtered_search_results,
+ progress_percent=iteration_progress_base
+ + iteration_band
+ - min(5, iteration_band / 3),
+ )
+
# Lightweight metadata finding (no actual content — synthesis happens later)
finding = {
"phase": f"Iteration {iteration}",
diff --git a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
index d018f38d2a..92ad6933f2 100644
--- a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
@@ -152,6 +152,39 @@ class TopicOrganizationStrategy(BaseSearchStrategy):
# Topic graph to store organized topics
self.topic_graph = TopicGraph()
+ def _make_delegate_progress_callback(self):
+ """Build the callback forwarded to source-gathering delegates.
+
+ The delegate's step events (``search_planning`` → ``search`` →
+ ``observation``) must flow — they are what give chat mode its
+ expandable timeline during the gathering phase. Its progress
+ PERCENTAGES must not: the delegate reports its own 5-90% scale,
+ which would yank this strategy's bar to ~90 mid-run and pin it
+ there (the global monotonic guard never lets it fall back).
+ Forwarding None leaves the bar to this strategy's own milestones.
+
+ Termination checks also flow through this callback so cancellation
+ remains responsive while the delegate is gathering sources. The
+ delegate uses a no-text citation handler, so its synthesis event is
+ false and must not reach the outer strategy's event stream.
+ """
+ callback = self.progress_callback
+ if callback is None:
+ return None
+
+ def _delegate_callback(message, _progress_percent, metadata):
+ phase = metadata.get("phase") if metadata else None
+ if phase not in {
+ "search_planning",
+ "search",
+ "observation",
+ "termination_check",
+ }:
+ return
+ callback(message, None, metadata)
+
+ return _delegate_callback
+
def _invoke_model(self, prompt: str) -> str:
"""Invoke the model and return normalized text.
@@ -207,43 +240,20 @@ class TopicOrganizationStrategy(BaseSearchStrategy):
return get_llm_response_text(await self.model.ainvoke(prompt))
def set_progress_callback(self, callback) -> None:
- """Set progress callback for both this strategy and its delegate.
-
- Without this propagation the delegate's ``check_termination()``
- calls are silent no-ops (``BaseSearchStrategy.check_termination``
- returns immediately when ``progress_callback`` is None), so a
- Stop click during the multi-minute source-gathering phase would
- not be detected until the delegate finished (#4871).
-
- Only termination-check callbacks are forwarded to the delegate;
- ordinary progress events (phase transitions, percentages) emitted
- by the delegate are suppressed so they don't leak into the outer
- strategy's event stream (#5114).
+ """Set the callback for this strategy AND its source delegate.
+
+ Without the propagation, every step event the delegate emits is
+ silently swallowed (``_update_progress`` no-ops on a None
+ callback) and a topic-organization research shows no gathering
+ timeline at all. Propagation also keeps the delegate's termination
+ checks live so cancellation is detected during source gathering.
"""
super().set_progress_callback(callback)
if hasattr(self, "source_strategy"):
self.source_strategy.set_progress_callback(
- self._make_termination_only_callback(callback)
- if callback
- else None
+ self._make_delegate_progress_callback()
)
- @staticmethod
- def _make_termination_only_callback(callback):
- """Wrap *callback* so only termination-check calls propagate.
-
- ``BaseSearchStrategy.check_termination`` invokes the callback
- with ``metadata['phase'] == 'termination_check'``; all other
- calls (ordinary ``_update_progress`` emissions) are silently
- dropped so delegate progress events don't reach the outer stream.
- """
-
- def _filtered(message, progress_percent, metadata):
- if metadata and metadata.get("phase") == "termination_check":
- callback(message, progress_percent, metadata)
-
- return _filtered
-
def _extract_topics_from_sources(
self,
sources: List[Dict[str, Any]],
@@ -1019,10 +1029,12 @@ Otherwise, respond with only the follow-up question, nothing else.
if self.use_focused_iteration
else "source-based"
)
+ # "search" (not a custom phase) so this becomes a persisted step
+ # row in chat mode — see _STEP_PHASES in research_service.
self._update_progress(
f"Gathering sources using {strategy_name} strategy",
10,
- {"phase": "source_gathering"},
+ {"phase": "search"},
)
# Use source-based strategy to gather sources
@@ -1262,15 +1274,9 @@ Otherwise, respond with only the follow-up question, nothing else.
settings_snapshot=self.settings_snapshot,
search_original_query=self.search_original_query,
)
-
- # Keep the refinement delegate's termination checks live —
- # without the callback they are silent no-ops (see
- # set_progress_callback). Only termination checks are
- # forwarded so delegate progress events don't leak (#5114).
- if self.progress_callback is not None:
- refinement_source_strategy.set_progress_callback(
- self._make_termination_only_callback(self.progress_callback)
- )
+ refinement_source_strategy.set_progress_callback(
+ self._make_delegate_progress_callback()
+ )
# Wrap in preserve_research_context to maintain context
@preserve_research_context
@@ -1386,10 +1392,12 @@ Otherwise, respond with only the follow-up question, nothing else.
# Generate text AFTER re-indexing sources
if self.generate_text and self.citation_handler:
+ # "output_generation" (not a custom phase) so this becomes a
+ # persisted step row in chat mode.
self._update_progress(
"Generating text synthesis from topics",
96,
- {"phase": "text_generation"},
+ {"phase": "output_generation"},
)
generated_text = self._generate_topic_based_text(
relevant_topics, query
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 95365c6aa6..9a1efb3ff2 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -234,6 +234,7 @@ _REPORT_PHASES = frozenset(
# Phases that produce user-visible step messages in chat mode.
# "complete" is excluded — it fires AFTER the response message is written,
# which would create a step with a higher sequence_number than the response.
+# Keep in sync with STEP_ICONS in chat.js.
_STEP_PHASES = frozenset(
{
"init",
@@ -241,6 +242,7 @@ _STEP_PHASES = frozenset(
"search_planning",
"search",
"observation",
+ "synthesis",
"output_generation",
"synthesis_error",
"synthesis_fallback",
@@ -250,6 +252,23 @@ _STEP_PHASES = frozenset(
}
)
+# Step phases whose ``metadata["content"]`` is an expandable detail meant
+# for the step row (search-pipeline events: planned questions, searched
+# questions, found sources / tool output). Other phases reuse
+# ``metadata["content"]`` for large payloads (e.g. full synthesized
+# answers) that must NOT be duplicated into step rows.
+# Keep in sync with STEP_DETAIL_PHASES in chat.js.
+_STEP_DETAIL_PHASES = frozenset({"search_planning", "search", "observation"})
+
+# Step phases that represent distinct per-event occurrences — a new tool
+# result, a new iteration's planning — exempt from the repeat-phase dedup
+# below. Without the exemption, an iteration that yields zero questions
+# (planning fires, search/observation are skipped) makes the NEXT
+# iteration's planning a same-phase repeat that would be silently
+# swallowed, so the timeline appears to skip an iteration.
+# Keep in sync with REPEATABLE_STEP_PHASES in chat.js.
+_REPEATABLE_STEP_PHASES = frozenset({"observation", "search_planning"})
+
# Socket.IO emission throttling: minimum interval between progress emissions per research
_EMIT_THROTTLE_SECONDS = 0.2 # 200ms
_EMIT_TTL_SECONDS = 3600 # 1 hour — evict stale entries from orphaned research
@@ -299,7 +318,7 @@ def _chat_step_decision(
# and let the emit through unchanged — completion / control
# events still need to reach the client.
return False, False
- dedup_ok = phase != last_step_phase or phase == "observation"
+ dedup_ok = phase != last_step_phase or phase in _REPEATABLE_STEP_PHASES
if dedup_ok:
return True, False
return False, not is_final
@@ -310,19 +329,20 @@ def _compose_chat_step_content(
) -> str:
"""Build the content persisted for a chat progress step.
- Observation events carry the (bounded) full tool output in
- ``metadata["content"]`` alongside the one-line ``message``. Persist it
- beneath the message so the chat step row can expand to show what the
- tool actually returned — and so a session reload reconstructs exactly
- what the live accordion showed (the same composition happens client-side
- in chat.js handleProgressUpdate; keep the two in sync).
+ Search-pipeline events (``_STEP_DETAIL_PHASES``) carry a bounded
+ expandable detail in ``metadata["content"]`` alongside the one-line
+ ``message`` — the tool output for observations, the question lists for
+ planning/search steps. Persist it beneath the message so the chat step
+ row can expand to show it — and so a session reload reconstructs
+ exactly what the live accordion showed (the same composition happens
+ client-side in chat.js handleProgressUpdate; keep the two in sync).
- Only observation events compose: other phases reuse ``metadata["content"]``
- for large payloads (e.g. full synthesized answers) that must not be
+ Other phases never compose: they reuse ``metadata["content"]`` for
+ large payloads (e.g. full synthesized answers) that must not be
duplicated into step rows.
"""
detail = metadata.get("content")
- if phase == "observation" and detail:
+ if phase in _STEP_DETAIL_PHASES and detail:
return f"{message}\n\n{detail}"
return message
diff --git a/src/local_deep_research/web/static/js/components/chat.js b/src/local_deep_research/web/static/js/components/chat.js
index 178d496fb7..7fe661a3cb 100644
--- a/src/local_deep_research/web/static/js/components/chat.js
+++ b/src/local_deep_research/web/static/js/components/chat.js
@@ -54,10 +54,12 @@
let sessionInteractionGeneration = 0;
// Research step config
+ // Keep in sync with _STEP_PHASES in research_service.py.
const STEP_ICONS = {
init: 'fa-play', setup: 'fa-gear',
search: 'fa-magnifying-glass', search_planning: 'fa-magnifying-glass',
- observation: 'fa-eye', output_generation: 'fa-file-pen',
+ observation: 'fa-eye', synthesis: 'fa-file-pen',
+ output_generation: 'fa-file-pen',
report_generation: 'fa-file-pen',
synthesis_error: 'fa-triangle-exclamation', synthesis_fallback: 'fa-rotate',
report_complete: 'fa-check',
@@ -65,6 +67,15 @@
};
// "complete" excluded — fires after response is written (broken sequence ordering)
const STEP_PHASES = new Set(Object.keys(STEP_ICONS).filter(k => !k.startsWith('_')));
+ // Phases whose data.content is an expandable step detail (planned
+ // questions, searched questions, found sources / tool output). Keep in
+ // sync with _STEP_DETAIL_PHASES in research_service.py.
+ const STEP_DETAIL_PHASES = new Set(['search_planning', 'search', 'observation']);
+ // Phases that are distinct per-event (a new tool result, a new
+ // iteration's planning) — always a new row, never a same-phase
+ // overwrite of the last one. Keep in sync with
+ // _REPEATABLE_STEP_PHASES in research_service.py.
+ const REPEATABLE_STEP_PHASES = new Set(['observation', 'search_planning']);
const MAX_LIVE_STEPS = 8;
let lastStepPhase = null;
// Cap client-side accumulation of streamed tokens. Mirrors the
@@ -1938,19 +1949,22 @@
// Add live step message for significant phases (dedup by phase)
if (message && !streamingMessageEl) {
const phase = data.phase;
- // Observation events carry the (bounded) full tool output in
- // data.content. Append it beneath the one-line message so the
- // click-to-expand step shows what the tool actually returned.
- // Mirrors _compose_chat_step_content on the backend, which
- // persists the same composition to chat_progress_steps — the
- // live accordion and a post-reload session must render
- // identically (symmetry invariant).
- const stepText = (phase === 'observation' && data.content)
+ // Search-pipeline events carry a bounded expandable detail in
+ // data.content (tool output for observations, question lists
+ // for planning/search steps). Append it beneath the one-line
+ // message so the click-to-expand step shows it. Mirrors
+ // _compose_chat_step_content on the backend, which persists
+ // the same composition to chat_progress_steps — the live
+ // accordion and a post-reload session must render identically
+ // (symmetry invariant).
+ const stepText = (STEP_DETAIL_PHASES.has(phase) && data.content)
? message + '\n\n' + data.content
: message;
if (STEP_PHASES.has(phase)) {
- if (phase !== lastStepPhase || phase === 'observation') {
- // Each observation is a distinct source — always create new bubble
+ if (phase !== lastStepPhase || REPEATABLE_STEP_PHASES.has(phase)) {
+ // Repeatable phases are distinct per event (a new
+ // source, a new iteration's planning) — always a new
+ // bubble, mirroring the backend dedup exemption.
addLiveStepMessage(STEP_ICONS[phase] || STEP_ICONS._default, stepText);
lastStepPhase = phase;
} else {
diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.js
index bfd4f39af6..6c18b1df6f 100644
--- a/src/local_deep_research/web/static/js/components/progress.js
+++ b/src/local_deep_research/web/static/js/components/progress.js
@@ -670,8 +670,11 @@
}
}
- // Update page title with progress
- if (data.progress !== undefined) {
+ // Update page title with progress. A frame without a percentage
+ // (null: relayed sub-search and delegate step events carry none)
+ // must leave the title alone, as it does the bar above; Math.floor
+ // would turn null into 0 and show "Research (0%)".
+ if (data.progress !== undefined && data.progress !== null) {
// Ensure progress is capped at 100% for page title
const cappedProgress = Math.max(0, Math.min(100, Math.floor(data.progress)));
document.title = `Research (${cappedProgress}%) - Local Deep Research`;
diff --git a/tests/advanced_search_system/strategies/test_base_strategy.py b/tests/advanced_search_system/strategies/test_base_strategy.py
index 2db84eb11e..ad4b5991cc 100644
--- a/tests/advanced_search_system/strategies/test_base_strategy.py
+++ b/tests/advanced_search_system/strategies/test_base_strategy.py
@@ -245,7 +245,12 @@ class TestValidateSearchEngine:
class TestEmitQuestionGenerationProgress:
- """Tests for _emit_question_generation_progress method."""
+ """Tests for _emit_question_generation_progress method.
+
+ The events use the ``search_planning`` step phase and carry the full
+ previous-question list in ``metadata["content"]`` (no "... and N more"
+ sampling) so the chat step row can expand to show it.
+ """
def test_emit_first_iteration_progress(self):
"""Emit progress for first iteration."""
@@ -260,12 +265,16 @@ class TestEmitQuestionGenerationProgress:
callback.assert_called_once()
call_args = callback.call_args
assert "test query" in call_args[0][0]
+ assert "\n" not in call_args[0][0] # one-line message
assert call_args[0][1] == 10
+ assert call_args[0][2]["phase"] == "search_planning"
assert call_args[0][2]["iteration"] == 1
assert call_args[0][2]["type"] == "milestone"
- def test_emit_later_iteration_progress(self):
- """Emit progress for later iterations."""
+ def test_emit_later_iteration_lists_all_questions_in_content(self):
+ """Later iterations: one-line message; ALL previous questions in
+ metadata['content'] — the old 3-question sample with '... and N
+ more' hid most of them."""
strategy = ConcreteStrategy()
strategy.questions_by_iteration = {
1: ["Question 1", "Question 2", "Question 3", "Question 4"]
@@ -280,12 +289,68 @@ class TestEmitQuestionGenerationProgress:
callback.assert_called_once()
call_args = callback.call_args
assert "10 sources" in call_args[0][0]
- assert "and 1 more" in call_args[0][0] # 4 questions, showing 3
- assert call_args[0][2]["source_count"] == 10
+ assert "\n" not in call_args[0][0] # one-line message
+ assert "more" not in call_args[0][0]
+ metadata = call_args[0][2]
+ assert metadata["phase"] == "search_planning"
+ assert metadata["source_count"] == 10
+ for q in strategy.questions_by_iteration[1]:
+ assert q in metadata["content"]
+
+ def test_emit_later_iteration_without_prev_questions_has_no_content(self):
+ strategy = ConcreteStrategy()
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+
+ strategy._emit_question_generation_progress(
+ iteration=2, progress_percent=50, source_count=0
+ )
+
+ callback.assert_called_once()
+ assert "content" not in callback.call_args[0][2]
+
+ def test_first_iteration_query_newlines_flattened_and_capped(self):
+ """Chat's textarea allows Shift+Enter — a multi-line query must
+ still produce a one-line message, capped with a visible marker."""
+ strategy = ConcreteStrategy()
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+
+ query = "line one\nline two " + "q" * 200
+ strategy._emit_question_generation_progress(
+ iteration=1, progress_percent=10, query=query
+ )
+
+ message = callback.call_args[0][0]
+ assert "\n" not in message
+ shown = message.split('"')[1]
+ assert shown.startswith("line one line two ")
+ assert len(shown) == 151 # 150 chars + truncation marker
+ assert shown.endswith("…")
+
+ def test_first_iteration_query_at_cap_is_not_marked(self):
+ from local_deep_research.advanced_search_system.strategies.base_strategy import (
+ _OBSERVATION_PREVIEW_MAX_CHARS,
+ )
+
+ strategy = ConcreteStrategy()
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+
+ query = "q" * _OBSERVATION_PREVIEW_MAX_CHARS
+ strategy._emit_question_generation_progress(
+ iteration=1, progress_percent=10, query=query
+ )
+
+ assert callback.call_args[0][0].split('"')[1] == query
class TestEmitSearchingProgress:
- """Tests for _emit_searching_progress method."""
+ """Tests for _emit_searching_progress method.
+
+ The events use the ``search`` step phase; the full question list rides
+ in ``metadata["content"]`` (no "... and N more" sampling).
+ """
def test_emit_searching_progress_basic(self):
"""Emit searching progress with questions."""
@@ -300,12 +365,15 @@ class TestEmitSearchingProgress:
callback.assert_called_once()
call_args = callback.call_args
- assert "Searching iteration 1" in call_args[0][0]
- assert "Q1" in call_args[0][0]
- assert call_args[0][2]["questions"] == questions
-
- def test_emit_searching_progress_many_questions(self):
- """Emit searching progress with many questions."""
+ assert call_args[0][0] == "Searching with 3 questions (iteration 1)"
+ metadata = call_args[0][2]
+ assert metadata["phase"] == "search"
+ assert metadata["questions"] == questions
+ for q in questions:
+ assert q in metadata["content"]
+
+ def test_emit_searching_progress_many_questions_all_listed(self):
+ """All questions appear in the detail — no '... and N more'."""
strategy = ConcreteStrategy()
callback = Mock()
strategy.set_progress_callback(callback)
@@ -317,7 +385,80 @@ class TestEmitSearchingProgress:
callback.assert_called_once()
call_args = callback.call_args
- assert "and 2 more" in call_args[0][0] # 7 questions, showing 5
+ assert "more" not in call_args[0][0]
+ for q in questions:
+ assert q in call_args[0][2]["content"]
+
+
+class TestEmitSearchResultsObservation:
+ """Tests for _emit_search_results_observation method."""
+
+ def test_emit_observation_with_results(self):
+ strategy = ConcreteStrategy()
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+
+ results = [
+ {"title": "Result A", "link": "http://a.com"},
+ {"title": "Result B", "url": "http://b.com"},
+ {"snippet": "no title or link"},
+ "not-a-dict",
+ ]
+ strategy._emit_search_results_observation(
+ iteration=1,
+ questions=["Q1", "Q2"],
+ results=results,
+ progress_percent=40,
+ )
+
+ callback.assert_called_once()
+ call_args = callback.call_args
+ assert (
+ call_args[0][0]
+ == "📄 Found 4 results from 2 searches (iteration 1)"
+ )
+ metadata = call_args[0][2]
+ assert metadata["phase"] == "observation"
+ assert metadata["iteration"] == 1
+ assert "• Result A (http://a.com)" in metadata["content"]
+ assert "• Result B (http://b.com)" in metadata["content"]
+ assert "• Untitled" in metadata["content"]
+
+ def test_emit_observation_no_results_has_no_content(self):
+ strategy = ConcreteStrategy()
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+
+ strategy._emit_search_results_observation(
+ iteration=2, questions=["Q1"], results=[], progress_percent=60
+ )
+
+ callback.assert_called_once()
+ call_args = callback.call_args
+ assert (
+ call_args[0][0] == "📄 Found 0 results from 1 search (iteration 2)"
+ )
+ assert "content" not in call_args[0][2]
+
+ def test_emit_observation_detail_is_capped(self):
+ from local_deep_research.advanced_search_system.strategies.base_strategy import (
+ _OBSERVATION_DETAIL_MAX_CHARS,
+ )
+
+ strategy = ConcreteStrategy()
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+
+ results = [
+ {"title": "T" * 200, "link": f"http://x{i}.com"} for i in range(40)
+ ]
+ strategy._emit_search_results_observation(
+ iteration=1, questions=["Q"], results=results, progress_percent=40
+ )
+
+ content = callback.call_args[0][2]["content"]
+ assert len(content) == _OBSERVATION_DETAIL_MAX_CHARS + 2
+ assert content.endswith(" …")
class TestAbstractMethod:
@@ -383,6 +524,106 @@ class TestStrategySubclassing:
assert result["param"] == "test_value"
+class TestDetailListOneLinePerEntry:
+ """Every entry in an expandable detail list must occupy exactly one
+ line.
+
+ The step message states a count ("Found 3 results", "Searching with 5
+ questions") and the detail lists that many bullets. Externally sourced
+ text — scraped page titles, PDF metadata, LLM-generated questions —
+ can contain newlines, which would split one entry across two visual
+ lines (the second with no bullet marker), so the rendered list stops
+ matching the stated count.
+ """
+
+ def _emit(self, method, **kwargs):
+ strategy = ConcreteStrategy()
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+ getattr(strategy, method)(**kwargs)
+ callback.assert_called_once()
+ return callback.call_args[0]
+
+ def test_result_title_with_newline_stays_one_bullet(self):
+ message, _, metadata = self._emit(
+ "_emit_search_results_observation",
+ iteration=1,
+ questions=["Q1"],
+ results=[
+ {
+ "title": "Fed holds rates\nMarkets react",
+ "link": "http://r.com",
+ },
+ {"title": "Second", "link": "http://s.com"},
+ ],
+ progress_percent=40,
+ )
+ content = metadata["content"]
+ assert content.count("\n") == 1 # 2 entries -> exactly 1 separator
+ assert len(content.splitlines()) == 2
+ assert all(ln.startswith("• ") for ln in content.splitlines())
+ assert "• Fed holds rates Markets react (http://r.com)" in content
+ assert "Found 2 results" in message
+
+ def test_result_title_without_link_stays_one_bullet(self):
+ _, _, metadata = self._emit(
+ "_emit_search_results_observation",
+ iteration=1,
+ questions=["Q1"],
+ results=[{"title": "No link\nsecond line"}],
+ progress_percent=40,
+ )
+ assert metadata["content"] == "• No link second line"
+
+ def test_searched_question_with_newline_stays_one_bullet(self):
+ _, _, metadata = self._emit(
+ "_emit_searching_progress",
+ iteration=1,
+ questions=["What is A?\nAnd also B?", "Plain question"],
+ progress_percent=25,
+ )
+ content = metadata["content"]
+ assert len(content.splitlines()) == 2
+ assert "• What is A? And also B?" in content
+
+ def test_previous_question_with_newline_stays_one_bullet(self):
+ strategy = ConcreteStrategy()
+ strategy.questions_by_iteration = {1: ["Multi\nline question", "Plain"]}
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+ strategy._emit_question_generation_progress(
+ iteration=2, progress_percent=50, source_count=4
+ )
+ content = callback.call_args[0][2]["content"]
+ # "Previous questions:" header + one line per question
+ assert len(content.splitlines()) == 3
+ assert "• Multi line question" in content
+
+ def test_carriage_returns_and_tabs_are_flattened(self):
+ """\\r, \\r\\n and tabs break the one-line contract just as \\n does."""
+ _, _, metadata = self._emit(
+ "_emit_searching_progress",
+ iteration=1,
+ questions=["bare\rCR", "crlf\r\nhere", "tab\tseparated"],
+ progress_percent=25,
+ )
+ content = metadata["content"]
+ assert len(content.splitlines()) == 3
+ assert "• bare CR" in content
+ assert "• crlf here" in content
+ assert "• tab separated" in content
+
+ def test_iteration_one_query_with_carriage_return_stays_one_line(self):
+ message, _, _ = self._emit(
+ "_emit_question_generation_progress",
+ iteration=1,
+ progress_percent=10,
+ query="line one\r\nline two\rline three",
+ )
+ assert "\n" not in message and "\r" not in message
+ assert "line one line two line three" in message
+
+
class TestFormatCitations:
"""_format_citations forwards content prose so uncited hits leave
the Sources block (#5379)."""
diff --git a/tests/advanced_search_system/strategies/test_strategy_cancellation_regression.py b/tests/advanced_search_system/strategies/test_strategy_cancellation_regression.py
index 928fcab69f..abed2bdcb1 100644
--- a/tests/advanced_search_system/strategies/test_strategy_cancellation_regression.py
+++ b/tests/advanced_search_system/strategies/test_strategy_cancellation_regression.py
@@ -297,8 +297,11 @@ class TestTopicOrganizationCancellation:
assert len(received) == 1
assert received[0][2]["phase"] == "termination_check"
- # Ordinary progress events are suppressed.
- delegate_cb("Searching", 50, {"phase": "parallel_search"})
+ # Ordinary progress events are suppressed. (The delegate's step
+ # events -- search_planning, search, observation -- are the ones
+ # that are forwarded, with no percentage; see TestDelegateProgress
+ # in test_topic_organization_strategy.py.)
+ delegate_cb("Initializing", 5, {"phase": "init"})
delegate_cb("Synthesizing", 90, {"phase": "synthesis"})
assert len(received) == 1 # still only the termination check
diff --git a/tests/advanced_search_system/strategies/test_strategy_step_events.py b/tests/advanced_search_system/strategies/test_strategy_step_events.py
new file mode 100644
index 0000000000..acac1153a3
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_strategy_step_events.py
@@ -0,0 +1,263 @@
+"""Wiring tests: classic strategies emit chat-step-phase progress events.
+
+The chat UI only renders progress events whose phase is in
+``research_service._STEP_PHASES``, and only composes the expandable detail
+for phases in ``_STEP_DETAIL_PHASES``. These tests drive the REAL
+``analyze_topic`` loops (LLM/search mocked) and assert the full step
+sequence a chat user sees: planning → searching → results observation →
+synthesis — with the question lists / found sources riding in
+``metadata["content"]``.
+
+Regression guard for the gap where source-based / focused-iteration runs
+produced almost no step timeline in chat mode because their phases
+(``question_generation``, ``parallel_search``, custom strings) matched
+nothing in the step vocabulary.
+"""
+
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.web.services.research_service import (
+ _STEP_DETAIL_PHASES,
+ _STEP_PHASES,
+)
+
+
+def _collect_progress(strategy):
+ """Attach a recording callback; return the list of (message, metadata)."""
+ events = []
+
+ def callback(message, progress_percent, metadata):
+ events.append((message, metadata))
+
+ strategy.set_progress_callback(callback)
+ return events
+
+
+def _step_events(events):
+ return [(msg, md) for msg, md in events if md.get("phase") in _STEP_PHASES]
+
+
+class TestSourceBasedStepEvents:
+ def _make_strategy(self):
+ from local_deep_research.advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+ )
+
+ return SourceBasedSearchStrategy(
+ model=MagicMock(),
+ search=MagicMock(),
+ all_links_of_system=[],
+ use_cross_engine_filter=False,
+ settings_snapshot={"search.iterations": {"value": 1}},
+ )
+
+ def test_full_run_emits_step_phase_sequence_with_detail(self):
+ strategy = self._make_strategy()
+ events = _collect_progress(strategy)
+
+ results = [
+ {"title": "Result A", "link": "http://a.com", "snippet": "sa"},
+ {"title": "Result B", "link": "http://b.com", "snippet": "sb"},
+ ]
+ with (
+ patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["What is A?"],
+ ),
+ patch(
+ "local_deep_research.advanced_search_system.strategies.source_based_strategy.run_parallel_searches",
+ return_value=[
+ (0, {"question": "What is A?", "results": results})
+ ],
+ ),
+ patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Done", "documents": []},
+ ),
+ ):
+ strategy.analyze_topic("test query")
+
+ phases = [md["phase"] for _, md in _step_events(events)]
+ # The chat timeline: init → planning → searching → results → synthesis
+ assert phases[0] == "init"
+ assert "search_planning" in phases
+ assert "search" in phases
+ assert "observation" in phases
+ assert "synthesis" in phases
+ assert phases.index("search_planning") < phases.index("search")
+ assert phases.index("search") < phases.index("observation")
+ assert phases.index("observation") < phases.index("synthesis")
+
+ search_events = [
+ (m, md) for m, md in events if md.get("phase") == "search"
+ ]
+ assert "What is A?" in search_events[0][1]["content"]
+
+ obs = [(m, md) for m, md in events if md.get("phase") == "observation"]
+ obs_msg, obs_md = obs[0]
+ # The original query is searched verbatim alongside the LLM question.
+ assert obs_msg.startswith("📄 Found 2 results from 2 searches")
+ assert "• Result A (http://a.com)" in obs_md["content"]
+ assert "• Result B (http://b.com)" in obs_md["content"]
+
+ def test_detail_phases_are_step_phases(self):
+ """Detail-carrying phases must be renderable steps at all."""
+ assert _STEP_DETAIL_PHASES <= _STEP_PHASES
+
+ def _make_two_iteration_strategy(self):
+ from local_deep_research.advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+ )
+
+ return SourceBasedSearchStrategy(
+ model=MagicMock(),
+ search=MagicMock(),
+ all_links_of_system=[],
+ use_cross_engine_filter=False,
+ settings_snapshot={"search.iterations": {"value": 2}},
+ )
+
+ def test_second_iteration_planning_lists_first_iterations_questions(self):
+ """The iteration-2 search_planning detail must carry iteration 1's
+ questions as populated by the REAL loop (guards the write-after-emit
+ ordering of questions_by_iteration)."""
+ strategy = self._make_two_iteration_strategy()
+ events = _collect_progress(strategy)
+
+ with (
+ patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ side_effect=[["What is A?"], ["What is B?"]],
+ ),
+ patch(
+ "local_deep_research.advanced_search_system.strategies.source_based_strategy.run_parallel_searches",
+ return_value=[
+ (
+ 0,
+ {
+ "question": "q",
+ "results": [{"title": "T", "link": "http://t.com"}],
+ },
+ )
+ ],
+ ),
+ patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Done", "documents": []},
+ ),
+ ):
+ strategy.analyze_topic("test query")
+
+ planning = [
+ (m, md) for m, md in events if md.get("phase") == "search_planning"
+ ]
+ assert len(planning) == 2
+ # Iteration 1: no detail, query in the message.
+ assert "test query" in planning[0][0]
+ assert "content" not in planning[0][1]
+ # Iteration 2: iteration 1's actual questions (original query is
+ # searched verbatim alongside the LLM question) in the detail.
+ assert "iteration 2" in planning[1][0]
+ assert "What is A?" in planning[1][1]["content"]
+ assert "test query" in planning[1][1]["content"]
+
+ def test_zero_question_iteration_still_emits_planning(self):
+ """An iteration whose LLM yields no questions must still surface
+ its planning step (search/observation are skipped); the following
+ synthesis still runs on iteration 1's results."""
+ strategy = self._make_two_iteration_strategy()
+ events = _collect_progress(strategy)
+
+ with (
+ patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ side_effect=[["What is A?"], []],
+ ),
+ patch(
+ "local_deep_research.advanced_search_system.strategies.source_based_strategy.run_parallel_searches",
+ return_value=[
+ (
+ 0,
+ {
+ "question": "q",
+ "results": [{"title": "T", "link": "http://t.com"}],
+ },
+ )
+ ],
+ ),
+ patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Done", "documents": []},
+ ),
+ ):
+ strategy.analyze_topic("test query")
+
+ phases = [md["phase"] for _, md in _step_events(events)]
+ assert phases.count("search_planning") == 2
+ assert phases.count("search") == 1
+ assert phases.count("observation") == 1
+
+
+class TestFocusedIterationStepEvents:
+ def _make_strategy(self):
+ from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
+ FocusedIterationStrategy,
+ )
+
+ # questions_per_iteration=2: iteration 1 is [original query] +
+ # LLM questions, trimmed to the limit — 2 keeps one of each.
+ return FocusedIterationStrategy(
+ model=MagicMock(),
+ search=MagicMock(),
+ all_links_of_system=[],
+ max_iterations=1,
+ questions_per_iteration=2,
+ )
+
+ def test_full_run_emits_step_phase_sequence_with_detail(self):
+ strategy = self._make_strategy()
+ # Simple path: no browsecomp explorer.
+ strategy.explorer = None
+ strategy.use_browsecomp_optimization = False
+ events = _collect_progress(strategy)
+
+ results = [{"title": "Doc X", "link": "http://x.com"}]
+ with (
+ patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Focused Q1"],
+ ),
+ patch.object(
+ strategy,
+ "_execute_parallel_searches",
+ return_value=results,
+ ),
+ patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Done", "documents": []},
+ ),
+ ):
+ strategy.analyze_topic("focused test query")
+
+ phases = [md["phase"] for _, md in _step_events(events)]
+ assert "search_planning" in phases
+ assert "search" in phases
+ assert "observation" in phases
+ assert "synthesis" in phases
+ assert phases.index("search") < phases.index("observation")
+
+ search_events = [
+ (m, md) for m, md in events if md.get("phase") == "search"
+ ]
+ assert "Focused Q1" in search_events[0][1]["content"]
+
+ obs = [(m, md) for m, md in events if md.get("phase") == "observation"]
+ assert "• Doc X (http://x.com)" in obs[0][1]["content"]
diff --git a/tests/advanced_search_system/strategies/test_topic_organization_strategy.py b/tests/advanced_search_system/strategies/test_topic_organization_strategy.py
index 3b943a4879..5792369ffb 100644
--- a/tests/advanced_search_system/strategies/test_topic_organization_strategy.py
+++ b/tests/advanced_search_system/strategies/test_topic_organization_strategy.py
@@ -132,6 +132,75 @@ class TestTopicOrganizationStrategyInit:
assert strategy.citation_handler is mock_citation_handler
+class TestDelegateProgress:
+ @pytest.mark.parametrize("use_focused_iteration", [False, True])
+ def test_no_text_delegate_does_not_forward_synthesis(
+ self, use_focused_iteration: bool
+ ):
+ from local_deep_research.advanced_search_system.strategies.topic_organization_strategy import (
+ TopicOrganizationStrategy,
+ )
+
+ strategy = TopicOrganizationStrategy(
+ search=Mock(),
+ model=Mock(),
+ use_focused_iteration=use_focused_iteration,
+ )
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+
+ strategy.source_strategy.progress_callback(
+ "Planning searches", 10, {"phase": "search_planning"}
+ )
+ strategy.source_strategy.progress_callback(
+ "Synthesizing sources", 90, {"phase": "synthesis"}
+ )
+ strategy._update_progress(
+ "Generating answer", 85, {"phase": "output_generation"}
+ )
+
+ assert callback.call_args_list == [
+ (("Planning searches", None, {"phase": "search_planning"}),),
+ (("Generating answer", 85, {"phase": "output_generation"}),),
+ ]
+
+ @pytest.mark.parametrize(
+ ("phase", "forwarded"),
+ [
+ ("search_planning", True),
+ ("search", True),
+ ("observation", True),
+ ("termination_check", True),
+ # A bare "planning" is not a phase any strategy emits; the
+ # whitelist is exactly the gathering timeline plus the
+ # termination check.
+ ("planning", False),
+ ("init", False),
+ ("synthesis", False),
+ ("output_generation", False),
+ ],
+ )
+ def test_delegate_whitelist_is_exactly_the_gathering_timeline(
+ self, phase: str, forwarded: bool
+ ):
+ from local_deep_research.advanced_search_system.strategies.topic_organization_strategy import (
+ TopicOrganizationStrategy,
+ )
+
+ strategy = TopicOrganizationStrategy(search=Mock(), model=Mock())
+ callback = Mock()
+ strategy.set_progress_callback(callback)
+
+ strategy.source_strategy.progress_callback("msg", 42, {"phase": phase})
+
+ if forwarded:
+ # Percentages never reach the outer bar: the delegate's own
+ # 5-90% scale would yank it.
+ callback.assert_called_once_with("msg", None, {"phase": phase})
+ else:
+ callback.assert_not_called()
+
+
class TestTopicExtraction:
"""Tests for topic extraction methods."""
diff --git a/tests/js/components/chat-live-step-detail.test.js b/tests/js/components/chat-live-step-detail.test.js
index ecc390d5d0..387702a8e8 100644
--- a/tests/js/components/chat-live-step-detail.test.js
+++ b/tests/js/components/chat-live-step-detail.test.js
@@ -184,7 +184,7 @@ describe('chat.js — live step observation detail (data.content)', () => {
).toBe(message);
});
- it('does NOT compose content for non-observation step phases', () => {
+ it('does NOT compose content for non-detail step phases', () => {
const message = 'Generating final answer…';
progressCb({
research_id: RESEARCH_ID,
@@ -201,6 +201,72 @@ describe('chat.js — live step observation detail (data.content)', () => {
).toBe(message);
});
+ it('composes question-list content for search_planning steps', () => {
+ const message = 'Generating search questions from 10 sources (iteration 2)';
+ const detail = 'Previous questions:\n• Q1\n• Q2\n• Q3\n• Q4';
+ progressCb({
+ research_id: RESEARCH_ID,
+ phase: 'search_planning',
+ message,
+ content: detail,
+ progress: 30,
+ });
+
+ const steps = liveSteps();
+ expect(steps.length).toBe(1);
+ expect(
+ steps[0].querySelector('.ldr-chat-message-text').textContent
+ ).toBe(message + '\n\n' + detail);
+ });
+
+ it('creates a new row for each search_planning event (repeatable phase)', () => {
+ // A zero-question iteration means two planning events arrive with
+ // no search/observation between them — the second must be a new
+ // row, not an overwrite of the first (mirrors the backend's
+ // _REPEATABLE_STEP_PHASES dedup exemption).
+ progressCb({
+ research_id: RESEARCH_ID,
+ phase: 'search_planning',
+ message: 'Planning initial search questions for: "q"',
+ progress: 10,
+ });
+ progressCb({
+ research_id: RESEARCH_ID,
+ phase: 'search_planning',
+ message: 'Generating search questions from 4 sources (iteration 2)',
+ progress: 25,
+ });
+
+ const steps = liveSteps();
+ expect(steps.length).toBe(2);
+ expect(
+ steps[0].querySelector('.ldr-chat-message-text').textContent
+ ).toContain('Planning initial');
+ expect(
+ steps[1].querySelector('.ldr-chat-message-text').textContent
+ ).toContain('iteration 2');
+ });
+
+ it('renders synthesis as a step but never composes its content', () => {
+ const message = 'Synthesizing 45 sources from 2 iterations...';
+ progressCb({
+ research_id: RESEARCH_ID,
+ phase: 'synthesis',
+ message,
+ content: 'the entire synthesized answer',
+ progress: 90,
+ });
+
+ const steps = liveSteps();
+ expect(steps.length).toBe(1);
+ expect(
+ steps[0].querySelector('.ldr-chat-message-text').textContent
+ ).toBe(message);
+ expect(
+ steps[0].querySelector('.ldr-chat-message-avatar i').className
+ ).toContain('fa-file-pen');
+ });
+
it('keeps the thinking-bubble preview on the short message only', () => {
progressCb({
research_id: RESEARCH_ID,
diff --git a/tests/js/components/progress-null-progress-frame.test.js b/tests/js/components/progress-null-progress-frame.test.js
new file mode 100644
index 0000000000..3b4c2cab51
--- /dev/null
+++ b/tests/js/components/progress-null-progress-frame.test.js
@@ -0,0 +1,129 @@
+/**
+ * A socket frame without a percentage must not touch the page title.
+ *
+ * Relayed step events (the topic-organization source-gathering delegate's
+ * planning/search/observation steps, LangGraph sub-search relays) are
+ * emitted with `progress: null`. The bar already ignores a null; the title
+ * ran it through Math.floor, which turned null into 0 and showed
+ * "Research (0%)" for each such event.
+ */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+
+const RESEARCH_ID = 'progress-null-frame-5188';
+
+let progressCallback;
+
+beforeEach(() => {
+ progressCallback = null;
+ document.title = 'Research in progress';
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'error',
+ 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+ window.socket = {
+ subscribeToResearch: vi.fn((_researchId, callback) => {
+ progressCallback = callback;
+ }),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => false),
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it.each([
+ ['null', null],
+ ['absent', undefined],
+])('keeps the title and bar for a step frame whose percentage is %s', async (_label, missing) => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }));
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ vi.spyOn(window.api, 'getResearchStatus').mockResolvedValue({
+ status: 'in_progress',
+ progress: 40,
+ current_task: 'Hydrated from HTTP',
+ });
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await vi.waitFor(() => {
+ expect(progressCallback).toBeTypeOf('function');
+ expect(document.title).toBe('Research (40%) - Local Deep Research');
+ });
+
+ progressCallback({
+ status: 'in_progress',
+ progress: 55,
+ message: 'Gathering sources using source-based strategy',
+ });
+ expect(document.title).toBe('Research (55%) - Local Deep Research');
+ expect(document.getElementById('progress-bar').style.width).toBe('55%');
+
+ const stepFrame = {
+ phase: 'search',
+ message: 'Searching with 3 questions (iteration 1)',
+ };
+ if (missing === null) {
+ stepFrame.progress = null;
+ }
+ progressCallback(stepFrame);
+
+ // The frame is still consumed ...
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Searching with 3 questions (iteration 1)');
+ // ... but it neither resets the title nor moves the bar.
+ expect(document.title).toBe('Research (55%) - Local Deep Research');
+ expect(document.getElementById('progress-bar').style.width).toBe('55%');
+
+ // The next frame that carries a percentage updates both again.
+ progressCallback({
+ status: 'in_progress',
+ progress: 60,
+ message: 'Generating text synthesis from topics',
+ });
+ expect(document.title).toBe('Research (60%) - Local Deep Research');
+ expect(document.getElementById('progress-bar').style.width).toBe('60%');
+});
diff --git a/tests/strategies/test_multi_iteration_progress.py b/tests/strategies/test_multi_iteration_progress.py
index cc008a8778..6b0fe1b5e4 100644
--- a/tests/strategies/test_multi_iteration_progress.py
+++ b/tests/strategies/test_multi_iteration_progress.py
@@ -10,8 +10,18 @@ answer was still being generated.
These tests drive the REAL strategy with the strategy fixtures' mocked LLM
and search, first on its own and then through the REAL progress_callback
closure of run_research_process with the real research_state registry.
+
+Each iteration's planning step is reported with phase ``search_planning``.
+The classic strategies used to report it as ``question_generation``, a
+phase outside ``research_service._STEP_PHASES``, so chat mode never rendered
+it; the strategies now speak the chat step vocabulary (``search_planning``,
+``search``, ``observation``). Nothing else keyed on the old name (no JS
+consumer, no progress-UI branch, no metrics query), so this test is the only
+place that counted it and it counts the new name.
"""
+import itertools
+
import pytest
from local_deep_research.search_system_factory import create_strategy
@@ -68,12 +78,13 @@ def test_strategy_progress_is_monotonic_and_within_bounds(
strategy.analyze_topic("What is artificial intelligence?")
phases = [metadata.get("phase") for _, metadata in events]
- # Every iteration reported its question-generation step, inside the
+ # Every iteration reported its planning step (``search_planning``, the
+ # chat step phase that replaced ``question_generation``), inside the
# band before synthesis (90).
iteration_steps = [
progress
for progress, metadata in events
- if metadata.get("phase") == "question_generation"
+ if metadata.get("phase") == "search_planning"
]
assert len(iteration_steps) >= iterations, events
assert all(progress < 90 for progress in iteration_steps), events
@@ -97,6 +108,86 @@ def test_strategy_progress_is_monotonic_and_within_bounds(
), events
+# Per strategy: where its first iteration band starts, and the total width of
+# all its iteration bands. Both report init at 5; source-based iterates over
+# 5-75 (final_filtering follows at 80), focused-iteration over 10-90
+# (synthesis follows at 90).
+_ITERATION_BANDS = {
+ "source-based": (5, 70),
+ "focused-iteration": (10, 80),
+}
+
+
[email protected]("iterations", [14, 25, 60])
[email protected]("name", ["source-based", "focused-iteration"])
+def test_step_events_stay_in_their_band_with_many_iterations(
+ name,
+ iterations,
+ strategy_mock_llm,
+ strategy_mock_search,
+ strategy_settings_snapshot,
+):
+ """Every iteration's step events stay inside that iteration's band.
+
+ A band is ``width / iterations`` wide and nothing caps
+ ``search.iterations``, so it narrows as iterations grow. The planning,
+ searching and results step events sit at offsets that only fit a wide
+ band. Left fixed, source-based's results event fell below its searching
+ event from 5 iterations and below the init milestone past 14, and
+ focused-iteration's did from 14 iterations, with its searching event
+ passing synthesis (90) from 21 -- none of which the 2- and 3-iteration
+ test above can show, because the offsets happen to fit there. Both
+ strategies are the ones that call the shared step emitters;
+ topic-organization forwards their events with no percentage.
+ """
+ strategy = _strategy(
+ name,
+ iterations,
+ strategy_mock_llm,
+ strategy_mock_search,
+ strategy_settings_snapshot,
+ )
+ # The mocked question generator repeats itself, and an iteration with no
+ # new question is skipped before it searches. Give every iteration a
+ # fresh question so each one reaches its searching and results events.
+ fresh_questions = itertools.count(1)
+ strategy.question_generator.generate_questions = lambda **_: [
+ f"fresh question {next(fresh_questions)}"
+ ]
+ events = []
+ strategy.set_progress_callback(
+ lambda _message, progress, metadata: events.append(
+ (progress, dict(metadata or {}))
+ )
+ )
+
+ strategy.analyze_topic("What is artificial intelligence?")
+
+ phases = [metadata.get("phase") for _, metadata in events]
+ step_phases = ("search_planning", "search", "observation")
+ # The run really did emit all three step events once per iteration.
+ for step_phase in step_phases:
+ assert phases.count(step_phase) == iterations, (step_phase, phases)
+ first_band_start, total_width = _ITERATION_BANDS[name]
+ band = total_width / iterations
+ for progress, metadata in events:
+ if metadata.get("phase") not in step_phases:
+ continue
+ band_start = first_band_start + (metadata["iteration"] - 1) * band
+ assert band_start - 1e-9 <= progress <= band_start + band + 1e-9, (
+ metadata["phase"],
+ metadata["iteration"],
+ progress,
+ band_start,
+ )
+ before_synthesis = [
+ progress
+ for progress, _ in events[: phases.index("synthesis")]
+ if progress is not None
+ ]
+ _assert_monotonic_and_bounded(before_synthesis, 90)
+
+
@pytest.mark.parametrize("iterations", [2, 3])
def test_quick_run_reaches_100_and_is_final_only_on_completion(
iterations,
diff --git a/tests/web/services/test_chat_step_decision.py b/tests/web/services/test_chat_step_decision.py
index dbc1792de0..689fa2b67f 100644
--- a/tests/web/services/test_chat_step_decision.py
+++ b/tests/web/services/test_chat_step_decision.py
@@ -12,11 +12,16 @@ return to gate both the DB write and the socket emit.
The tests below pin down the contract per scenario.
"""
+import re
+from pathlib import Path
+
import pytest
from local_deep_research.web.services.research_service import (
_chat_step_decision,
_compose_chat_step_content,
+ _REPEATABLE_STEP_PHASES,
+ _STEP_DETAIL_PHASES,
_STEP_PHASES,
)
@@ -108,7 +113,7 @@ class TestRepeatPhaseDedup:
assert (persist, suppress) == (False, True)
def test_observation_can_repeat(self):
- """'observation' is the documented exception to the dedup —
+ """'observation' is a documented exception to the dedup —
it represents distinct in-iteration findings and must always
persist + emit."""
persist, suppress = _chat_step_decision(
@@ -119,6 +124,22 @@ class TestRepeatPhaseDedup:
assert persist is True
assert suppress is False
+ def test_search_planning_can_repeat(self):
+ """A zero-question iteration emits planning then skips its
+ search/observation events — the NEXT iteration's planning is a
+ same-phase repeat that must still persist + emit, or the timeline
+ silently skips an iteration."""
+ persist, suppress = _chat_step_decision(
+ phase="search_planning",
+ last_step_phase="search_planning",
+ is_final=False,
+ )
+ assert persist is True
+ assert suppress is False
+
+ def test_repeatable_phases_are_step_phases(self):
+ assert _REPEATABLE_STEP_PHASES <= _STEP_PHASES
+
def test_repeat_phase_but_is_final_still_emits(self):
"""Final phases (error, report_complete) emit even on repeat so
the client completion handler fires. Persist is still blocked by
@@ -165,7 +186,7 @@ class TestComposeChatStepContent:
)
assert out == "📄 From PubMed: no results"
- def test_non_observation_phase_ignores_content(self):
+ def test_non_detail_phase_ignores_content(self):
out = _compose_chat_step_content(
"Generating final answer…",
"output_generation",
@@ -173,6 +194,33 @@ class TestComposeChatStepContent:
)
assert out == "Generating final answer…"
+ def test_search_planning_with_detail_appends_it(self):
+ out = _compose_chat_step_content(
+ "Generating search questions from 10 sources (iteration 2)",
+ "search_planning",
+ {"content": "Previous questions:\n• Q1\n• Q2"},
+ )
+ assert out.endswith("\n\nPrevious questions:\n• Q1\n• Q2")
+
+ def test_search_with_detail_appends_it(self):
+ out = _compose_chat_step_content(
+ "Searching with 3 questions (iteration 1)",
+ "search",
+ {"content": "• Q1\n• Q2\n• Q3"},
+ )
+ assert out.endswith("\n\n• Q1\n• Q2\n• Q3")
+
+ def test_synthesis_phase_ignores_content(self):
+ """`synthesis` is a step phase but NOT a detail phase — strategies
+ must never get a full synthesized answer duplicated into a step
+ row via metadata['content']."""
+ out = _compose_chat_step_content(
+ "Synthesizing 45 sources…",
+ "synthesis",
+ {"content": "the entire synthesized answer"},
+ )
+ assert out == "Synthesizing 45 sources…"
+
def test_empty_detail_keeps_message(self):
out = _compose_chat_step_content(
"📄 From arXiv: …", "observation", {"content": ""}
@@ -180,6 +228,43 @@ class TestComposeChatStepContent:
assert out == "📄 From arXiv: …"
+class TestPhaseVocabularyJsSync:
+ """The chat client renders steps from the SAME phase vocabulary the
+ server persists with — silent drift breaks the live/reload symmetry
+ invariant, so pin chat.js's literals against the Python sets."""
+
+ def _chat_js(self):
+ root = Path(__file__).resolve().parents[3]
+ return (
+ root / "src/local_deep_research/web/static/js/components/chat.js"
+ ).read_text(encoding="utf-8")
+
+ def test_step_icons_keys_match_step_phases(self):
+ block = re.search(
+ r"const STEP_ICONS = \{(.*?)\};", self._chat_js(), re.S
+ ).group(1)
+ js_phases = {
+ k
+ for k in re.findall(r"(\w+):\s*'fa-[\w-]+'", block)
+ if not k.startswith("_")
+ }
+ assert js_phases == _STEP_PHASES
+
+ def test_step_detail_phases_match(self):
+ block = re.search(
+ r"STEP_DETAIL_PHASES = new Set\(\[(.*?)\]\)", self._chat_js(), re.S
+ ).group(1)
+ assert set(re.findall(r"'(\w+)'", block)) == _STEP_DETAIL_PHASES
+
+ def test_repeatable_step_phases_match(self):
+ block = re.search(
+ r"REPEATABLE_STEP_PHASES = new Set\(\[(.*?)\]\)",
+ self._chat_js(),
+ re.S,
+ ).group(1)
+ assert set(re.findall(r"'(\w+)'", block)) == _REPEATABLE_STEP_PHASES
+
+
class TestSymmetryInvariant:
"""Property-style assertion of the invariant: for every event in
_STEP_PHASES, if we persist we also emit; if we don't persist and