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): expandable tool-result detail in research steps + full tool listing in heartbeat (#5051)

LearningCircuit996e1b809805
diff --git a/changelog.d/5051.feature.md b/changelog.d/5051.feature.md
new file mode 100644
index 0000000000..448b79f9b7
--- /dev/null
+++ b/changelog.d/5051.feature.md
@@ -0,0 +1 @@
+Research steps in chat mode now expand to show the actual tool output (search results, fetched page content — capped at 4,000 chars) when clicked, and the agent's "selecting next action from …" heartbeat lists every enabled tool instead of sampling 3 with "+N more".
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 8f0518a480..fd12a57f2f 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
@@ -174,6 +174,35 @@ _TOOL_DISPLAY_NAMES = {
"research_subtopic": "subtopic researcher",
}
+# The step heartbeat lists tools as a comma list ("selecting next action
+# from X, Y, Z…"). The sentence-fragment display names of the two
+# non-search tools read wrong in that context ("the page", "subtopic
+# researcher"), so the heartbeat uses these list-friendly labels instead;
+# every other tool falls through to ``_display_tool_name``.
+_HEARTBEAT_TOOL_LABELS = {
+ "fetch_content": "page fetching",
+ "research_subtopic": "subtopic research",
+}
+
+# Bounds for observation progress events. The one-line preview feeds the
+# log panel / current-task line / thinking bubble; the detail
+# (``metadata["content"]``) is persisted per chat step and emitted per
+# socket event, so it must stay bounded — but large enough to show what a
+# 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
+
+
+def _truncate_arg(value: str, limit: int = 80) -> str:
+ """Cap a tool-call arg for the one-line progress message.
+
+ Marks the cut with an ellipsis so a shortened query/URL doesn't read
+ as if it were the complete value.
+ """
+ return value[:limit] + "…" if len(value) > limit else value
+
def _tool_display_name(name: str) -> str:
"""Friendly name for a tool, falling back to a cleaned raw name."""
@@ -622,8 +651,11 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
``🔍 Searching <Display Name>: "<query>"`` (falls back to
``url`` if ``query`` is absent).
- All arg extractions are truncated to 80 chars to keep the chat-progress
- line bounded.
+ Arg extractions are truncated to 80 chars (marked with an ellipsis
+ so a cut arg doesn't read as complete) to keep the chat-progress
+ line bounded. Subtopic lists cap per item instead of cutting the
+ joined string, so every subtopic stays visible — the collapsed
+ step row ellipsizes via CSS and expands on click.
"""
tc_args = tc.get("args", {})
raw_name = tc.get("name", "")
@@ -631,7 +663,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# arg. Either way, show the meaningful arg in quotes so the user
# sees what the agent is actually looking up.
if raw_name == "fetch_content":
- target = str(tc_args.get("url", ""))[:80]
+ target = _truncate_arg(str(tc_args.get("url", "")))
return f'📖 Reading {display_name}: "{target}"'
if raw_name == "research_subtopic":
# Tool signature is `subtopics: list[str]`. Accept either key for
@@ -644,22 +676,89 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
),
)
if isinstance(raw_sub, list):
- sub = ", ".join(str(s) for s in raw_sub)[:80]
+ sub = ", ".join(_truncate_arg(str(s)) for s in raw_sub)
else:
- sub = str(raw_sub)[:80]
+ sub = _truncate_arg(str(raw_sub))
return f'🔬 Investigating subtopic: "{sub}"'
# Search-style tool — query arg (or URL if query missing). Use a
# loop-local name here — do NOT reassign the `query` parameter, which
# is still needed downstream by _synthesize_from_collector()/
# _finalize() as the original research question.
- tc_query = str(
- tc_args.get(
- "query",
- tc_args.get("url", ""),
+ tc_query = _truncate_arg(
+ str(
+ tc_args.get(
+ "query",
+ tc_args.get("url", ""),
+ )
)
- )[:80]
+ )
return f'🔍 Searching {display_name}: "{tc_query}"'
+ def _observation_event(self, msg) -> tuple[str, dict]:
+ """Build the (message, metadata) pair for a tool-result observation.
+
+ The message stays a one-line 150-char preview — it feeds the log
+ panel, the classic progress page's current-task line, and the chat
+ thinking bubble, none of which can absorb a full tool result. When
+ the output is longer than the preview, the (bounded) full output
+ rides along in ``metadata["content"]``: the chat route persists it
+ beneath the message so the click-to-expand step row shows what was
+ actually fetched, and the classic progress page's agent-thinking
+ panel appends it to its RESULT entry. Outputs the preview already
+ shows verbatim attach no detail — the expanded step would just
+ repeat the line ("No results." twice).
+
+ Extracted from the ``analyze_topic`` stream loop so it can be
+ unit-tested without driving the full LangGraph stream.
+ """
+ tool_name = getattr(msg, "name", "tool")
+ display_name = self._display_tool_name(tool_name)
+ raw = str(getattr(msg, "content", ""))
+ preview = raw[:_OBSERVATION_PREVIEW_MAX_CHARS].replace("\n", " ")
+ # Keep the stable tool id in metadata; the friendly label
+ # already lives in the message.
+ metadata = {"phase": "observation", "tool": tool_name}
+ # Attach detail only when it adds something beyond the preview —
+ # longer output, or short multi-line output whose newlines the
+ # preview flattened. Outputs identical to the preview would just
+ # be repeated in the expanded step.
+ if raw != preview:
+ detail = raw[:_OBSERVATION_DETAIL_MAX_CHARS]
+ if len(raw) > _OBSERVATION_DETAIL_MAX_CHARS:
+ detail += " …"
+ metadata["content"] = detail
+ return (f"📄 From {display_name}: {preview}", metadata)
+
+ def _heartbeat_message(self, iteration: int) -> str:
+ """Build the between-steps heartbeat line for the given iteration.
+
+ Before any source is gathered the agent is still planning, so the
+ line reports the size of its toolbox. Afterwards it lists EVERY
+ enabled tool by friendly name — an earlier 3-name sample with
+ "+N more" hid most engines, which users read as the agent having
+ fewer options than it does.
+
+ Extracted from the ``analyze_topic`` stream loop so it can be
+ unit-tested without driving the full LangGraph stream.
+ """
+ sources_so_far = len(self.all_links_of_system)
+ names = getattr(self, "_tool_names", []) or []
+ if sources_so_far == 0:
+ return (
+ f"Step {iteration} · planning approach "
+ f"with {len(names)} research tool"
+ f"{'s' if len(names) != 1 else ''} available…"
+ )
+ listing = ", ".join(
+ _HEARTBEAT_TOOL_LABELS.get(n) or self._display_tool_name(n)
+ for n in names
+ )
+ return (
+ f"Step {iteration} · {sources_so_far} source"
+ f"{'s' if sources_so_far != 1 else ''} gathered · "
+ f"selecting next action from {listing}…"
+ )
+
def _build_egress_context(self):
"""Construct the frozen ``EgressContext`` for this run.
@@ -1086,20 +1185,14 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
elif "tools" in chunk:
msgs = chunk["tools"].get("messages", [])
for msg in msgs:
- tool_name = getattr(msg, "name", "tool")
- display_name = self._display_tool_name(tool_name)
- preview = str(getattr(msg, "content", ""))[
- :150
- ].replace("\n", " ")
+ obs_message, obs_metadata = self._observation_event(msg)
self._update_progress(
- f"📄 From {display_name}: {preview}",
+ obs_message,
min(
85,
10 + int((iteration / effective_max) * 75) + 3,
),
- # Keep the stable tool id in metadata; the
- # friendly label already lives in the message.
- {"phase": "observation", "tool": tool_name},
+ obs_metadata,
)
# After every tool result, the agent immediately re-
# invokes the model to decide the next step. For
@@ -1113,33 +1206,8 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# sense of progress (which iteration, how many sources
# collected, which tools are available) instead of
# a generic "Choosing next step…" spinner.
- sources_so_far = len(self.all_links_of_system)
- tool_count = len(getattr(self, "_tool_names", []) or [])
- if sources_so_far == 0:
- heartbeat = (
- f"Step {iteration} · planning approach "
- f"with {tool_count} research tool"
- f"{'s' if tool_count != 1 else ''} available…"
- )
- else:
- # Show up to 3 representative tool names so the
- # user sees what the agent might pick next without
- # the line ballooning when many specialised
- # engines are enabled.
- names = getattr(self, "_tool_names", []) or []
- sample = ", ".join(
- self._display_tool_name(n) for n in names[:3]
- )
- more = (
- f" +{len(names) - 3} more" if len(names) > 3 else ""
- )
- heartbeat = (
- f"Step {iteration} · {sources_so_far} source"
- f"{'s' if sources_so_far != 1 else ''} gathered · "
- f"selecting next action from {sample}{more}…"
- )
self._update_progress(
- heartbeat,
+ self._heartbeat_message(iteration),
min(
85,
10 + int((iteration / effective_max) * 75) + 4,
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 7a4a11e3ab..17efaa9d0f 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -133,6 +133,28 @@ def _chat_step_decision(
return False, not is_final
+def _compose_chat_step_content(
+ message: str, phase: str | None, metadata: dict
+) -> 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).
+
+ Only observation events compose: other phases 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:
+ return f"{message}\n\n{detail}"
+ return message
+
+
def _parse_research_metadata(research_meta) -> dict:
"""Parse research_meta into a dict, handling both dict and JSON string types."""
if isinstance(research_meta, dict):
@@ -1212,6 +1234,31 @@ def run_research_process(research_id, query, mode, **kwargs):
for rid in stale:
del _last_emit_times[rid]
+ # Decide chat-step persistence BEFORE building the event:
+ # a step that will be persisted must always emit, even
+ # inside the throttle window above — otherwise a burst of
+ # back-to-back observations (the agent issuing several tool
+ # calls in one turn) writes rows the live UI never showed,
+ # breaking the symmetry invariant in the live direction.
+ #
+ # Symmetry invariant: for chat sessions, what the user sees
+ # live must equal what `loadSession` reconstructs on reload.
+ # If dedup blocks persistence of a repeat step phase, drop
+ # the socket emit too (unless this is a final-phase event
+ # the completion handler depends on) so live UI doesn't
+ # surface events that vanish on reload.
+ _chat_session_id = shared_research_context.get(
+ "chat_session_id"
+ )
+ _persist = False
+ _suppress_emit = False
+ if _chat_session_id:
+ _persist, _suppress_emit = _chat_step_decision(
+ phase, last_step_phase, is_final
+ )
+ if _persist:
+ should_emit = True
+
# Build event data (before emit, shared scope)
event_data = None
if should_emit:
@@ -1236,42 +1283,30 @@ def run_research_process(research_id, query, mode, **kwargs):
# Persist step message to chat session BEFORE emitting socket
# (ensures DB has the step when clients receive the event).
- #
- # Symmetry invariant: for chat sessions, what the user sees
- # live must equal what `loadSession` reconstructs on reload.
- # If dedup blocks persistence of a repeat step phase, drop
- # the socket emit too (unless this is a final-phase event
- # the completion handler depends on) so live UI doesn't
- # surface events that vanish on reload.
- _chat_session_id = shared_research_context.get(
- "chat_session_id"
- )
- if _chat_session_id:
- _persist, _suppress_emit = _chat_step_decision(
- phase, last_step_phase, is_final
- )
- if _persist:
- try:
- from ...chat.service import ChatService
+ if _persist:
+ try:
+ from ...chat.service import ChatService
- ChatService(username).add_progress_step(
- session_id=_chat_session_id,
- research_id=research_id,
- content=message,
- phase=phase,
- )
- last_step_phase = phase
- except Exception:
- logger.opt(exception=True).warning(
- "Failed to persist progress step"
- )
- # Symmetry invariant: if persistence failed
- # (e.g. OperationalError under DB contention),
- # suppress the live emit too — otherwise the
- # client sees a step that vanishes on reload.
- event_data = None
- if _suppress_emit:
+ ChatService(username).add_progress_step(
+ session_id=_chat_session_id,
+ research_id=research_id,
+ content=_compose_chat_step_content(
+ message, phase, metadata
+ ),
+ phase=phase,
+ )
+ last_step_phase = phase
+ except Exception:
+ logger.opt(exception=True).warning(
+ "Failed to persist progress step"
+ )
+ # Symmetry invariant: if persistence failed
+ # (e.g. OperationalError under DB contention),
+ # suppress the live emit too — otherwise the
+ # client sees a step that vanishes on reload.
event_data = None
+ if _suppress_emit:
+ event_data = None
# Emit socket event AFTER DB persistence
if event_data is not None:
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 decea47c7f..78382e5a09 100644
--- a/src/local_deep_research/web/static/js/components/chat.js
+++ b/src/local_deep_research/web/static/js/components/chat.js
@@ -182,7 +182,7 @@
};
data.messages.forEach(msg => {
if (msg.message_type === 'step') {
- const el = createStepElement(getStepIconForContent(msg.content), msg.content || '');
+ const el = createStepElement(getStepIconForRow(msg), msg.content || '');
if (el) pendingSteps.push(el);
} else {
flushSteps();
@@ -860,7 +860,7 @@
messagesData.messages.forEach(msg => {
if (msg.message_type === 'step') {
- const el = createStepElement(getStepIconForContent(msg.content), msg.content || '');
+ const el = createStepElement(getStepIconForRow(msg), msg.content || '');
if (el) pendingSteps.push(el);
} else {
flushSteps();
@@ -1387,6 +1387,19 @@
lastStepPhase = null;
}
+ /**
+ * Pick the icon for a DB-loaded step row. Persisted steps carry their
+ * phase, so use it directly — the content heuristic below can misfire
+ * on the composed observation detail (raw web text containing words
+ * like "error" or "fail" must not turn a successful result row red).
+ * Rows persisted before the phase column existed fall back to the
+ * content heuristic.
+ */
+ function getStepIconForRow(msg) {
+ if (msg.phase && STEP_ICONS[msg.phase]) return STEP_ICONS[msg.phase];
+ return getStepIconForContent(msg.content);
+ }
+
/**
* Infer step icon from message content (best-effort for DB-loaded steps).
*/
@@ -1649,13 +1662,23 @@
// 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)
+ ? 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
- addLiveStepMessage(STEP_ICONS[phase] || STEP_ICONS._default, message);
+ addLiveStepMessage(STEP_ICONS[phase] || STEP_ICONS._default, stepText);
lastStepPhase = phase;
} else {
- updateLastLiveStep(message);
+ updateLastLiveStep(stepText);
}
} else if (data.phase === 'tool_call') {
// Tool calls — each is a distinct user-meaningful event
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 e09dfff1e7..d90ebb9398 100644
--- a/src/local_deep_research/web/static/js/components/progress.js
+++ b/src/local_deep_research/web/static/js/components/progress.js
@@ -1239,8 +1239,15 @@
case 'observation': {
stepType = 'result';
label = '📋 RESULT';
- // Use content if available, otherwise message
- let resultText = data.content || data.message || '';
+ // Keep the "From {engine}" attribution line from the
+ // message and append the fuller tool output beneath it
+ // when the event carries one (LangGraph observation
+ // events attach up to 4000 chars in data.content for
+ // outputs longer than the message's one-line preview).
+ let resultText = data.message || data.content || '';
+ if (data.message && data.content) {
+ resultText = data.message + '\n' + data.content;
+ }
if (resultText.length > 800) {
resultText = resultText.substring(0, 800) + '...';
}
diff --git a/tests/js/components/chat-live-step-detail.test.js b/tests/js/components/chat-live-step-detail.test.js
new file mode 100644
index 0000000000..d41ae217b0
--- /dev/null
+++ b/tests/js/components/chat-live-step-detail.test.js
@@ -0,0 +1,299 @@
+/**
+ * Tests for the expandable observation detail in chat.js live steps.
+ *
+ * Observation progress events carry the (bounded) full tool output in
+ * `data.content` alongside the one-line `data.message`. The live step
+ * handler must append the detail beneath the message — mirroring what
+ * `_compose_chat_step_content` persists to chat_progress_steps on the
+ * backend, so the live accordion and a post-reload session render
+ * identically (symmetry invariant). Non-observation phases must NOT
+ * compose: `metadata["content"]` is reused there for large payloads
+ * (full synthesized answers) that don't belong in step rows.
+ *
+ * `handleProgressUpdate` is private to the chat IIFE, so we drive it the
+ * way production does: load a session whose messages response reports an
+ * in-progress research, capture the progress callback that chat.js hands
+ * to window.socket.subscribeToResearch, and invoke it with progress
+ * events.
+ */
+import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest';
+
+const SESSION_ID = 'sess-1';
+const RESEARCH_ID = 'research-1';
+
+function buildChatDom() {
+ // Static literal (no interpolation) so no-unsanitized/property is
+ // satisfied; SESSION_ID must match this meta content.
+ document.head.innerHTML = `
+ <meta name="chat-session-id" content="sess-1">
+ `;
+ document.body.innerHTML = `
+ <div id="chat-welcome"></div>
+ <textarea id="chat-input"></textarea>
+ <button id="send-btn"></button>
+ <div id="chat-title"></div>
+ <div id="chat-messages" role="log"></div>
+ <template id="thinking-template">
+ <div class="ldr-chat-message ldr-chat-message-assistant ldr-chat-message-thinking" role="status">
+ <div class="ldr-chat-message-avatar"><i class="fas fa-robot"></i></div>
+ <div class="ldr-chat-message-content">
+ <div class="ldr-chat-thinking-text" hidden></div>
+ <div class="ldr-chat-thinking-dots"><span></span><span></span><span></span></div>
+ </div>
+ </div>
+ </template>
+ <template id="message-template">
+ <div class="ldr-chat-message">
+ <div class="ldr-chat-message-avatar"><i class="fas fa-user"></i></div>
+ <div class="ldr-chat-message-content">
+ <div class="ldr-chat-message-text"></div>
+ <div class="ldr-chat-message-meta"><span class="ldr-chat-message-time"></span></div>
+ </div>
+ </div>
+ </template>
+ `;
+}
+
+const json = (payload) => ({
+ ok: true,
+ status: 200,
+ json: async () => payload,
+});
+
+const flush = async (n = 10) => {
+ for (let i = 0; i < n; i++) await Promise.resolve();
+};
+
+/** The step elements inside the live accordion. */
+function liveSteps() {
+ return document.querySelectorAll(
+ '.ldr-chat-steps-group[data-live="true"] .ldr-chat-message-step'
+ );
+}
+
+describe('chat.js — live step observation detail (data.content)', () => {
+ let progressCb;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ progressCb = null;
+ buildChatDom();
+
+ window.api = { getCsrfToken: () => '' };
+ window.ui = { renderMarkdown: (t) => t };
+ window.socket = {
+ subscribeToResearch: vi.fn((id, cb) => {
+ progressCb = cb;
+ }),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => ({
+ on: vi.fn(),
+ off: vi.fn(),
+ })),
+ };
+
+ // Session restore: one prior user message + an in-progress
+ // research, so loadSession() subscribes to progress events.
+ globalThis.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes(`/api/chat/sessions/${SESSION_ID}/messages`)) {
+ return json({
+ success: true,
+ messages: [
+ {
+ id: 'm1',
+ role: 'user',
+ message_type: 'chat',
+ content: 'hello',
+ created_at: '2026-07-11T00:00:00Z',
+ },
+ ],
+ has_more: false,
+ in_progress_research_id: RESEARCH_ID,
+ });
+ }
+ if (u.includes(`/api/chat/sessions/${SESSION_ID}`)) {
+ return json({
+ success: true,
+ session: { id: SESSION_ID, title: 'Test session' },
+ });
+ }
+ return json({ success: true, sessions: [] });
+ });
+
+ await import('@js/components/chat.js');
+ await flush();
+
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ RESEARCH_ID,
+ expect.any(Function)
+ );
+ expect(progressCb).toBeTypeOf('function');
+ });
+
+ afterEach(() => {
+ delete globalThis.fetch;
+ });
+
+ it('appends data.content beneath the message for observation steps', () => {
+ const message = '📄 From the web (SearXNG): [1] Some Title (http://a.com) Snip';
+ const detail = '[1] Some Title (http://a.com)\nThe full snippet body with much more text.';
+ progressCb({
+ research_id: RESEARCH_ID,
+ phase: 'observation',
+ message,
+ content: detail,
+ progress: 42,
+ });
+
+ const steps = liveSteps();
+ expect(steps.length).toBe(1);
+ const text = steps[0].querySelector('.ldr-chat-message-text').textContent;
+ expect(text).toBe(message + '\n\n' + detail);
+ });
+
+ it('keeps the bare message when an observation has no content', () => {
+ const message = '📄 From PubMed: no results';
+ progressCb({
+ research_id: RESEARCH_ID,
+ phase: 'observation',
+ message,
+ progress: 42,
+ });
+
+ const steps = liveSteps();
+ expect(steps.length).toBe(1);
+ expect(
+ steps[0].querySelector('.ldr-chat-message-text').textContent
+ ).toBe(message);
+ });
+
+ it('does NOT compose content for non-observation step phases', () => {
+ const message = 'Generating final answer…';
+ progressCb({
+ research_id: RESEARCH_ID,
+ phase: 'output_generation',
+ message,
+ content: 'the entire synthesized answer — must not land in the step',
+ progress: 90,
+ });
+
+ const steps = liveSteps();
+ expect(steps.length).toBe(1);
+ expect(
+ steps[0].querySelector('.ldr-chat-message-text').textContent
+ ).toBe(message);
+ });
+
+ it('keeps the thinking-bubble preview on the short message only', () => {
+ progressCb({
+ research_id: RESEARCH_ID,
+ phase: 'observation',
+ message: '📄 From arXiv: [2] Paper',
+ content: '[2] Paper (http://arxiv.org/x)\nAbstract text',
+ progress: 42,
+ });
+
+ const preview = document.querySelector('.ldr-chat-thinking-text');
+ expect(preview).not.toBeNull();
+ expect(preview.textContent).toBe('📄 From arXiv: [2] Paper');
+ expect(preview.textContent).not.toContain('Abstract text');
+ });
+});
+
+describe('chat.js — reloaded step icons use the persisted phase', () => {
+ /**
+ * Persisted step rows now carry composed observation detail — raw web
+ * text that can contain words like "failed". The reload icon must come
+ * from the row's `phase` field, not the content heuristic, so a
+ * successful result row never renders with the error icon.
+ */
+ function stepIcons() {
+ return [
+ ...document.querySelectorAll(
+ '.ldr-chat-steps-group .ldr-chat-message-step .ldr-chat-message-avatar i'
+ ),
+ ].map((i) => i.className);
+ }
+
+ beforeEach(async () => {
+ vi.resetModules();
+ buildChatDom();
+
+ window.api = { getCsrfToken: () => '' };
+ window.ui = { renderMarkdown: (t) => t };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => ({ on: vi.fn(), off: vi.fn() })),
+ };
+
+ // Completed session: no in-progress research, two persisted steps —
+ // one observation whose detail contains failure-y web text, one
+ // legacy row without a phase (pre-phase-column fallback).
+ globalThis.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes(`/api/chat/sessions/${SESSION_ID}/messages`)) {
+ return json({
+ success: true,
+ messages: [
+ {
+ id: 'm1',
+ role: 'user',
+ message_type: 'chat',
+ content: 'hello',
+ created_at: '2026-07-11T00:00:00Z',
+ },
+ {
+ id: 'step-1',
+ role: 'assistant',
+ message_type: 'step',
+ phase: 'observation',
+ content:
+ '📄 From PubMed: [1] Titration study\n\n'
+ + '[1] Titration study (http://p.com)\n'
+ + 'The first titration attempt failed; the '
+ + 'second failed titration was repeated.',
+ created_at: '2026-07-11T00:00:01Z',
+ },
+ {
+ id: 'step-2',
+ role: 'assistant',
+ message_type: 'step',
+ content: 'Starting research: "hello"',
+ created_at: '2026-07-11T00:00:02Z',
+ },
+ ],
+ has_more: false,
+ in_progress_research_id: null,
+ });
+ }
+ if (u.includes(`/api/chat/sessions/${SESSION_ID}`)) {
+ return json({
+ success: true,
+ session: { id: SESSION_ID, title: 'Test session' },
+ });
+ }
+ return json({ success: true, sessions: [] });
+ });
+
+ await import('@js/components/chat.js');
+ await flush();
+ });
+
+ afterEach(() => {
+ delete globalThis.fetch;
+ });
+
+ it('uses the phase icon for observation rows despite "failed" in the detail', () => {
+ const icons = stepIcons();
+ expect(icons.length).toBe(2);
+ expect(icons[0]).toContain('fa-eye'); // observation, NOT fa-circle-xmark
+ expect(icons[0]).not.toContain('fa-circle-xmark');
+ });
+
+ it('falls back to the content heuristic for rows without a phase', () => {
+ const icons = stepIcons();
+ expect(icons[1]).toContain('fa-play'); // "starting research" heuristic
+ });
+});
diff --git a/tests/js/components/progress-agent-thinking.test.js b/tests/js/components/progress-agent-thinking.test.js
index c7f1ecafef..86c5fc1ddb 100644
--- a/tests/js/components/progress-agent-thinking.test.js
+++ b/tests/js/components/progress-agent-thinking.test.js
@@ -88,3 +88,52 @@ describe('updateAgentThinking - tool_call rendering', () => {
expect(content).toBe('Using unknown');
});
});
+
+function renderObservation(data) {
+ progressComponent.updateAgentThinking({ phase: 'observation', ...data });
+ const step = document
+ .getElementById('agent-thinking-content')
+ .querySelector('.ldr-agent-step-content');
+ return step ? step.textContent : null;
+}
+
+describe('updateAgentThinking - observation rendering', () => {
+ it('keeps the "From {engine}" attribution and appends data.content beneath it', () => {
+ const content = renderObservation({
+ message: '📄 From the web (SearXNG): [1] Some Title (http://a.com) Snip',
+ content: '[1] Some Title (http://a.com)\nThe full snippet body.',
+ });
+
+ expect(content).toBe(
+ '📄 From the web (SearXNG): [1] Some Title (http://a.com) Snip\n'
+ + '[1] Some Title (http://a.com)\nThe full snippet body.'
+ );
+ });
+
+ it('shows the message alone when no content is attached (short outputs)', () => {
+ const content = renderObservation({
+ message: '📄 From PubMed: No results.',
+ });
+
+ expect(content).toBe('📄 From PubMed: No results.');
+ });
+
+ it('falls back to content when no message is present', () => {
+ const content = renderObservation({
+ content: 'raw tool output only',
+ });
+
+ expect(content).toBe('raw tool output only');
+ });
+
+ it('truncates the composed result to 800 chars', () => {
+ const content = renderObservation({
+ message: '📄 From arXiv: long',
+ content: 'z'.repeat(1000),
+ });
+
+ expect(content.length).toBe(803); // 800 + '...'
+ expect(content.endsWith('...')).toBe(true);
+ expect(content.startsWith('📄 From arXiv: long\n')).toBe(true);
+ });
+});
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index 69b1c03d83..35053db9bd 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -434,9 +434,45 @@ class TestToolCallProgressFormatting:
out = strategy._format_tool_call_progress(
self._tc("fetch_content", url=long_url), "the page"
)
- # 80 chars of URL inside the quoted target.
+ # 80 chars of URL + ellipsis marker inside the quoted target — the
+ # cut must be visible, not read as a complete URL.
quoted = out.split(chr(34))[1]
- assert len(quoted) == 80
+ assert quoted == long_url[:80] + "…"
+
+ def test_short_args_get_no_ellipsis(self):
+ strategy = self._make_strategy()
+ out = strategy._format_tool_call_progress(
+ self._tc("search_pubmed", query="short query"), "PubMed"
+ )
+ assert out == '🔍 Searching PubMed: "short query"'
+
+ def test_long_query_is_truncated_with_ellipsis(self):
+ strategy = self._make_strategy()
+ long_query = "q" * 120
+ out = strategy._format_tool_call_progress(
+ self._tc("search_pubmed", query=long_query), "PubMed"
+ )
+ assert out == f'🔍 Searching PubMed: "{"q" * 80}…"'
+
+ def test_subtopics_list_is_capped_per_item_not_globally(self):
+ """A realistic 3-subtopic call easily exceeds 80 chars joined; every
+ subtopic must stay visible (the collapsed step row ellipsizes via
+ CSS and expands on click) — only an individual overlong item gets
+ cut, with an ellipsis."""
+ strategy = self._make_strategy()
+ subtopics = [
+ "history of the transformer architecture in NLP",
+ "current benchmark results for long-context models",
+ "z" * 100,
+ ]
+ out = strategy._format_tool_call_progress(
+ self._tc("research_subtopic", subtopics=subtopics),
+ "subtopic researcher",
+ )
+ assert subtopics[0] in out
+ assert subtopics[1] in out
+ assert "z" * 80 + "…" in out
+ assert "z" * 81 not in out
def test_legacy_fetch_url_name_now_falls_through_to_search(self):
"""The legacy ``fetch_url`` name no longer matches the curated
@@ -500,6 +536,210 @@ class TestToolCallProgressFormatting:
assert out == '🔍 Searching arXiv: "transformers"'
+# ---------------------------------------------------------------------------
+# Observation progress events (message + expandable detail)
+# ---------------------------------------------------------------------------
+
+
+class TestObservationEvent:
+ """Pin ``LangGraphAgentStrategy._observation_event``: the one-line
+ message stays bounded for the log panel / current-task line, while
+ ``metadata["content"]`` carries the (capped) full tool output for the
+ click-to-expand chat step and the agent-thinking panel."""
+
+ def _make_strategy(self):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ LangGraphAgentStrategy,
+ )
+
+ return LangGraphAgentStrategy(
+ model=MagicMock(),
+ search=MagicMock(),
+ all_links_of_system=[],
+ settings_snapshot={"search.tool": {"value": "searxng"}},
+ )
+
+ def _msg(self, name="web_search", content=""):
+ from types import SimpleNamespace
+
+ return SimpleNamespace(name=name, content=content)
+
+ def test_message_is_flattened_150_char_preview(self):
+ strategy = self._make_strategy()
+ content = "line one\nline two " + "x" * 200
+ message, _ = strategy._observation_event(self._msg(content=content))
+
+ assert message.startswith("📄 From the web (SearXNG): ")
+ preview = message.split("📄 From the web (SearXNG): ", 1)[1]
+ assert len(preview) == 150
+ assert "\n" not in message
+ assert preview.startswith("line one line two ")
+
+ def test_metadata_carries_full_detail_with_newlines(self):
+ strategy = self._make_strategy()
+ content = "\n\n".join(
+ f"[{i}] Title {i} (http://a{i}.com)\nSnippet text for result {i}"
+ for i in range(1, 6)
+ )
+ assert len(content) > 150 # long enough that the preview truncates
+ message, metadata = strategy._observation_event(
+ self._msg(content=content)
+ )
+
+ assert metadata["phase"] == "observation"
+ assert metadata["tool"] == "web_search"
+ # Detail preserves the full formatted result including newlines —
+ # the expanded chat step renders it pre-wrap.
+ assert metadata["content"] == content
+
+ def test_short_output_attaches_no_detail(self):
+ """Output the preview already shows verbatim must not attach a
+ detail — the expanded step would just repeat the line
+ ("No results." twice)."""
+ strategy = self._make_strategy()
+ _, metadata = strategy._observation_event(
+ self._msg(content="No results.")
+ )
+
+ assert "content" not in metadata
+
+ def test_short_multiline_output_keeps_formatted_detail(self):
+ """A short output WITH newlines differs from the flattened
+ preview, so the detail (preserving the formatting) must still be
+ attached — length alone must not gate it."""
+ strategy = self._make_strategy()
+ content = "Title: Foo Bar\nURL: http://example.com\nSnippet: short"
+ assert len(content) <= 150
+ _, metadata = strategy._observation_event(self._msg(content=content))
+
+ assert metadata["content"] == content
+
+ def test_detail_attached_only_beyond_preview_length(self):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _OBSERVATION_PREVIEW_MAX_CHARS,
+ )
+
+ strategy = self._make_strategy()
+ at_limit = "y" * _OBSERVATION_PREVIEW_MAX_CHARS
+ over_limit = "y" * (_OBSERVATION_PREVIEW_MAX_CHARS + 1)
+ _, meta_at = strategy._observation_event(self._msg(content=at_limit))
+ _, meta_over = strategy._observation_event(
+ self._msg(content=over_limit)
+ )
+
+ assert "content" not in meta_at
+ assert meta_over["content"] == over_limit
+
+ def test_detail_is_capped_with_ellipsis(self):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _OBSERVATION_DETAIL_MAX_CHARS,
+ )
+
+ strategy = self._make_strategy()
+ content = "y" * (_OBSERVATION_DETAIL_MAX_CHARS + 500)
+ _, metadata = strategy._observation_event(self._msg(content=content))
+
+ assert len(metadata["content"]) == _OBSERVATION_DETAIL_MAX_CHARS + 2
+ assert metadata["content"].endswith(" …")
+
+ def test_detail_at_cap_is_not_marked_truncated(self):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _OBSERVATION_DETAIL_MAX_CHARS,
+ )
+
+ strategy = self._make_strategy()
+ content = "y" * _OBSERVATION_DETAIL_MAX_CHARS
+ _, metadata = strategy._observation_event(self._msg(content=content))
+
+ assert metadata["content"] == content
+
+
+# ---------------------------------------------------------------------------
+# Step heartbeat (full tool listing)
+# ---------------------------------------------------------------------------
+
+
+class TestHeartbeatMessage:
+ """Pin ``LangGraphAgentStrategy._heartbeat_message``: once sources are
+ gathered the heartbeat lists EVERY enabled tool by friendly name — the
+ old 3-name sample with "+N more" hid most engines."""
+
+ def _make_strategy(self, links=None):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ LangGraphAgentStrategy,
+ )
+
+ return LangGraphAgentStrategy(
+ model=MagicMock(),
+ search=MagicMock(),
+ all_links_of_system=links if links is not None else [],
+ settings_snapshot={"search.tool": {"value": "searxng"}},
+ )
+
+ def test_zero_sources_reports_planning_with_tool_count(self):
+ strategy = self._make_strategy()
+ strategy._tool_names = ["web_search", "search_arxiv"]
+
+ out = strategy._heartbeat_message(1)
+
+ assert (
+ out == "Step 1 · planning approach with 2 research tools available…"
+ )
+
+ def test_lists_all_tools_without_more_suffix(self):
+ strategy = self._make_strategy(links=[{"link": "http://a.com"}] * 5)
+ strategy._tool_names = [
+ "web_search",
+ "search_arxiv",
+ "search_pubmed",
+ "search_wikipedia",
+ "search_github",
+ "search_semantic_scholar",
+ ]
+
+ out = strategy._heartbeat_message(3)
+
+ assert out.startswith(
+ "Step 3 · 5 sources gathered · selecting next action from "
+ )
+ for name in (
+ "the web (SearXNG)",
+ "arXiv",
+ "PubMed",
+ "Wikipedia",
+ "GitHub",
+ "Semantic Scholar",
+ ):
+ assert name in out
+ assert "more" not in out
+
+ def test_non_search_tools_use_list_friendly_labels(self):
+ """`fetch_content` ("the page") and `research_subtopic`
+ ("subtopic researcher") read wrong in a comma list — the heartbeat
+ must use the list-friendly overrides."""
+ strategy = self._make_strategy(links=[{"link": "http://a.com"}])
+ strategy._tool_names = [
+ "web_search",
+ "fetch_content",
+ "research_subtopic",
+ ]
+
+ out = strategy._heartbeat_message(2)
+
+ assert "page fetching" in out
+ assert "subtopic research" in out
+ assert "the page" not in out
+ assert "subtopic researcher" not in out
+
+ def test_single_source_uses_singular(self):
+ strategy = self._make_strategy(links=[{"link": "http://a.com"}])
+ strategy._tool_names = ["web_search"]
+
+ out = strategy._heartbeat_message(2)
+
+ assert "1 source gathered" in out
+
+
# ---------------------------------------------------------------------------
# Citation offset for detailed report mode
# ---------------------------------------------------------------------------
diff --git a/tests/web/services/test_chat_step_decision.py b/tests/web/services/test_chat_step_decision.py
index 188d01ad52..39ce8e169c 100644
--- a/tests/web/services/test_chat_step_decision.py
+++ b/tests/web/services/test_chat_step_decision.py
@@ -16,6 +16,7 @@ import pytest
from src.local_deep_research.web.services.research_service import (
_chat_step_decision,
+ _compose_chat_step_content,
_STEP_PHASES,
)
@@ -139,6 +140,46 @@ class TestRepeatPhaseDedup:
assert (persist, suppress) == (False, False)
+class TestComposeChatStepContent:
+ """``_compose_chat_step_content`` appends the observation detail from
+ ``metadata["content"]`` beneath the one-line message — and ONLY for
+ observation events. Other phases reuse metadata["content"] for large
+ payloads (full synthesized answers) that must not be duplicated into
+ step rows. The same composition happens client-side for live steps
+ (chat.js handleProgressUpdate), preserving the symmetry invariant."""
+
+ def test_observation_with_detail_appends_it(self):
+ out = _compose_chat_step_content(
+ "📄 From the web (SearXNG): [1] Title…",
+ "observation",
+ {"content": "[1] Title (http://a.com)\nFull snippet"},
+ )
+ assert out == (
+ "📄 From the web (SearXNG): [1] Title…"
+ "\n\n[1] Title (http://a.com)\nFull snippet"
+ )
+
+ def test_observation_without_detail_keeps_message(self):
+ out = _compose_chat_step_content(
+ "📄 From PubMed: no results", "observation", {}
+ )
+ assert out == "📄 From PubMed: no results"
+
+ def test_non_observation_phase_ignores_content(self):
+ out = _compose_chat_step_content(
+ "Generating final answer…",
+ "output_generation",
+ {"content": "the entire synthesized answer"},
+ )
+ assert out == "Generating final answer…"
+
+ def test_empty_detail_keeps_message(self):
+ out = _compose_chat_step_content(
+ "📄 From arXiv: …", "observation", {"content": ""}
+ )
+ assert out == "📄 From arXiv: …"
+
+
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
diff --git a/tests/web/services/test_research_service_progress_integration.py b/tests/web/services/test_research_service_progress_integration.py
index a7f0cebc53..45ff7405e0 100644
--- a/tests/web/services/test_research_service_progress_integration.py
+++ b/tests/web/services/test_research_service_progress_integration.py
@@ -62,13 +62,20 @@ def _noop_db_session(*_, **__):
@contextmanager
-def captured_progress_callback(mode, flask_app):
+def captured_progress_callback(mode, flask_app, run_kwargs=None, extras=None):
"""Yield (callback, progress_state, update_calls) with patches active.
progress_state[0] is the value globals.update_progress_and_check_active
would have stored. update_calls is the list of (rid, new, stored) for
every invocation, so tests can assert on order and rejection of lower
values.
+
+ ``run_kwargs`` overrides/extends the ``run_research_process`` call
+ (e.g. ``chat_session_id`` to exercise the chat-step path, or a unique
+ ``research_id`` to isolate the module-global emit-throttle state).
+ ``extras``, when given a dict, is populated with the ``socketio``
+ service mock and the patched ``chat_service_cls`` so tests can assert
+ on emits and persisted steps.
"""
from local_deep_research.exceptions import ResearchTerminatedException
from local_deep_research.web.services.research_service import (
@@ -95,6 +102,12 @@ def captured_progress_callback(mode, flask_app):
update_calls.append((rid, new_progress, progress_state[0]))
return (progress_state[0], True)
+ socketio_service = Mock()
+ chat_service_cls = MagicMock()
+ if extras is not None:
+ extras["socketio"] = socketio_service
+ extras["chat_service_cls"] = chat_service_cls
+
with flask_app.app_context():
with (
patch(
@@ -132,14 +145,20 @@ def captured_progress_callback(mode, flask_app):
patch("local_deep_research.settings.logger.log_settings"),
patch(
"local_deep_research.web.services.research_service.SocketIOService",
- return_value=Mock(),
+ return_value=socketio_service,
+ ),
+ # The chat-step persist path imports ChatService at function
+ # scope inside the callback — patch the source module.
+ patch(
+ "local_deep_research.chat.service.ChatService",
+ chat_service_cls,
),
patch("local_deep_research.web.queue.processor_v2.queue_processor"),
patch(
"local_deep_research.web.services.research_service.handle_termination"
),
):
- run_research_process(
+ call_kwargs = dict(
research_id=1,
query="test query",
mode=mode,
@@ -150,6 +169,9 @@ def captured_progress_callback(mode, flask_app):
# wiring under test runs.
settings_snapshot={"search.tool": "searxng"},
)
+ if run_kwargs:
+ call_kwargs.update(run_kwargs)
+ run_research_process(**call_kwargs)
yield captured.get("callback"), progress_state, update_calls
@@ -262,3 +284,109 @@ class TestRunResearchProcessProgressCallbackIntegration:
cb("sub-search complete", None, {"phase": "search_complete"})
assert progress_state[0] == baseline
+
+
+class TestChatStepEmitBypassesThrottle:
+ """Persisted chat steps must always emit (PR #5051).
+
+ The 200ms socket-emit throttle used to drop back-to-back observation
+ events (the agent issuing several tool calls in one turn) from the
+ live stream even though every one was persisted as a chat step — the
+ live UI showed fewer steps than a session reload reconstructed,
+ violating the symmetry invariant in the live direction. The chat-step
+ decision now runs before the throttle gate and forces the emit for
+ any event that persists a step.
+ """
+
+ def _progress_emits(self, socketio):
+ return [
+ c
+ for c in socketio.emit_to_subscribers.call_args_list
+ if c.args[0] == "progress"
+ ]
+
+ def test_back_to_back_observations_all_emit_and_persist(self, flask_app):
+ extras = {}
+ with captured_progress_callback(
+ "quick",
+ flask_app,
+ # Unique research_id isolates the module-global throttle state.
+ run_kwargs={
+ "research_id": 987654,
+ "chat_session_id": "sess-throttle-test",
+ },
+ extras=extras,
+ ) as (cb, _, __):
+ socketio = extras["socketio"]
+ add_step = extras["chat_service_cls"].return_value.add_progress_step
+ socketio.emit_to_subscribers.reset_mock()
+ add_step.reset_mock()
+
+ detail_1 = "x" * 200
+ detail_2 = "y" * 200
+ cb(
+ "📄 From the web (SearXNG): first",
+ 42,
+ {
+ "phase": "observation",
+ "tool": "web_search",
+ "content": detail_1,
+ },
+ )
+ # Fired microseconds later — inside the 200ms throttle window.
+ cb(
+ "📄 From the web (SearXNG): second",
+ 43,
+ {
+ "phase": "observation",
+ "tool": "web_search",
+ "content": detail_2,
+ },
+ )
+
+ emits = self._progress_emits(socketio)
+ assert len(emits) == 2, (
+ "second back-to-back observation was throttled off the "
+ "live stream despite being persisted as a chat step"
+ )
+ # The detail rides along on the wire for the live step…
+ assert emits[1].args[2]["content"] == detail_2
+ # …and both events persisted the composed message + detail.
+ assert add_step.call_count == 2
+ assert add_step.call_args_list[1].kwargs["content"] == (
+ "📄 From the web (SearXNG): second\n\n" + detail_2
+ )
+
+ def test_non_persisted_repeat_phase_still_suppressed(self, flask_app):
+ """The forced emit is persist-gated: a deduped repeat step phase
+ (persist=False, non-final) must still be suppressed even when the
+ throttle would let it through."""
+ import local_deep_research.web.services.research_service as rs
+
+ extras = {}
+ with captured_progress_callback(
+ "quick",
+ flask_app,
+ run_kwargs={
+ "research_id": 987655,
+ "chat_session_id": "sess-suppress-test",
+ },
+ extras=extras,
+ ) as (cb, _, __):
+ socketio = extras["socketio"]
+ add_step = extras["chat_service_cls"].return_value.add_progress_step
+ socketio.emit_to_subscribers.reset_mock()
+ add_step.reset_mock()
+
+ # Disable the throttle so suppression is the ONLY thing that
+ # can drop the second emit — otherwise the throttle window
+ # would mask a broken suppress path.
+ with patch.object(rs, "_EMIT_THROTTLE_SECONDS", 0.0):
+ cb("Searching the web…", 20, {"phase": "search"})
+ cb("Searching the web again…", 21, {"phase": "search"})
+
+ assert len(self._progress_emits(socketio)) == 1, (
+ "deduped repeat 'search' step leaked to the live stream — "
+ "reload would not reconstruct it (symmetry violation)"
+ )
+ assert add_step.call_count == 1