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.

refactor(chat): remove dead/inert context code + orphaned max_context_messages setting (#4350)

LearningCircuit0dc17e32aaaf
diff --git a/changelog.d/+chat-remove-dead-context-code.misc.md b/changelog.d/+chat-remove-dead-context-code.misc.md
new file mode 100644
index 0000000000..0255a2c78e
--- /dev/null
+++ b/changelog.d/+chat-remove-dead-context-code.misc.md
@@ -0,0 +1 @@
+Removed dead and inert code from Chat Mode's context manager that shipped without a consumer: the unused ``build_prompt_context()`` and ``_get_recent_messages()`` helpers, the ``conversation_history`` and ``accumulated_sources`` keys in the research-context dict (nothing downstream read them), and the cross-turn source-count tracking (``_extract_sources_from_history``, the ``source_count`` field, and ``update_accumulated_context``'s ``source_count_delta`` parameter) — which never functioned because the producer was never called with sources. The ``chat.max_context_messages`` setting is removed with it, since it only fed the now-deleted recent-message inclusion path. ``chat.max_findings_to_include`` (which still controls how many prior findings carry into a follow-up) is unchanged.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 51a2f9478a..4ae02e94db 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -97,7 +97,6 @@ They are not available in the Web UI because they are needed to start the applic
| `benchmark.evaluation.temperature` | `LDR_BENCHMARK_EVALUATION_TEMPERATURE` | `0` | Sampling temperature for the benchmark judge model (0.0-1.0). Use 0 for deterministic, reproducible grading results. Higher values introduce randomness in evaluation scores. | APP |
| `chat.followup_context_mode` | `LDR_CHAT_FOLLOWUP_CONTEXT_MODE` | `summary` | What prior conversation context a follow-up research turn receives as its 'previous findings'. 'Focused summary' uses the LLM to summarize the whole conversation toward the new question (one extra LLM call per follow-up); 'Raw recent findings' reuses recent answers truncated; 'Full transcript' sends the entire conversation; 'None' sends no prior findings. | CHAT |
| `chat.llm_title_generation` | `LDR_CHAT_LLM_TITLE_GENERATION` | `false` | Use LLM to generate descriptive chat session titles instead of simple query truncation. When disabled, titles are the first 100 characters of the query. | CHAT |
-| `chat.max_context_messages` | `LDR_CHAT_MAX_CONTEXT_MESSAGES` | `10` | Maximum number of recent messages to include in chat context when building research queries. Higher values provide more conversation history but increase token usage. | CHAT |
| `chat.max_findings_to_include` | `LDR_CHAT_MAX_FINDINGS_TO_INCLUDE` | `5` | Maximum number of recent research findings to include in chat context. Higher values provide more background but increase token usage. | CHAT |
| `chat.title_llm_timeout_seconds` | `LDR_CHAT_TITLE_LLM_TIMEOUT_SECONDS` | `30` | Hard wall-clock timeout (seconds) for the LLM call that generates a chat session title. Past this, the request thread falls back to truncation so a slow LLM endpoint cannot block title generation indefinitely. | CHAT |
| `document_scheduler.download_pdfs` | `LDR_DOCUMENT_SCHEDULER_DOWNLOAD_PDFS` | `false` | Automatically download PDF files during scheduled document processing. Files will be stored on disk (requires storage space). WARNING: Downloaded files are stored unencrypted on disk. | APP |
diff --git a/docs/faq.md b/docs/faq.md
index 1c2dd25f22..20504f28c4 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -60,7 +60,7 @@ For details, see [Chat Mode in features.md](features.md#chat-mode).
### Does Chat Mode use the same settings as regular research mode?
-Yes — same LLM and search engines. But chat always runs in "quick" mode (1 iteration). Four chat-specific settings tune context depth and title generation: in Settings, on the **All Settings** tab, click the **Chat** section header to expand it. There you'll find `chat.max_context_messages`, `chat.max_findings_to_include`, `chat.llm_title_generation`, and `chat.title_llm_timeout_seconds` (hard wall-clock timeout for the title-generation LLM call so a slow endpoint can't block title generation).
+Yes — same LLM and search engines. But chat always runs in "quick" mode (1 iteration). Three chat-specific settings tune context depth and title generation: in Settings, on the **All Settings** tab, click the **Chat** section header to expand it. There you'll find `chat.max_findings_to_include`, `chat.llm_title_generation`, and `chat.title_llm_timeout_seconds` (hard wall-clock timeout for the title-generation LLM call so a slow endpoint can't block title generation).
### Can I save or export conversations from Chat Mode?
diff --git a/src/local_deep_research/chat/context.py b/src/local_deep_research/chat/context.py
index 712d306d1c..020268038e 100644
--- a/src/local_deep_research/chat/context.py
+++ b/src/local_deep_research/chat/context.py
@@ -24,7 +24,6 @@ class ChatContextManager:
Different from follow-up: accumulates from MULTIPLE previous turns.
"""
- MAX_CONTEXT_MESSAGES = 10 # Recent messages to include fully
MAX_FINDINGS_TO_INCLUDE = 5 # Recent findings to include
# Limits for the query-focused conversation summary that becomes the
@@ -75,11 +74,6 @@ class ChatContextManager:
# Note: settings_snapshot is the 4th keyword arg; passing it positionally
# would bind it to the unused `username` param, silently using defaults.
if settings_snapshot:
- self.MAX_CONTEXT_MESSAGES = get_setting_from_snapshot(
- "chat.max_context_messages",
- self.MAX_CONTEXT_MESSAGES,
- settings_snapshot=settings_snapshot,
- )
self.MAX_FINDINGS_TO_INCLUDE = get_setting_from_snapshot(
"chat.max_findings_to_include",
self.MAX_FINDINGS_TO_INCLUDE,
@@ -98,10 +92,9 @@ class ChatContextManager:
Returns dict with:
- session_id: Current session
- - conversation_history: Recent messages
+ - original_query: The session's first user message
- accumulated_findings / past_findings: Prior work for the follow-up
(query-focused summary on follow-ups; empty on the first turn)
- - accumulated_sources: Deduplicated sources
- key_entities: Important entities mentioned
- topics: Topics discussed
- is_multi_turn: Whether this is a follow-up
@@ -129,10 +122,8 @@ class ChatContextManager:
return {
"session_id": self.session_id,
"original_query": original_query,
- "conversation_history": self._get_recent_messages(),
"accumulated_findings": findings,
"past_findings": findings, # Research engine expects this key
- "accumulated_sources": self._extract_sources_from_history(),
"key_entities": self._get_key_entities(),
"topics": self._get_topics(),
"is_multi_turn": is_multi_turn,
@@ -251,70 +242,6 @@ class ChatContextManager:
max_chars=self.CONTEXT_SUMMARY_MAX_CHARS,
).summarize(transcript)
- def build_prompt_context(self) -> str:
- """
- Build a text context string suitable for including in prompts.
-
- Returns a formatted string with conversation context.
- """
- if not self.messages:
- return ""
-
- parts = []
-
- # Add accumulated summary if available
- summary = self.accumulated_context.get("summary", "")
- if summary:
- parts.append("Previous conversation summary:")
- parts.append(summary[:2000]) # Limit summary length
- parts.append("")
-
- # Add key entities and topics
- entities = self.accumulated_context.get("key_entities", [])
- if entities:
- parts.append(f"Key entities discussed: {', '.join(entities[:10])}")
-
- topics = self.accumulated_context.get("topics", [])
- if topics:
- parts.append(f"Topics covered: {', '.join(topics[:10])}")
-
- if entities or topics:
- parts.append("")
-
- # Add recent conversation
- recent = self._get_recent_messages()
- if recent:
- parts.append("Recent conversation:")
- for msg in recent:
- role = (msg.get("role") or "unknown").capitalize()
- content = msg.get("content") or ""
- # Truncate long messages
- if len(content) > 500:
- content = content[:500] + "..."
- parts.append(f"{role}: {content}")
-
- return "\n".join(parts)
-
- def _get_recent_messages(self) -> List[Dict[str, Any]]:
- """
- Get recent messages within context window.
-
- Returns messages with limited content length.
- """
- recent = self.messages[-self.MAX_CONTEXT_MESSAGES :]
-
- # Return simplified message dicts
- return [
- {
- "role": msg.get("role") or "unknown",
- "content": msg.get("content") or "",
- "message_type": msg.get("message_type"),
- "research_id": msg.get("research_id"),
- }
- for msg in recent
- if isinstance(msg, dict)
- ]
-
def _extract_findings_from_history(self) -> str:
"""
Extract key findings from assistant messages with research.
@@ -339,29 +266,6 @@ class ChatContextManager:
recent_findings = findings[-self.MAX_FINDINGS_TO_INCLUDE :]
return "\n\n---\n\n".join(recent_findings)
- def _extract_sources_from_history(self) -> List[Dict[str, Any]]:
- """
- Collect a sources-summary from accumulated context if available.
-
- Per-source metadata (url, title, snippet) is NOT persisted on
- ChatMessage rows in the current schema, so the chat layer cannot
- reconstruct individual source entries from message history. What
- IS tracked across turns is the running source_count maintained
- by ChatService.update_accumulated_context().
-
- Returns either an empty list (no sources seen yet) or a
- single-element list containing one summary dict of shape
- ``[{"count": <int>}]``. Callers must NOT iterate this list as
- if it were a list of source records — it is a count summary
- wrapped in a list for consumer-shape stability.
- """
- # Sources are tracked in accumulated_context by update_accumulated_context()
- # rather than per-message metadata (which is not stored in ChatMessage model)
- source_count = self.accumulated_context.get("source_count", 0)
- if source_count > 0:
- return [{"count": source_count}]
- return []
-
def _get_key_entities(self) -> List[str]:
"""Get key entities from accumulated context."""
entities: List[str] = self.accumulated_context.get("key_entities", [])
@@ -372,26 +276,20 @@ class ChatContextManager:
topics: List[str] = self.accumulated_context.get("topics", [])
return topics[:10]
- def extract_context_updates(
- self,
- new_content: str,
- new_sources: Optional[List[Dict[str, Any]]] = None,
- ) -> Dict[str, Any]:
+ def extract_context_updates(self, new_content: str) -> Dict[str, Any]:
"""
- Extract context updates from new research response.
+ Extract context updates from a new research response.
Args:
new_content: New assistant response content
- new_sources: New sources from research
Returns:
- Dict with entities, topics, summary update, source count
+ Dict with entity, topic, and summary updates.
"""
return {
"new_entities": [], # Could be enhanced with NLP entity extraction
"new_topics": [], # Could be enhanced with NLP topic modeling
"summary_addition": self._create_summary(new_content),
- "source_count_delta": len(new_sources) if new_sources else 0,
}
def _create_summary(self, content: str) -> str:
diff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.py
index c647f3a5f3..5314a9db37 100644
--- a/src/local_deep_research/chat/service.py
+++ b/src/local_deep_research/chat/service.py
@@ -179,7 +179,6 @@ class ChatService:
"key_entities": [],
"topics": [],
"summary": "",
- "source_count": 0,
},
message_count=0,
)
@@ -1213,7 +1212,6 @@ class ChatService:
new_entities: Optional[List[str]] = None,
new_topics: Optional[List[str]] = None,
summary_addition: Optional[str] = None,
- source_count_delta: int = 0,
) -> bool:
"""
Update the accumulated context for a session.
@@ -1223,7 +1221,6 @@ class ChatService:
new_entities: New entities to add
new_topics: New topics to add
summary_addition: Text to append to summary
- source_count_delta: Number of sources to add to count
Returns:
True if updated successfully
@@ -1272,12 +1269,6 @@ class ChatService:
)
ctx["summary"] = new_summary[-8000:] # Keep last 8000 chars
- # Update source count
- if source_count_delta:
- ctx["source_count"] = (
- ctx.get("source_count", 0) + source_count_delta
- )
-
session.accumulated_context = ctx
db.commit()
return True
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 8f9409f32a..31e57cf481 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -371,20 +371,6 @@
"value": false,
"visible": true
},
- "chat.max_context_messages": {
- "category": "chat",
- "description": "Maximum number of recent messages to include in chat context when building research queries. Higher values provide more conversation history but increase token usage.",
- "editable": true,
- "max_value": 50,
- "min_value": 1,
- "name": "Max Context Messages",
- "options": null,
- "step": 1,
- "type": "CHAT",
- "ui_element": "number",
- "value": 10,
- "visible": true
- },
"chat.max_findings_to_include": {
"category": "chat",
"description": "Maximum number of recent research findings to include in chat context. Higher values provide more background but increase token usage.",
diff --git a/tests/chat/conftest.py b/tests/chat/conftest.py
index 3d4759dfd8..e942f8640a 100644
--- a/tests/chat/conftest.py
+++ b/tests/chat/conftest.py
@@ -224,7 +224,6 @@ def sample_accumulated_context():
],
"topics": ["physics", "computing", "cryptography"],
"summary": "Discussion about quantum computing fundamentals and applications.",
- "source_count": 5,
}
@@ -242,47 +241,6 @@ def mock_chat_session():
return session
-def mock_chat_message():
- """Create a mock ChatMessage object."""
- message = MagicMock()
- message.id = "msg-test-456"
- message.session_id = "session-test-123"
- message.role = "user"
- message.content = "What is quantum computing?"
- message.message_type = "query"
- message.research_id = None
- message.sequence_number = 1
- message.created_at = datetime(2024, 1, 15, 10, 0, 0)
- return message
-
-
-def sample_research_findings():
- """Sample research findings for testing context extraction."""
- return [
- {
- "finding": "Quantum computers use qubits instead of classical bits.",
- "sources": [
- {
- "title": "Quantum Computing 101",
- "url": "https://example.com/qc101",
- },
- {"title": "IBM Quantum", "url": "https://ibm.com/quantum"},
- ],
- },
- {
- "finding": "Superposition allows qubits to be in multiple states.",
- "sources": [
- {
- "title": "Physics Today",
- "url": "https://physicstoday.org/quantum",
- },
- ],
- },
- ]
-
-
@pytest.fixture
def mock_settings_manager():
"""Mock the SettingsManager."""
@@ -307,19 +265,6 @@ def long_query_text():
)
-def sample_message_with_long_content():
- """A message with content longer than 500 characters for truncation tests."""
- return {
- "id": "msg-long-001",
- "role": "assistant",
- "content": "A" * 600, # 600 character content
- "message_type": "response",
- "research_id": "research-long-123",
- "created_at": datetime(2024, 1, 15, 10, 0, 0),
- }
-
-
@pytest.fixture
def many_messages():
"""Generate more than 10 messages for limit testing."""
@@ -338,17 +283,6 @@ def many_messages():
return messages
-def accumulated_context_with_many_entities():
- """Accumulated context with more than 50 entities for limit testing."""
- return {
- "key_entities": [f"entity_{i}" for i in range(60)],
- "topics": [f"topic_{i}" for i in range(25)],
- "summary": "A" * 9000, # 9000 character summary
- "source_count": 100,
- }
-
-
# =============================================================================
# Security Test Fixtures
# =============================================================================
diff --git a/tests/chat/test_chat_accumulated_context.py b/tests/chat/test_chat_accumulated_context.py
index 1c82b34878..e95d2e8062 100644
--- a/tests/chat/test_chat_accumulated_context.py
+++ b/tests/chat/test_chat_accumulated_context.py
@@ -45,7 +45,6 @@ class TestAccumulatedContextStructure:
"key_entities": ["entity1", "entity2"],
"topics": ["topic1"],
"summary": "Previous summary",
- "source_count": 5,
}
manager = ChatContextManager("test-session", messages, accumulated)
@@ -96,26 +95,12 @@ class TestContextMerging:
manager = ChatContextManager("test-session", [], accumulated)
# Get updates with overlapping and new entities
- updates = manager.extract_context_updates("Content about entity1", [])
+ updates = manager.extract_context_updates("Content about entity1")
# new_entities would normally contain extracted entities;
# verify the structure is present
assert "new_entities" in updates
- def test_source_count_accumulates(self):
- """Test that source counts accumulate correctly."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager("test-session", [], {"source_count": 5})
-
- updates1 = manager.extract_context_updates("Content 1", [{"url": "u1"}])
- updates2 = manager.extract_context_updates(
- "Content 2", [{"url": "u2"}, {"url": "u3"}]
- )
-
- assert updates1["source_count_delta"] == 1
- assert updates2["source_count_delta"] == 2
-
class TestContextSummary:
"""Tests for context summary handling."""
@@ -274,10 +259,11 @@ class TestEdgeCases:
}
manager = ChatContextManager("test", [], accumulated)
- prompt = manager.build_prompt_context()
+ context = manager.build_research_context()
- # Should handle without crashing
- assert isinstance(prompt, str)
+ # Should handle without crashing and preserve entities/topics
+ assert "<script>" in context["key_entities"]
+ assert "C++ programming" in context["topics"]
def test_unicode_in_context(self):
"""Test handling of unicode in context."""
@@ -298,8 +284,7 @@ class TestEdgeCases:
manager = ChatContextManager("test", messages, accumulated)
context = manager.build_research_context()
- prompt = manager.build_prompt_context()
# Should handle unicode
assert "日本語" in context["key_entities"]
- assert isinstance(prompt, str)
+ assert "한국어" in context["topics"]
diff --git a/tests/chat/test_chat_boundaries.py b/tests/chat/test_chat_boundaries.py
index c5e7009961..10c33b2d03 100644
--- a/tests/chat/test_chat_boundaries.py
+++ b/tests/chat/test_chat_boundaries.py
@@ -80,7 +80,6 @@ class TestContextBoundaries:
"key_entities": [f"existing_{i}" for i in range(40)],
"topics": [],
"summary": "",
- "source_count": 0,
}
@contextmanager
@@ -116,7 +115,6 @@ class TestContextBoundaries:
"key_entities": [],
"topics": [f"existing_topic_{i}" for i in range(15)],
"summary": "",
- "source_count": 0,
}
@contextmanager
@@ -152,7 +150,6 @@ class TestContextBoundaries:
"key_entities": [],
"topics": [],
"summary": "A" * 7000, # Already 7000 chars
- "source_count": 0,
}
@contextmanager
@@ -252,34 +249,6 @@ class TestSessionBoundaries:
class TestContextManagerBoundaries:
"""Tests for ChatContextManager boundaries."""
- def test_recent_messages_limited_to_10(self):
- """Test that recent messages are limited to MAX_CONTEXT_MESSAGES (10)."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- # Create 15 messages
- messages = [
- {
- "id": f"msg-{i}",
- "role": "user" if i % 2 == 0 else "assistant",
- "content": f"Message {i}",
- "message_type": "query" if i % 2 == 0 else "response",
- }
- for i in range(15)
- ]
-
- manager = ChatContextManager(
- session_id="test-session",
- messages=messages,
- accumulated_context={},
- )
-
- recent = manager._get_recent_messages()
-
- # Should be limited to 10
- assert len(recent) <= 10
- # Should be the most recent 10
- assert recent[0]["content"] == "Message 5" # First of last 10
-
def test_findings_limited_to_5(self):
"""Test that findings are limited to MAX_FINDINGS_TO_INCLUDE (5)."""
from src.local_deep_research.chat.context import ChatContextManager
@@ -309,50 +278,6 @@ class TestContextManagerBoundaries:
finding_count = findings.count("Finding")
assert finding_count <= 5
- def test_prompt_context_summary_truncated_to_2000(self):
- """Test that summary in prompt context is truncated to 2000 chars."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- long_summary = "X" * 3000
-
- manager = ChatContextManager(
- session_id="test-session",
- messages=[{"role": "user", "content": "test"}],
- accumulated_context={
- "key_entities": [],
- "topics": [],
- "summary": long_summary,
- "source_count": 0,
- },
- )
-
- context = manager.build_prompt_context()
-
- # The full 3000-char summary should not be present
- assert long_summary not in context
- # But some of the summary should be (truncated)
- assert "X" in context
-
- def test_message_content_truncated_to_500_in_prompt(self):
- """Test that long message content is truncated to 500 chars."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- long_content = "Y" * 700
-
- manager = ChatContextManager(
- session_id="test-session",
- messages=[{"role": "user", "content": long_content}],
- accumulated_context={},
- )
-
- context = manager.build_prompt_context()
-
- # The full 700-char content should not be present
- assert long_content not in context
- # But truncated version should be
- assert "Y" in context
- assert "..." in context
-
def test_create_summary_truncates_long_paragraphs_to_300(self):
"""Test that _create_summary truncates paragraphs to 300 chars."""
from src.local_deep_research.chat.context import ChatContextManager
@@ -375,40 +300,6 @@ class TestContextManagerBoundaries:
class TestEdgeCases:
"""Tests for various edge cases."""
- def test_source_count_accumulates_correctly(self):
- """Test that source count accumulates across updates."""
- from src.local_deep_research.chat.service import ChatService
-
- mock_session_obj = MagicMock()
- mock_session_obj.id = "test-session"
- mock_session_obj.accumulated_context = {
- "key_entities": [],
- "topics": [],
- "summary": "",
- "source_count": 10,
- }
-
- @contextmanager
- def mock_get_user_db_session(username, password=None):
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.with_for_update.return_value.first.return_value = mock_session_obj
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_session_obj
- mock_session.commit = MagicMock()
- yield mock_session
-
- with patch(
- "src.local_deep_research.chat.service.get_user_db_session",
- mock_get_user_db_session,
- ):
- service = ChatService(username="testuser")
- service.update_accumulated_context(
- "test-session",
- source_count_delta=5,
- )
-
- # Source count should be accumulated
- assert mock_session_obj.accumulated_context["source_count"] == 15
-
def test_entity_deduplication(self):
"""Test that duplicate entities are deduplicated."""
from src.local_deep_research.chat.service import ChatService
@@ -419,7 +310,6 @@ class TestEdgeCases:
"key_entities": ["quantum", "computing"],
"topics": [],
"summary": "",
- "source_count": 0,
}
@contextmanager
diff --git a/tests/chat/test_chat_concurrency.py b/tests/chat/test_chat_concurrency.py
index 435d6d1d56..dfd1621e61 100644
--- a/tests/chat/test_chat_concurrency.py
+++ b/tests/chat/test_chat_concurrency.py
@@ -277,7 +277,6 @@ class TestChatConcurrency:
"key_entities": [],
"topics": [],
"summary": "",
- "source_count": 0,
}
lock = threading.Lock()
@@ -407,7 +406,6 @@ class TestAddMessageSequenceRace:
"key_entities": [],
"topics": [],
"summary": "",
- "source_count": 0,
},
created_at=datetime.now(UTC),
message_count=0,
diff --git a/tests/chat/test_chat_context_advanced.py b/tests/chat/test_chat_context_advanced.py
index b35ef7fb93..01a7795aa5 100644
--- a/tests/chat/test_chat_context_advanced.py
+++ b/tests/chat/test_chat_context_advanced.py
@@ -7,46 +7,6 @@ Tests context window limits, summarization, and context building.
from src.local_deep_research.chat.context import ChatContextManager
-class TestContextWindowLimits:
- """Tests for context window size limits."""
-
- def test_max_context_messages_enforced(self):
- """Test that only MAX_CONTEXT_MESSAGES are included."""
- # Create more messages than the limit
- messages = [
- {"role": "user", "content": f"Message {i}", "message_type": "query"}
- for i in range(20)
- ]
-
- manager = ChatContextManager("test-session", messages, {})
- recent = manager._get_recent_messages()
-
- # Should only have the last MAX_CONTEXT_MESSAGES
- assert len(recent) == ChatContextManager.MAX_CONTEXT_MESSAGES
-
- def test_recent_messages_are_most_recent(self):
- """Test that the most recent messages are kept."""
- messages = [
- {"role": "user", "content": f"Message {i}", "message_type": "query"}
- for i in range(20)
- ]
-
- manager = ChatContextManager("test-session", messages, {})
- recent = manager._get_recent_messages()
-
- # Should have messages 10-19 (the last 10)
- contents = [m["content"] for m in recent]
- assert "Message 10" in contents
- assert "Message 19" in contents
- assert "Message 0" not in contents
-
- def test_empty_messages_handled(self):
- """Test handling of empty message list."""
- manager = ChatContextManager("test-session", [], {})
- recent = manager._get_recent_messages()
- assert recent == []
-
-
class TestContextBuilding:
"""Tests for building research context."""
@@ -61,10 +21,9 @@ class TestContextBuilding:
expected_keys = [
"session_id",
- "conversation_history",
+ "original_query",
"accumulated_findings",
"past_findings",
- "accumulated_sources",
"key_entities",
"topics",
"is_multi_turn",
@@ -113,84 +72,6 @@ class TestContextBuilding:
assert context["turn_count"] == 5
-class TestPromptContextBuilding:
- """Tests for building prompt context strings."""
-
- def test_prompt_context_empty_for_no_messages(self):
- """Test prompt context is empty with no messages."""
- manager = ChatContextManager("test-session", [], {})
- prompt = manager.build_prompt_context()
- assert prompt == ""
-
- def test_prompt_context_includes_summary(self):
- """Test that prompt context includes accumulated summary."""
- messages = [
- {"role": "user", "content": "Test", "message_type": "query"}
- ]
- accumulated = {"summary": "Previous discussion summary here"}
-
- manager = ChatContextManager("test-session", messages, accumulated)
- prompt = manager.build_prompt_context()
-
- assert "Previous conversation summary" in prompt
- assert "Previous discussion summary here" in prompt
-
- def test_prompt_context_includes_entities(self):
- """Test that prompt context includes key entities."""
- messages = [
- {"role": "user", "content": "Test", "message_type": "query"}
- ]
- accumulated = {"key_entities": ["Python", "Flask", "API"]}
-
- manager = ChatContextManager("test-session", messages, accumulated)
- prompt = manager.build_prompt_context()
-
- assert "Key entities discussed" in prompt
- assert "Python" in prompt
- assert "Flask" in prompt
-
- def test_prompt_context_includes_topics(self):
- """Test that prompt context includes topics."""
- messages = [
- {"role": "user", "content": "Test", "message_type": "query"}
- ]
- accumulated = {"topics": ["web development", "testing"]}
-
- manager = ChatContextManager("test-session", messages, accumulated)
- prompt = manager.build_prompt_context()
-
- assert "Topics covered" in prompt
- assert "web development" in prompt
-
- def test_prompt_context_truncates_long_messages(self):
- """Test that long messages are truncated in prompt."""
- long_content = "A" * 1000
- messages = [
- {"role": "user", "content": long_content, "message_type": "query"}
- ]
-
- manager = ChatContextManager("test-session", messages, {})
- prompt = manager.build_prompt_context()
-
- # Should be truncated with ...
- assert "..." in prompt
- assert len(prompt) < len(long_content)
-
- def test_prompt_context_limits_summary_length(self):
- """Test that summary is limited in length."""
- messages = [
- {"role": "user", "content": "Test", "message_type": "query"}
- ]
- long_summary = "B" * 5000
- accumulated = {"summary": long_summary}
-
- manager = ChatContextManager("test-session", messages, accumulated)
- prompt = manager.build_prompt_context()
-
- # Summary should be truncated to 2000 chars
- assert len(prompt) < 5000
-
-
class TestFindingsExtraction:
"""Tests for extracting findings from history."""
@@ -262,29 +143,6 @@ class TestFindingsExtraction:
assert "Finding 0" not in findings
-class TestSourceExtractionFromAccumulatedContext:
- """Tests for source extraction from accumulated_context (not message metadata)."""
-
- def test_extract_sources_returns_count_when_source_count_positive(self):
- """Test that source count from accumulated_context is returned."""
- manager = ChatContextManager("test-session", [], {"source_count": 5})
- sources = manager._extract_sources_from_history()
- assert len(sources) == 1
- assert sources[0]["count"] == 5
-
- def test_extract_sources_returns_empty_when_no_sources(self):
- """Test that empty list returned when source_count is 0."""
- manager = ChatContextManager("test-session", [], {"source_count": 0})
- sources = manager._extract_sources_from_history()
- assert sources == []
-
- def test_extract_sources_returns_empty_when_key_missing(self):
- """Test that empty list returned when source_count key is absent."""
- manager = ChatContextManager("test-session", [], {})
- sources = manager._extract_sources_from_history()
- assert sources == []
-
-
class TestContextUpdates:
"""Tests for extracting context updates."""
@@ -292,23 +150,12 @@ class TestContextUpdates:
"""Test that context updates include summary creation."""
manager = ChatContextManager("test-session", [], {})
updates = manager.extract_context_updates(
- "New research content here with details", []
+ "New research content here with details"
)
assert "summary_addition" in updates
assert len(updates["summary_addition"]) > 0
- def test_extract_context_updates_counts_sources(self):
- """Test that context updates count new sources."""
- manager = ChatContextManager("test-session", [], {})
- sources = [
- {"url": "http://example.com/1"},
- {"url": "http://example.com/2"},
- ]
- updates = manager.extract_context_updates("Content", sources)
-
- assert updates["source_count_delta"] == 2
-
def test_create_summary_truncates_long_content(self):
"""Test that summary creation truncates long content."""
manager = ChatContextManager("test-session", [], {})
@@ -350,29 +197,6 @@ class TestStepMessageFiltering:
# step is filtered → only 2 messages visible
assert context["turn_count"] == 2
- def test_step_messages_excluded_from_conversation_history(self):
- """Step messages should not appear in conversation_history."""
- messages = [
- {"role": "user", "content": "Query", "message_type": "query"},
- {
- "role": "assistant",
- "content": "Searching...",
- "message_type": "step",
- },
- {
- "role": "assistant",
- "content": "Here are results",
- "message_type": "response",
- "research_id": "r1",
- },
- ]
- manager = ChatContextManager("test-session", messages, {})
- context = manager.build_research_context()
- types_in_history = [
- m["message_type"] for m in context["conversation_history"]
- ]
- assert "step" not in types_in_history
-
def test_step_messages_excluded_from_is_multi_turn(self):
"""is_multi_turn should not be True from step messages alone."""
messages = [
diff --git a/tests/chat/test_chat_context_manager.py b/tests/chat/test_chat_context_manager.py
index 05bb732dab..df693d6450 100644
--- a/tests/chat/test_chat_context_manager.py
+++ b/tests/chat/test_chat_context_manager.py
@@ -20,10 +20,9 @@ class TestChatContextManagerBuildResearchContext:
# Actual return keys from implementation
required_keys = {
"session_id",
- "conversation_history",
+ "original_query",
"accumulated_findings",
"past_findings",
- "accumulated_sources",
"key_entities",
"topics",
"is_multi_turn",
@@ -63,21 +62,6 @@ class TestChatContextManagerBuildResearchContext:
assert result["is_multi_turn"] is True
- def test_build_research_context_limits_recent_messages_to_10(
- self, many_messages, sample_accumulated_context
- ):
- """Test that conversation_history is limited to 10 recent messages."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=many_messages,
- accumulated_context=sample_accumulated_context,
- )
- result = manager.build_research_context()
-
- assert len(result["conversation_history"]) <= 10
-
def test_build_research_context_includes_turn_count(
self, sample_messages, sample_accumulated_context
):
@@ -109,107 +93,6 @@ class TestChatContextManagerBuildResearchContext:
assert result["session_id"] == "test-session-abc"
-class TestChatContextManagerBuildPromptContext:
- """Tests for ChatContextManager.build_prompt_context method."""
-
- def test_build_prompt_context_returns_empty_for_no_messages(self):
- """Test that build_prompt_context returns empty string for no messages."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=[],
- accumulated_context={},
- )
- result = manager.build_prompt_context()
-
- # Should return empty or minimal context
- assert result is not None
- assert isinstance(result, str)
- assert result == ""
-
- def test_build_prompt_context_includes_summary(
- self, sample_messages, sample_accumulated_context
- ):
- """Test that build_prompt_context includes the summary."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=sample_messages,
- accumulated_context=sample_accumulated_context,
- )
- result = manager.build_prompt_context()
-
- # Should contain some reference to the summary or context
- assert len(result) > 0
- # Check that summary content is in the result
- assert "Previous conversation summary:" in result
-
- def test_build_prompt_context_truncates_summary_to_2000_chars(
- self, sample_messages
- ):
- """Test that summary is truncated to 2000 characters in prompt."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- long_summary = "A" * 3000
- context_with_long_summary = {
- "key_entities": [],
- "topics": [],
- "summary": long_summary,
- "source_count": 0,
- }
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=sample_messages,
- accumulated_context=context_with_long_summary,
- )
- result = manager.build_prompt_context()
-
- # The result should not contain the full 3000-char summary
- # It should be truncated in the prompt context
- assert long_summary not in result
-
- def test_build_prompt_context_truncates_long_messages_to_500_chars(
- self, sample_message_with_long_content, sample_accumulated_context
- ):
- """Test that individual messages are truncated to 500 chars."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- messages = [sample_message_with_long_content]
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=messages,
- accumulated_context=sample_accumulated_context,
- )
- result = manager.build_prompt_context()
-
- # The 600-char message content should be truncated
- assert "A" * 600 not in result
-
- def test_build_prompt_context_includes_entities_and_topics(
- self, sample_messages, sample_accumulated_context
- ):
- """Test that entities and topics are included in context."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=sample_messages,
- accumulated_context=sample_accumulated_context,
- )
- result = manager.build_prompt_context()
-
- # Context should reference entities or topics
- assert len(result) > 0
- # Check for entities section
- assert "Key entities discussed:" in result
- # Check for topics section
- assert "Topics covered:" in result
-
-
class TestChatContextManagerExtraction:
"""Tests for ChatContextManager extraction methods via build_research_context."""
@@ -259,45 +142,6 @@ class TestChatContextManagerExtraction:
finding_count = separator_count + 1 if findings.strip() else 0
assert finding_count <= 5
- def test_extract_sources_returns_count_summary(
- self, sample_accumulated_context
- ):
- """accumulated_sources is the count-summary shape, not per-URL records.
-
- Per-message ``metadata.sources`` are not persisted on the chat
- message rows in the current schema; the context layer reports
- only the aggregate ``source_count`` from accumulated_context.
- URL-level deduplication is unreachable until that schema
- changes — this test pins the actual contract.
- """
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=[],
- accumulated_context=sample_accumulated_context,
- )
- result = manager.build_research_context()
-
- sources = result["accumulated_sources"]
- # Count-summary shape: single entry with a numeric "count".
- assert len(sources) == 1
- assert "count" in sources[0]
- assert isinstance(sources[0]["count"], int)
- assert sources[0]["count"] > 0
-
- def test_extract_sources_empty_when_no_source_count(self):
- """Returns empty list when accumulated_context lacks source_count."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=[],
- accumulated_context={},
- )
- result = manager.build_research_context()
- assert result["accumulated_sources"] == []
-
class TestChatContextManagerCreateSummary:
"""Tests for ChatContextManager _create_summary method via extract_context_updates."""
@@ -383,41 +227,9 @@ class TestChatContextManagerExtractContextUpdates:
"new_entities",
"new_topics",
"summary_addition",
- "source_count_delta",
}
assert required_keys.issubset(set(result.keys()))
- def test_extract_context_updates_with_sources(self):
- """Test that extract_context_updates counts sources correctly."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=[],
- accumulated_context={},
- )
- sources = [
- {"title": "Source 1", "url": "https://example.com/1"},
- {"title": "Source 2", "url": "https://example.com/2"},
- {"title": "Source 3", "url": "https://example.com/3"},
- ]
- result = manager.extract_context_updates("Content", new_sources=sources)
-
- assert result["source_count_delta"] == 3
-
- def test_extract_context_updates_without_sources(self):
- """Test that extract_context_updates handles no sources."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="session-123",
- messages=[],
- accumulated_context={},
- )
- result = manager.extract_context_updates("Content", new_sources=None)
-
- assert result["source_count_delta"] == 0
-
class TestChatContextManagerKeyEntitiesAndTopics:
"""Tests for key entities and topics handling."""
diff --git a/tests/chat/test_chat_fuzz.py b/tests/chat/test_chat_fuzz.py
index faa7e309d8..1b2f88574d 100644
--- a/tests/chat/test_chat_fuzz.py
+++ b/tests/chat/test_chat_fuzz.py
@@ -67,7 +67,6 @@ def accumulated_context_dict():
"key_entities": st.lists(safe_text(max_size=50), max_size=20),
"topics": st.lists(safe_text(max_size=30), max_size=10),
"summary": safe_text(max_size=200),
- "source_count": st.integers(min_value=0, max_value=1000),
}
)
@@ -102,7 +101,6 @@ class TestChatContextManagerFuzz:
# Verify result structure
assert isinstance(context, dict)
assert "session_id" in context
- assert "conversation_history" in context
assert "is_multi_turn" in context
except Exception as e:
@@ -154,53 +152,21 @@ class TestChatContextManagerFuzz:
except Exception as e:
pytest.fail(f"Summary creation crashed: {type(e).__name__}: {e}")
- @given(messages=st.lists(message_dict(), max_size=20))
+ @given(content=safe_text(max_size=200))
@settings(max_examples=30, suppress_health_check=[HealthCheck.too_slow])
- def test_get_recent_messages_respects_limit(self, messages):
- """Test that recent messages retrieval respects limit."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- try:
- manager = ChatContextManager("test-session", messages, {})
- recent = manager._get_recent_messages()
-
- # Should respect MAX_CONTEXT_MESSAGES
- assert len(recent) <= manager.MAX_CONTEXT_MESSAGES
-
- except Exception as e:
- pytest.fail(
- f"Recent messages retrieval crashed: {type(e).__name__}: {e}"
- )
-
- @given(
- content=safe_text(max_size=200),
- sources=st.lists(
- st.fixed_dictionaries(
- {
- "url": st.text(max_size=50),
- "title": st.text(max_size=30),
- }
- ),
- max_size=5,
- ),
- )
- @settings(max_examples=30, suppress_health_check=[HealthCheck.too_slow])
- def test_extract_context_updates_handles_arbitrary_input(
- self, content, sources
- ):
+ def test_extract_context_updates_handles_arbitrary_input(self, content):
"""Test that context update extraction handles arbitrary input."""
from src.local_deep_research.chat.context import ChatContextManager
try:
manager = ChatContextManager("test-session", [], {})
- updates = manager.extract_context_updates(content, sources)
+ updates = manager.extract_context_updates(content)
# Verify structure
assert isinstance(updates, dict)
assert "new_entities" in updates
assert "new_topics" in updates
assert "summary_addition" in updates
- assert "source_count_delta" in updates
except Exception as e:
pytest.fail(
@@ -450,38 +416,7 @@ class TestChatAPIFuzz:
class TestPromptContextFuzz:
- """Fuzz tests for prompt context building."""
-
- @given(
- messages=st.lists(message_dict(), max_size=10),
- accumulated=accumulated_context_dict(),
- )
- @settings(max_examples=30, suppress_health_check=[HealthCheck.too_slow])
- def test_build_prompt_context_produces_valid_string(
- self, messages, accumulated
- ):
- """Test that prompt context building produces valid string."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- try:
- manager = ChatContextManager(
- session_id="test-session",
- messages=messages,
- accumulated_context=accumulated,
- )
-
- context_str = manager.build_prompt_context()
-
- # Should return a string
- assert isinstance(context_str, str)
-
- # Should not raise on encoding
- context_str.encode("utf-8")
-
- except Exception as e:
- pytest.fail(
- f"Prompt context building crashed: {type(e).__name__}: {e}"
- )
+ """Fuzz tests for findings extraction."""
@given(messages=st.lists(message_dict(), min_size=5, max_size=20))
@settings(max_examples=20, suppress_health_check=[HealthCheck.too_slow])
@@ -517,7 +452,6 @@ class TestEdgeCases:
assert context["is_multi_turn"] is False
assert context["turn_count"] == 0
- assert len(context["conversation_history"]) == 0
def test_none_messages_list(self):
"""Test handling of None messages."""
@@ -556,10 +490,10 @@ class TestEdgeCases:
]
manager = ChatContextManager("test-session", messages, {})
- prompt = manager.build_prompt_context()
+ findings = manager.build_research_context()["accumulated_findings"]
# Should be significantly shorter than original
- assert len(prompt) < len(long_content)
+ assert len(findings) < len(long_content)
def test_special_characters_in_entities(self):
"""Test handling of special characters in entities."""
@@ -574,7 +508,6 @@ class TestEdgeCases:
],
"topics": ["topic<tag>", "topic;semicolon"],
"summary": "Summary with <html> tags",
- "source_count": 5,
}
manager = ChatContextManager("test-session", [], accumulated)
diff --git a/tests/chat/test_chat_research_integration.py b/tests/chat/test_chat_research_integration.py
index 7a2df6956b..7224f01f33 100644
--- a/tests/chat/test_chat_research_integration.py
+++ b/tests/chat/test_chat_research_integration.py
@@ -8,7 +8,7 @@ class TestResearchIntegration:
"""Tests for chat-research integration."""
def test_research_context_built_from_conversation_history(self):
- """Test that research context includes conversation history."""
+ """Test that research context reflects the conversation turns."""
from src.local_deep_research.chat.context import ChatContextManager
messages = [
@@ -37,7 +37,6 @@ class TestResearchIntegration:
"key_entities": ["quantum computing", "qubits"],
"topics": ["physics", "computing"],
"summary": "Discussion about quantum computing basics.",
- "source_count": 5,
}
manager = ChatContextManager(
@@ -48,9 +47,9 @@ class TestResearchIntegration:
context = manager.build_research_context()
- # Should include conversation history
+ # Should reflect the multi-turn conversation
assert context["is_multi_turn"] is True
- assert len(context["conversation_history"]) == 3
+ assert context["turn_count"] == 3
# Should include accumulated data
assert "quantum computing" in context["key_entities"]
assert "physics" in context["topics"]
@@ -158,96 +157,7 @@ class TestContextExtraction:
- Applications include cryptography and drug discovery
"""
- new_sources = [
- {"url": "https://example.com/quantum1", "title": "Quantum Basics"},
- {
- "url": "https://example.com/quantum2",
- "title": "Quantum Applications",
- },
- ]
-
- updates = manager.extract_context_updates(new_content, new_sources)
+ updates = manager.extract_context_updates(new_content)
- # Should have source count
- assert updates["source_count_delta"] == 2
# Should have summary
assert len(updates["summary_addition"]) > 0
-
- def test_source_count_from_accumulated_context(self):
- """Test that sources are extracted from accumulated_context source_count."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- # Source count is tracked in accumulated_context, not per-message metadata
- manager = ChatContextManager(
- session_id="test-session",
- messages=[],
- accumulated_context={"source_count": 5},
- )
-
- sources = manager._extract_sources_from_history()
-
- assert len(sources) == 1
- assert sources[0]["count"] == 5
-
- def test_source_count_zero_returns_empty(self):
- """Test that zero source count returns empty list."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="test-session",
- messages=[],
- accumulated_context={"source_count": 0},
- )
-
- sources = manager._extract_sources_from_history()
- assert sources == []
-
-
-class TestPromptContextBuilding:
- """Tests for building prompt context for research."""
-
- def test_prompt_context_includes_all_components(self):
- """Test that prompt context includes summary, entities, topics, and messages."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- messages = [
- {"role": "user", "content": "Question about quantum computing"},
- {"role": "assistant", "content": "Answer about quantum computing"},
- ]
-
- accumulated_context = {
- "key_entities": ["quantum computing", "qubits"],
- "topics": ["physics"],
- "summary": "Discussion about quantum mechanics.",
- "source_count": 3,
- }
-
- manager = ChatContextManager(
- session_id="test-session",
- messages=messages,
- accumulated_context=accumulated_context,
- )
-
- prompt_context = manager.build_prompt_context()
-
- # Should include summary reference
- assert (
- "quantum mechanics" in prompt_context.lower()
- or "summary" in prompt_context.lower()
- )
- # Should include recent conversation
- assert "User" in prompt_context or "user" in prompt_context.lower()
-
- def test_prompt_context_empty_for_no_history(self):
- """Test that prompt context is empty when no history exists."""
- from src.local_deep_research.chat.context import ChatContextManager
-
- manager = ChatContextManager(
- session_id="test-session",
- messages=[],
- accumulated_context={},
- )
-
- prompt_context = manager.build_prompt_context()
-
- assert prompt_context == ""
diff --git a/tests/chat/test_chat_research_triggering.py b/tests/chat/test_chat_research_triggering.py
index 0f9f283703..a4611c474d 100644
--- a/tests/chat/test_chat_research_triggering.py
+++ b/tests/chat/test_chat_research_triggering.py
@@ -224,9 +224,6 @@ class TestResearchTriggering:
mock_context_manager = MagicMock()
mock_context_manager.build_research_context.return_value = {
"session_id": session_id,
- "conversation_history": [
- {"role": "user", "content": "What is AI?"}
- ],
"is_multi_turn": True,
}
mock_context_manager_class.return_value = mock_context_manager
@@ -302,7 +299,6 @@ class TestResearchTriggering:
mock_ctx = MagicMock()
mock_ctx.build_research_context.return_value = {
"session_id": session_id,
- "conversation_history": [],
"is_multi_turn": True,
}
mock_ctx_cls.return_value = mock_ctx
@@ -339,7 +335,6 @@ class TestResearchTriggering:
mock_ctx = MagicMock()
mock_ctx.build_research_context.return_value = {
"session_id": session_id,
- "conversation_history": [],
"is_multi_turn": False,
}
mock_ctx_cls.return_value = mock_ctx
diff --git a/tests/chat/test_chat_service.py b/tests/chat/test_chat_service.py
index 2d99d5b18f..77a7654194 100644
--- a/tests/chat/test_chat_service.py
+++ b/tests/chat/test_chat_service.py
@@ -126,7 +126,6 @@ class TestChatServiceSessionCreation:
"key_entities": [],
"topics": [],
"summary": "",
- "source_count": 0,
}
assert added_session.accumulated_context == expected_context
@@ -238,7 +237,6 @@ class TestChatServiceContextAccumulation:
"key_entities": ["entity1"],
"topics": [],
"summary": "",
- "source_count": 0,
}
setup_query_mock_with_session(mock_user_db_session, mock_chat_session)
mock_user_db_session.commit = MagicMock()
@@ -250,7 +248,6 @@ class TestChatServiceContextAccumulation:
new_entities=["entity2", "entity3"],
new_topics=["topic1"],
summary_addition="New summary",
- source_count_delta=3,
)
assert result is True
@@ -275,7 +272,6 @@ class TestChatServiceContextAccumulation:
"key_entities": [],
"topics": [],
"summary": "",
- "source_count": 0,
}
setup_query_mock_with_session(mock_user_db_session, mock_chat_session)
mock_user_db_session.commit = MagicMock()
@@ -301,7 +297,6 @@ class TestChatServiceContextAccumulation:
"key_entities": [],
"topics": [],
"summary": "",
- "source_count": 0,
}
setup_query_mock_with_session(mock_user_db_session, mock_chat_session)
mock_user_db_session.commit = MagicMock()
@@ -327,7 +322,6 @@ class TestChatServiceContextAccumulation:
"key_entities": [],
"topics": [],
"summary": "",
- "source_count": 0,
}
setup_query_mock_with_session(mock_user_db_session, mock_chat_session)
mock_user_db_session.commit = MagicMock()
@@ -343,30 +337,6 @@ class TestChatServiceContextAccumulation:
# Summary should be capped at 8000 characters
assert len(mock_chat_session.accumulated_context["summary"]) <= 8000
- def test_update_accumulated_context_increments_source_count(
- self, mock_user_db_session, mock_chat_session
- ):
- """Test that source_count is incremented."""
- from src.local_deep_research.chat.service import ChatService
-
- mock_chat_session.accumulated_context = {
- "key_entities": [],
- "topics": [],
- "summary": "",
- "source_count": 5,
- }
- setup_query_mock_with_session(mock_user_db_session, mock_chat_session)
- mock_user_db_session.commit = MagicMock()
-
- service = ChatService(username="testuser")
- service.update_accumulated_context(
- session_id=mock_chat_session.id,
- source_count_delta=3,
- )
-
- # Source count should be cumulative
- assert mock_chat_session.accumulated_context["source_count"] == 8
-
class TestChatServiceGetSession:
"""Tests for ChatService get_session method."""
@@ -804,7 +774,6 @@ class TestChatMessageEnumValidation:
"key_entities": [],
"topics": [],
"summary": "",
- "source_count": 0,
},
created_at=_dt.now(_utc),
message_count=0,
diff --git a/tests/chat/test_chat_xss_prevention.py b/tests/chat/test_chat_xss_prevention.py
index eb62f838fc..a878d47450 100644
--- a/tests/chat/test_chat_xss_prevention.py
+++ b/tests/chat/test_chat_xss_prevention.py
@@ -254,9 +254,8 @@ class TestContextManagerXSS:
context = manager.build_research_context()
assert isinstance(context, dict)
- # Prompt context should include the content (escaping is UI layer's job)
- prompt = manager.build_prompt_context()
- assert isinstance(prompt, str)
+ # Findings store the raw content as-is (escaping is the UI layer's job)
+ assert "<img onerror=alert(1)>" in context["accumulated_findings"]
def test_xss_in_accumulated_context(self):
"""Test that XSS in accumulated context is handled safely."""
@@ -269,7 +268,6 @@ class TestContextManagerXSS:
],
"topics": ["<img onerror=alert(1)>"],
"summary": "<svg onload=alert(1)> summary text",
- "source_count": 5,
}
manager = ChatContextManager("test-session", [], accumulated)
diff --git a/tests/database/test_chat_models.py b/tests/database/test_chat_models.py
index a703c94bc8..a69de41964 100644
--- a/tests/database/test_chat_models.py
+++ b/tests/database/test_chat_models.py
@@ -57,7 +57,6 @@ class TestChatSessionModel:
"key_entities": ["test1", "test2"],
"topics": ["topic1"],
"summary": "",
- "source_count": 0,
}
chat_session = ChatSession(
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index e3708232b3..08df548394 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -684,20 +684,6 @@
"value": false,
"visible": true
},
- "chat.max_context_messages": {
- "category": "chat",
- "description": "Maximum number of recent messages to include in chat context when building research queries. Higher values provide more conversation history but increase token usage.",
- "editable": true,
- "max_value": 50,
- "min_value": 1,
- "name": "Max Context Messages",
- "options": null,
- "step": 1,
- "type": "CHAT",
- "ui_element": "number",
- "value": 10,
- "visible": true
- },
"chat.max_findings_to_include": {
"category": "chat",
"description": "Maximum number of recent research findings to include in chat context. Higher values provide more background but increase token usage.",