Files
DeepTutor/tests/capabilities/test_explore_context_capability.py
zszz3 246aa1426b fix(chat): keep the loop's tools in the forced final round
Prompt caches key on tools, then system, then messages. Every round of a
chat-loop turn sends the loop's tool schemas, but the forced finish (round
budget spent) sent the request with tool_schemas=None. That changed the
very start of the request, so the whole turn history (often 10k-60k
tokens) missed the cache on the final round. tool_choice="none" is no
fix: on DeepSeek it caches exactly like a request without tools.

The forced finish now sends the same tool list the last normal round
sent (taken from the request snapshot, since the deferred tool loader
appends to the live list after a request goes out) with tool_choice left
at auto; the finish instruction already tells the model to stop calling
tools. A tool call it returns anyway is never dispatched, and no ask_user
draft card is published for it. The round is kept in the history as text
only (a call without a result is rejected by the next request; Responses
function_call items are dropped too), a repair note asks for a plain-text
answer, and one more attempt runs. If that also calls a tool, the turn
ends with the existing empty-response fallback. The forced finish still
counts as one loop round. The persisted model_turn tools and the context
budget now reflect what the final request really carried.

The context-exploration pre-pass had the same pattern on its last round
(tools dropped); it now keeps the tools, does not run a tool call there,
repairs once, and otherwise degrades to the existing single pass.

The finish instructions (chat, mastery, explore_context; en/zh) now say
the tools are still listed but no call will run. Same approach as the
staged pipelines' forced finish (#3080).

Refs #3182
2026-12-02 16:58:58 +08:00

831 lines
32 KiB
Python

"""Unit tests for the explore-context loop capability and its explorer."""
from __future__ import annotations
import asyncio
from typing import Any
import pytest
from deeptutor.capabilities.explore_context import ExploreContextCapability
from deeptutor.capabilities.explore_context import explorer as explorer_mod
from deeptutor.capabilities.explore_context.capability import _load_prompts
from deeptutor.capabilities.protocol import PromptBlock
from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.core.stream import StreamEventType
from deeptutor.runtime.agentic.usage import UsageTracker, message_content_chars
from deeptutor.runtime.stream_bus import StreamBus
from deeptutor.services.llm.exceptions import LLMProviderTransportError
def _ctx(**metadata: Any) -> UnifiedContext:
attachments = metadata.pop("_attachments", [])
manifest = metadata.pop("_manifest", "")
return UnifiedContext(
session_id="s1",
user_message="what did this chat do?",
attachments=attachments,
source_manifest=manifest,
metadata=metadata,
)
# ---------------------------------------------------------------------------
# is_active
# ---------------------------------------------------------------------------
def test_is_active_requires_readable_sources() -> None:
cap = ExploreContextCapability()
# A readable source attached this turn → active.
assert cap.is_active(_ctx(source_index={"hs-x": "t"}, history_references=["hs-x"])) is True
# A source carried over from an earlier turn (no fresh ref this turn) is
# ALSO active now — the investigation runs query-driven on every turn that
# has sources to read.
assert cap.is_active(_ctx(source_index={"hs-x": "t"})) is True
# A fresh reference but no readable source index (e.g. non-chat turn) → skip.
assert cap.is_active(_ctx(history_references=["hs-x"])) is False
# Empty turn → skip.
assert cap.is_active(_ctx()) is False
def test_is_active_image_only_turn_has_no_readable_source() -> None:
cap = ExploreContextCapability()
# Image attachments never enter the source index, so an image-only turn
# carries no readable source and the pre-pass stays dormant.
img = Attachment(type="image", id="i1")
assert cap.is_active(_ctx(_attachments=[img])) is False
def test_capability_owns_no_tools_and_no_system_block() -> None:
cap = ExploreContextCapability()
assert cap.owned_tools == ()
assert cap.pre_loop_seed(_ctx()) == ""
assert cap.system_block(_ctx(), language="en", prompts={}) is None
# ---------------------------------------------------------------------------
# Single-pass fallback (non-native tool-calling models)
# ---------------------------------------------------------------------------
def _fake_stream(briefing_chunks: list[str]):
async def _stream(*_args: Any, **_kwargs: Any):
for chunk in briefing_chunks:
yield chunk
return _stream
@pytest.fixture
def _force_single_pass(monkeypatch: pytest.MonkeyPatch) -> None:
"""Pin the explorer onto its single-pass (llm_stream) fallback path."""
monkeypatch.setattr(explorer_mod, "can_use_native_tool_calling", lambda **_kwargs: False)
@pytest.mark.asyncio
async def test_single_pass_returns_investigation_block(
monkeypatch: pytest.MonkeyPatch, _force_single_pass: None
) -> None:
monkeypatch.setattr(
explorer_mod,
"llm_stream",
_fake_stream(["In this transcript, the user and ", "the other agent updated the nav."]),
)
cap = ExploreContextCapability()
ctx = _ctx(
source_index={"hs-imported_claude_code_x": "## Claude Code\nI updated the nav."},
history_references=["imported_claude_code_x"],
_manifest="[Attached Sources]\n- id=hs-imported_claude_code_x type=history name='nav'",
)
block = await cap.pre_loop(ctx, StreamBus(), usage=None)
assert isinstance(block, PromptBlock)
assert block.name == "explore_context"
# Header framing + the model's third-person account are both present.
assert "Context Investigation" in block.content
assert "Do not call a file, PDF, or source-loading tool" in block.content
assert "the other agent updated the nav." in block.content
@pytest.mark.asyncio
async def test_pre_loop_emits_no_content_events(
monkeypatch: pytest.MonkeyPatch, _force_single_pass: None
) -> None:
"""The pre-pass must never stream CONTENT — only that channel is captured
as the turn's user-facing answer."""
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["briefing"]))
cap = ExploreContextCapability()
ctx = _ctx(source_index={"hs-x": "transcript"}, history_references=["x"])
bus = StreamBus()
await cap.pre_loop(ctx, bus, usage=None)
kinds = [e.type for e in bus._history]
assert StreamEventType.CONTENT not in kinds
assert StreamEventType.STAGE_START in kinds
assert StreamEventType.THINKING in kinds
@pytest.mark.asyncio
async def test_pre_loop_inactive_returns_none() -> None:
cap = ExploreContextCapability()
# No readable sources → inactive → no pre-pass, no LLM call.
assert await cap.pre_loop(_ctx(history_references=["x"]), StreamBus(), usage=None) is None
@pytest.mark.asyncio
async def test_pre_loop_empty_investigation_returns_none(
monkeypatch: pytest.MonkeyPatch, _force_single_pass: None
) -> None:
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream([" "]))
cap = ExploreContextCapability()
ctx = _ctx(source_index={"hs-x": "t"}, history_references=["x"])
assert await cap.pre_loop(ctx, StreamBus(), usage=None) is None
@pytest.mark.asyncio
async def test_pre_loop_swallows_llm_failure(
monkeypatch: pytest.MonkeyPatch, _force_single_pass: None
) -> None:
def _boom(*_args: Any, **_kwargs: Any):
raise RuntimeError("provider down")
monkeypatch.setattr(explorer_mod, "llm_stream", _boom)
cap = ExploreContextCapability()
ctx = _ctx(source_index={"hs-x": "t"}, history_references=["x"])
# A failed pre-pass degrades to no investigation, never raises.
assert await cap.pre_loop(ctx, StreamBus(), usage=None) is None
# ---------------------------------------------------------------------------
# Agentic loop (native tool-calling models)
# ---------------------------------------------------------------------------
class _FakeFunc:
def __init__(self, name: str | None = None, arguments: str | None = None) -> None:
self.name = name
self.arguments = arguments
class _FakeToolCall:
def __init__(self, index: int, call_id: str, name: str, arguments: str) -> None:
self.index = index
self.id = call_id
self.function = _FakeFunc(name=name, arguments=arguments)
class _FakeDelta:
def __init__(
self,
content: str | None = None,
tool_calls: list[_FakeToolCall] | None = None,
reasoning_content: str | None = None,
) -> None:
self.content = content
self.tool_calls = tool_calls
self.reasoning_content = reasoning_content
self.reasoning = None
class _FakeChoice:
def __init__(self, delta: _FakeDelta, provider_specific_fields: dict | None = None) -> None:
self.delta = delta
self.finish_reason = None
self.provider_specific_fields = provider_specific_fields
class _FakeChunk:
def __init__(
self,
delta: _FakeDelta | None = None,
provider_specific_fields: dict | None = None,
*,
usage: dict[str, int] | None = None,
) -> None:
self.choices = [_FakeChoice(delta, provider_specific_fields)] if delta is not None else []
self.usage = usage
class _FakeResponseStream:
def __init__(self, chunks: list[_FakeChunk]) -> None:
self._chunks = chunks
async def __aiter__(self):
for chunk in self._chunks:
yield chunk
class _FakeCompletions:
"""Returns one queued response per ``create`` call (one per loop round)."""
def __init__(self, rounds: list[list[_FakeChunk]]) -> None:
self._rounds = list(rounds)
self.calls: list[dict[str, Any]] = []
async def create(self, **kwargs: Any) -> _FakeResponseStream:
self.calls.append(kwargs)
chunks = self._rounds.pop(0) if self._rounds else []
return _FakeResponseStream(chunks)
class _FakeClient:
def __init__(self, rounds: list[list[_FakeChunk]]) -> None:
self.chat = type("Chat", (), {"completions": _FakeCompletions(rounds)})()
@pytest.fixture
def _force_loop(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(explorer_mod, "can_use_native_tool_calling", lambda **_kwargs: True)
@pytest.mark.asyncio
@pytest.mark.parametrize("language", ["en", "zh"])
async def test_loop_reads_source_then_writes_investigation(
monkeypatch: pytest.MonkeyPatch, _force_loop: None, language: str
) -> None:
"""The investigator calls read_source on a source, then writes an
investigation grounded in the loaded full text."""
rounds = [
# Round 0: ask to read the attached transcript.
[
_FakeChunk(
_FakeDelta(
tool_calls=[_FakeToolCall(0, "call_1", "read_source", '{"source_id": "hs-x"}')]
)
)
],
# Round 1: no tool calls → this text is the investigation.
[_FakeChunk(_FakeDelta(content="The other agent rewrote the nav and shipped it."))],
]
fake_client = _FakeClient(rounds)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)
cap = ExploreContextCapability()
ctx = _ctx(
source_index={"hs-x": "## Claude Code\nI rewrote the nav and shipped it."},
history_references=["x"],
_manifest="[Attached Sources]\n- id=hs-x type=history name='nav'",
)
ctx.language = language
bus = StreamBus()
block = await cap.pre_loop(ctx, bus, usage=None)
assert isinstance(block, PromptBlock)
assert ("Context Investigation" if language == "en" else "上下文调查") in block.content
assert "rewrote the nav" in block.content
# read_source was dispatched (the model's source_id reached the create
# call only via the tool round, and a tool result fed the second round).
completions = fake_client.chat.completions
assert len(completions.calls) == 2
system_prompt = completions.calls[0]["messages"][0]["content"]
assert (
"at most 15 tool calls" if language == "en" else "最多请求 15 次工具调用"
) in system_prompt
assert "{tool_call_limit}" not in system_prompt
# Never streamed CONTENT — the investigation rides the thinking channel.
kinds = [e.type for e in bus._history]
assert StreamEventType.CONTENT not in kinds
assert StreamEventType.TOOL_CALL in kinds
@pytest.mark.asyncio
async def test_loop_records_reported_or_estimated_usage_per_call(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
read = _FakeToolCall(0, "call_1", "read_source", '{"source_id":"hs-x"}')
answer = "briefing"
client = _FakeClient(
[
[
_FakeChunk(
_FakeDelta(tool_calls=[read]),
usage={"prompt_tokens": 100, "completion_tokens": 4},
),
_FakeChunk(usage={"prompt_tokens": 100, "completion_tokens": 8}),
],
[_FakeChunk(_FakeDelta(content=answer)), _FakeChunk(usage={})],
]
)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _: client)
usage = UsageTracker()
block = await ExploreContextCapability().pre_loop(
_ctx(source_index={"hs-x": "source text"}), StreamBus(), usage=usage
)
assert block and answer in block.content
first, second = client.chat.completions.calls
estimated_input = sum(message_content_chars(m) for m in second["messages"])
assert usage.calls == 2
assert usage.prompt_tokens == 100 + int(estimated_input / 3.5)
assert usage.completion_tokens == 8 + int(len(answer) / 3.5)
assert first["stream_options"] == second["stream_options"] == {"include_usage": True}
@pytest.mark.asyncio
async def test_loop_retries_without_rejected_stream_options(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
client = _FakeClient([])
calls = []
async def create(**kwargs: Any) -> _FakeResponseStream:
calls.append(kwargs)
if "stream_options" in kwargs:
raise ValueError("Unsupported parameter: stream_options")
return _FakeResponseStream([_FakeChunk(_FakeDelta(content="compatible reply"))])
monkeypatch.setattr(client.chat.completions, "create", create)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _: client)
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["single-pass reply"]))
usage = UsageTracker()
block = await ExploreContextCapability().pre_loop(
_ctx(source_index={"hs-x": "source text"}), StreamBus(), usage=usage
)
assert block and "compatible reply" in block.content
first, retry = calls
assert "stream_options" not in retry
assert first == {**retry, "stream_options": {"include_usage": True}}
assert usage.calls == 1
@pytest.mark.asyncio
async def test_loop_falls_back_to_single_pass_on_client_error(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
"""A loop that errors before producing anything degrades to the robust
single-pass dump-and-brief so the answer loop still gets grounding."""
def _boom_client(_cfg: Any) -> Any:
raise RuntimeError("schema rejected")
monkeypatch.setattr(explorer_mod, "build_openai_client", _boom_client)
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["fallback briefing text"]))
cap = ExploreContextCapability()
ctx = _ctx(source_index={"hs-x": "transcript body"}, history_references=["x"])
block = await cap.pre_loop(ctx, StreamBus(), usage=None)
assert isinstance(block, PromptBlock)
assert "fallback briefing text" in block.content
# ---------------------------------------------------------------------------
# Stream idle timeout (#2539: a connected provider that stops yielding
# chunks parked the whole turn in ``running`` — the pre-pass runs before the
# answer loop's watchdog, so nothing else bounded it).
# ---------------------------------------------------------------------------
class _StalledStream:
"""A stream that yields one chunk, then never produces another."""
def __init__(self, first: _FakeChunk | None = None) -> None:
self._first = first
def __aiter__(self):
return self
async def __anext__(self):
if self._first is not None:
chunk, self._first = self._first, None
return chunk
await asyncio.Event().wait()
raise StopAsyncIteration # pragma: no cover — unreachable
@pytest.mark.asyncio
async def test_a_stalled_pre_pass_stream_times_out(monkeypatch: pytest.MonkeyPatch) -> None:
"""The pre-pass raises once the provider goes idle instead of hanging.
Done against ``ContextExplorer._call_llm`` rather than the helper, so the
test fails on a hang (not just on a missing symbol) if the bound is ever
removed from the call site.
"""
monkeypatch.setattr(explorer_mod, "_STREAM_IDLE_TIMEOUT_SECONDS", 0.1, raising=False)
explorer = explorer_mod.ContextExplorer.__new__(explorer_mod.ContextExplorer)
explorer.model = "m"
explorer.binding = "openai"
explorer.reasoning_effort = None
class _Client:
def __init__(self) -> None:
self.chat = type(
"Chat", (), {"completions": type("Completions", (), {"create": self._create})()}
)()
async def _create(self, **_kwargs: Any) -> _StalledStream:
return _StalledStream()
# Without the idle bound the await never returns; the outer ``wait_for``
# then trips with ``asyncio.TimeoutError`` and this assertion fails, which
# is the regression signal (a hang, not a missing symbol).
with pytest.raises(LLMProviderTransportError):
await asyncio.wait_for(
explorer._call_llm(
client=_Client(),
messages=[{"role": "user", "content": "hi"}],
tool_schemas=None,
chunk_meta={},
stream=StreamBus(),
session_id="s1",
),
timeout=5,
)
@pytest.mark.asyncio
async def test_loop_falls_back_to_single_pass_when_stream_stalls(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
"""A stream that stalls mid-round degrades to the single-pass briefing.
This is the #2539 third-attempt hang: without the idle bound, the
``pre_loop`` await never completed, the turn stayed ``running`` forever,
and the lease kept renewing so recovery never claimed it.
"""
monkeypatch.setattr(explorer_mod, "_STREAM_IDLE_TIMEOUT_SECONDS", 0.1, raising=False)
class _StalledClient:
def __init__(self) -> None:
self.chat = type(
"Chat", (), {"completions": type("Completions", (), {"create": self._create})()}
)()
async def _create(self, **_kwargs: Any) -> _StalledStream:
return _StalledStream(_FakeChunk(_FakeDelta(content="partial")))
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: _StalledClient())
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["stalled fallback briefing"]))
cap = ExploreContextCapability()
ctx = _ctx(source_index={"hs-x": "transcript body"}, history_references=["x"])
block = await asyncio.wait_for(cap.pre_loop(ctx, StreamBus(), usage=None), timeout=5)
assert isinstance(block, PromptBlock)
assert "stalled fallback briefing" in block.content
# ---------------------------------------------------------------------------
# Reasoning replay state (#1400: DeepSeek thinking mode rejects a tool-round
# history whose reasoning was dropped — Responses-wire converters only replay
# it from ``_provider_response_state``).
# ---------------------------------------------------------------------------
def _reasoning_tool_round(native_items: list[dict[str, Any]] | None) -> list[_FakeChunk]:
"""One streamed round: reasoning delta, then a read_source tool call."""
chunks = [
_FakeChunk(_FakeDelta(reasoning_content="I should read the transcript first.")),
_FakeChunk(
_FakeDelta(
tool_calls=[_FakeToolCall(0, "call_1", "read_source", '{"source_id": "hs-x"}')]
)
),
]
if native_items is not None:
chunks.append(
_FakeChunk(
_FakeDelta(),
provider_specific_fields={"native_output_items": native_items},
)
)
return chunks
@pytest.mark.asyncio
async def test_loop_replays_provider_reasoning_state_on_tool_rounds(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
"""The tool-round assistant message carries the provider's native output
items so a Responses-wire provider still sees the round's reasoning."""
native_items = [
{
"type": "reasoning",
"id": "rs_1",
"content": [{"type": "reasoning_text", "text": "I should read the transcript first."}],
},
{
"type": "function_call",
"id": "fc_1",
"call_id": "call_1",
"name": "read_source",
"arguments": '{"source_id": "hs-x"}',
},
]
fake_client = _FakeClient(
[
_reasoning_tool_round(native_items),
[_FakeChunk(_FakeDelta(content="The transcript shows the nav was rewritten."))],
]
)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)
cap = ExploreContextCapability()
ctx = _ctx(
source_index={"hs-x": "## Claude Code\nI rewrote the nav and shipped it."},
history_references=["x"],
)
block = await cap.pre_loop(ctx, StreamBus(), usage=None)
assert isinstance(block, PromptBlock)
assert "nav was rewritten" in block.content
completions = fake_client.chat.completions
assert len(completions.calls) == 2
assistant = next(m for m in completions.calls[1]["messages"] if m.get("role") == "assistant")
state = assistant.get("_provider_response_state")
assert state is not None
assert state.get("responses_output_items") == native_items
# The chat-dialect echo stays on the message for Chat Completions providers.
assert assistant.get("reasoning_content") == "I should read the transcript first."
@pytest.mark.asyncio
async def test_loop_plain_provider_keeps_chat_echo_without_native_items(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
"""A provider that never reported native output items gets the plain
chat-completions echo — and never a fabricated reasoning item."""
fake_client = _FakeClient(
[
_reasoning_tool_round(None),
[_FakeChunk(_FakeDelta(content="The transcript shows the nav was rewritten."))],
]
)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)
cap = ExploreContextCapability()
ctx = _ctx(
source_index={"hs-x": "## Claude Code\nI rewrote the nav."}, history_references=["x"]
)
await cap.pre_loop(ctx, StreamBus(), usage=None)
completions = fake_client.chat.completions
assistant = next(m for m in completions.calls[1]["messages"] if m.get("role") == "assistant")
assert assistant.get("reasoning_content") == "I should read the transcript first."
state = assistant.get("_provider_response_state")
assert not (state or {}).get("responses_output_items")
@pytest.mark.asyncio
async def test_loop_nudges_reasoning_only_round_into_writing(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
"""A round that produced only reasoning (budget burned, nothing visible)
is nudged once with the forced-finish instruction instead of silently
collapsing into the single-pass fallback."""
monkeypatch.setattr(
explorer_mod, "llm_stream", _fake_stream(["fallback briefing that must not be used"])
)
fake_client = _FakeClient(
[
[_FakeChunk(_FakeDelta(reasoning_content="Planning the whole investigation..."))],
[_FakeChunk(_FakeDelta(content="The transcript shows the nav was rewritten."))],
]
)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)
cap = ExploreContextCapability()
ctx = _ctx(
source_index={"hs-x": "## Claude Code\nI rewrote the nav."}, history_references=["x"]
)
block = await cap.pre_loop(ctx, StreamBus(), usage=None)
completions = fake_client.chat.completions
assert len(completions.calls) == 2
second_messages = completions.calls[1]["messages"]
nudged_assistant = next(m for m in second_messages if m.get("role") == "assistant")
assert nudged_assistant.get("reasoning_content") == "Planning the whole investigation..."
assert second_messages[-1]["role"] == "user"
assert "Investigation budget reached" in str(second_messages[-1]["content"])
# The loop's own investigation won — not the single-pass fallback.
assert isinstance(block, PromptBlock)
assert "nav was rewritten" in block.content
@pytest.mark.asyncio
async def test_reasoning_only_exhaustion_falls_back_to_single_pass(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
"""The nudge fires once; a second reasoning-only round ends the loop and
degrades to the single-pass briefing (bounded, never an infinite nudge)."""
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["fallback briefing text"]))
fake_client = _FakeClient(
[
[_FakeChunk(_FakeDelta(reasoning_content="Thinking pass one..."))],
[_FakeChunk(_FakeDelta(reasoning_content="Thinking pass two..."))],
]
)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)
cap = ExploreContextCapability()
ctx = _ctx(
source_index={"hs-x": "## Claude Code\nI rewrote the nav."}, history_references=["x"]
)
block = await cap.pre_loop(ctx, StreamBus(), usage=None)
# Round 0 nudged, round 1 reasoning-only again → loop ends, single pass runs.
assert len(fake_client.chat.completions.calls) == 2
assert isinstance(block, PromptBlock)
assert "fallback briefing text" in block.content
def _read_call(call_id: str) -> list[_FakeChunk]:
return [
_FakeChunk(
_FakeDelta(
tool_calls=[_FakeToolCall(0, call_id, "read_source", '{"source_id": "hs-x"}')]
)
)
]
def _tool_results(messages: list[dict[str, Any]]) -> list[str]:
return [m["tool_call_id"] for m in messages if m.get("role") == "tool"]
@pytest.mark.asyncio
async def test_forced_finish_keeps_the_loop_tools(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
"""The last round sends the same tools as the rounds before it, so its
request keeps their cached prefix (caches key on tools first)."""
monkeypatch.setattr(explorer_mod, "MAX_LOOP_ROUNDS", 2)
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["fallback briefing"]))
fake_client = _FakeClient(
[_read_call("call_1"), [_FakeChunk(_FakeDelta(content="The nav was rewritten."))]]
)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)
cap = ExploreContextCapability()
ctx = _ctx(source_index={"hs-x": "I rewrote the nav."}, history_references=["x"])
block = await cap.pre_loop(ctx, StreamBus(), usage=None)
calls = fake_client.chat.completions.calls
assert len(calls) == 2
assert calls[0]["tools"]
assert calls[1]["tools"] == calls[0]["tools"]
assert calls[1].get("tool_choice") in (None, "auto")
assert "Investigation budget reached" in str(calls[1]["messages"][-1]["content"])
assert isinstance(block, PromptBlock)
assert "nav was rewritten" in block.content
@pytest.mark.asyncio
async def test_forced_finish_tool_call_is_not_run_and_gets_one_repair(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
monkeypatch.setattr(explorer_mod, "MAX_LOOP_ROUNDS", 2)
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["fallback briefing"]))
fake_client = _FakeClient(
[
_read_call("call_1"),
_read_call("call_2"),
[_FakeChunk(_FakeDelta(content="The nav was rewritten."))],
]
)
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)
cap = ExploreContextCapability()
ctx = _ctx(source_index={"hs-x": "I rewrote the nav."}, history_references=["x"])
block = await cap.pre_loop(ctx, StreamBus(), usage=None)
calls = fake_client.chat.completions.calls
assert len(calls) == 3
assert calls[2]["tools"] == calls[0]["tools"]
repair_messages = calls[2]["messages"]
# Only the exploration round's call ran; the forced round's call did not.
assert _tool_results(repair_messages) == ["call_1"]
skipped, repair = repair_messages[-2:]
assert skipped["role"] == "assistant"
assert not skipped.get("tool_calls")
assert skipped["content"] == "(Tool call not run: the investigation must finish now.)"
assert repair["role"] == "user"
assert "not run" in repair["content"]
assert isinstance(block, PromptBlock)
assert "nav was rewritten" in block.content
@pytest.mark.asyncio
async def test_forced_finish_that_keeps_calling_tools_falls_back_to_single_pass(
monkeypatch: pytest.MonkeyPatch, _force_loop: None
) -> None:
monkeypatch.setattr(explorer_mod, "MAX_LOOP_ROUNDS", 2)
monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["fallback briefing text"]))
fake_client = _FakeClient([_read_call("call_1"), _read_call("call_2"), _read_call("call_3")])
monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)
cap = ExploreContextCapability()
ctx = _ctx(source_index={"hs-x": "I rewrote the nav."}, history_references=["x"])
block = await cap.pre_loop(ctx, StreamBus(), usage=None)
assert len(fake_client.chat.completions.calls) == 3
assert isinstance(block, PromptBlock)
assert "fallback briefing text" in block.content
# ---------------------------------------------------------------------------
# ContextExplorer source assembly (single-pass helpers)
# ---------------------------------------------------------------------------
def test_explorer_clips_and_caps_sources() -> None:
explorer = explorer_mod.ContextExplorer(language="en", prompts={})
big = {f"nb-{i}": "y" * 100_000 for i in range(explorer_mod.MAX_SOURCES + 5)}
blocks = explorer._render_source_blocks(big)
assert blocks.count("### [") <= explorer_mod.MAX_SOURCES
assert "(truncated)" in blocks
assert len(blocks) <= explorer_mod.TOTAL_CHARS + 5_000 # blocks + headers/notes
def test_explorer_kind_label_from_prefix() -> None:
explorer = explorer_mod.ContextExplorer(language="en", prompts={})
assert explorer._kind_label("hs-abc") == "Conversation transcript"
assert explorer._kind_label("at-abc") == "Document"
assert explorer._kind_label("zz-abc") == "Source"
@pytest.mark.parametrize("language", ["en", "zh"])
def test_preloaded_source_text_stays_in_the_shared_prefix(language: str) -> None:
explorer = explorer_mod.ContextExplorer(language=language, prompts=_load_prompts(language))
source_text = "Lecture notes on the sampling theorem."
sources = {"at-lecture": source_text}
fresh = "at-lecture: preview from the upload"
previous = "at-lecture: previously attached (turn 1)"
upload = explorer._cache_shaped_messages(
source_index=sources, mode="chat", manifest=fresh, question="What is the theorem?"
)
followup = explorer._cache_shaped_messages(
source_index=sources, mode="deep_solve", manifest=previous, question="Can you prove it?"
)
assert upload[0] == followup[0]
assert source_text in upload[0]["content"]
# Without this the model re-reads the preloaded text with read_source on
# every turn, sending the whole lecture a second time.
assert "read_source" in upload[0]["content"]
for messages, mode, manifest, question in (
(upload, "chat", fresh, "What is the theorem?"),
(followup, "deep_solve", previous, "Can you prove it?"),
):
assert [m["role"] for m in messages] == ["user", "user"]
assert all(value in messages[1]["content"] for value in (mode, manifest, question))
def test_preload_never_exceeds_limit_even_for_the_first_source():
explorer = object.__new__(explorer_mod.ContextExplorer)
sources = {"too-large": "x" * 120001, "b": "y" * 80000, "a": "z" * 40000, "extra": "q"}
selected = explorer._preload_selection(sources)
assert selected == ["b", "a"]
assert sum(len(sources[key]) for key in selected) <= explorer_mod.PRELOAD_MAX_CHARS
assert sources["too-large"] == "x" * 120001
assert explorer._preload_selection({"only": sources["too-large"]}) == []
@pytest.mark.asyncio
async def test_a_stalled_connection_setup_also_times_out(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Opening the stream is bounded too, not just reading it.
A provider that hangs while connecting parks the turn exactly like one
that stalls mid-stream, and the answer loop already bounds both halves.
"""
monkeypatch.setattr(explorer_mod, "_STREAM_IDLE_TIMEOUT_SECONDS", 0.1)
explorer = explorer_mod.ContextExplorer.__new__(explorer_mod.ContextExplorer)
explorer.model = "m"
explorer.binding = "openai"
explorer.reasoning_effort = None
class _HangingClient:
def __init__(self) -> None:
self.chat = type(
"Chat", (), {"completions": type("Completions", (), {"create": self._create})()}
)()
async def _create(self, **_kwargs: Any) -> Any:
await asyncio.Event().wait()
with pytest.raises(asyncio.TimeoutError):
await asyncio.wait_for(
explorer._call_llm(
client=_HangingClient(),
messages=[{"role": "user", "content": "hi"}],
tool_schemas=None,
chunk_meta={},
stream=StreamBus(),
session_id="s1",
),
timeout=5,
)