fix: stream internal model calls with idle timeouts (#5730)

* fix: stream internal model calls with idle timeouts

* fix(providers): reject streams without terminal events
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-11 13:06:43 +08:00
1 parent aeb7b207d7
commit 73410e0217
60 files changed
+815 -795

No files matched your search

+26 -27
View File
@@ -63,7 +63,7 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):
provider.generation = GenerationSettings()
captured: dict[str, object] = {}
async def chat_with_retry(**kwargs):
async def chat_stream_with_retry(**kwargs):
captured.update(kwargs)
retry_status = kwargs["provider_context"].events.emit
assert retry_status is not None
@@ -76,7 +76,7 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):
))
return LLMResponse(content="done", tool_calls=[], usage=None)
provider.chat_with_retry = chat_with_retry
provider.chat_stream_with_retry = chat_stream_with_retry
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")
loop.tools.get_definitions = MagicMock(return_value=[])
@@ -103,11 +103,11 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):
async def test_ephemeral_runner_enters_and_restores_turn_scopes(tmp_path):
loop = _make_loop(tmp_path)
async def chat_with_retry(**_kwargs):
async def chat_stream_with_retry(**_kwargs):
assert goal_mutation_allowed() is True
return LLMResponse(content="done", tool_calls=[], usage=None)
loop.provider.chat_with_retry = AsyncMock(side_effect=chat_with_retry)
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=chat_stream_with_retry)
loop.tools.get_definitions = MagicMock(return_value=[])
await loop._run_agent_loop(
@@ -128,7 +128,7 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(
content="recording the agreed plan",
tool_calls=[
@@ -184,11 +184,11 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
assert result.content == "done"
assert goal_mutation_allowed() is False
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
first_request = provider.chat_with_retry.await_args_list[0].kwargs["messages"]
first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"]
assert "staged migration plan" in str(first_request)
assert "/goal implement the plan above" in str(first_request)
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(first_request)
final_request = provider.chat_with_retry.await_args_list[-1].kwargs["messages"]
final_request = provider.chat_stream_with_retry.await_args_list[-1].kwargs["messages"]
assert "create_goal is unavailable for this turn" in str(final_request)
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(session.messages[2]["content"])
assert _GOAL_RUNTIME_GUIDANCE_TAG not in str(
@@ -215,7 +215,7 @@ async def test_runtime_context_is_persisted_as_next_turn_prompt_prefix(tmp_path)
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="first answer", usage=None),
LLMResponse(content="second answer", usage=None),
])
@@ -243,8 +243,8 @@ async def test_runtime_context_is_persisted_as_next_turn_prompt_prefix(tmp_path)
content="second turn",
))
first_request = provider.chat_with_retry.await_args_list[0].kwargs["messages"]
second_request = provider.chat_with_retry.await_args_list[1].kwargs["messages"]
first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"]
second_request = provider.chat_stream_with_retry.await_args_list[1].kwargs["messages"]
first_wire = LLMProvider._sanitize_empty_content(first_request)
second_wire = LLMProvider._sanitize_empty_content(second_request)
assert second_wire[: len(first_wire)] == first_wire
@@ -271,7 +271,7 @@ async def test_webui_quote_reaches_model_without_leaking_into_public_history(tmp
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.chat_with_retry = AsyncMock(return_value=LLMResponse(content="answer", usage=None))
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="answer", usage=None))
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
session = loop.sessions.get_or_create("websocket:chat")
quote = webui_quote_runtime_context({
@@ -287,7 +287,7 @@ async def test_webui_quote_reaches_model_without_leaking_into_public_history(tmp
metadata={RUNTIME_CONTEXT_INPUT_META: [quote]},
))
request = provider.chat_with_retry.await_args.kwargs["messages"]
request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
assert "What does this mean?" in str(request)
assert "the selected answer excerpt" in str(request)
assert "the selected answer excerpt" in str(session.messages[0]["content"])
@@ -304,7 +304,7 @@ async def test_runtime_context_provider_runs_once_across_tool_iterations(tmp_pat
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(
content="reading",
tool_calls=[ToolCallRequest(
@@ -333,9 +333,9 @@ async def test_runtime_context_provider_runs_once_across_tool_iterations(tmp_pat
content="read the note",
))
assert provider.chat_with_retry.await_count == 2
assert provider.chat_stream_with_retry.await_count == 2
assert provider_calls == 1
for call in provider.chat_with_retry.await_args_list:
for call in provider.chat_stream_with_retry.await_args_list:
assert "frozen context" in str(call.kwargs["messages"])
@@ -346,7 +346,7 @@ async def test_non_goal_direct_turn_cannot_reuse_prior_goal_command(tmp_path):
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(
content="trying to create a goal",
tool_calls=[
@@ -376,13 +376,13 @@ async def test_non_goal_direct_turn_cannot_reuse_prior_goal_command(tmp_path):
assert result is not None
assert result.content == "handled as a one-time task"
assert GOAL_STATE_KEY not in session.metadata
second_request = provider.chat_with_retry.await_args_list[1].kwargs["messages"]
second_request = provider.chat_stream_with_retry.await_args_list[1].kwargs["messages"]
assert "create_goal is unavailable for this turn" in str(second_request)
@pytest.mark.asyncio
async def test_loop_max_iterations_message_stays_stable(tmp_path):
loop = _make_loop(tmp_path)
loop.provider.chat_with_retry = AsyncMock(return_value=LLMResponse(
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="working",
tool_calls=[ToolCallRequest(id="call_1", name="list_dir", arguments={})],
))
@@ -404,7 +404,7 @@ async def test_loop_max_iterations_message_stays_stable(tmp_path):
@pytest.mark.asyncio
async def test_loop_goal_turn_uses_standard_iteration_budget(tmp_path):
loop = _make_loop(tmp_path)
loop.provider.chat_with_retry = AsyncMock(return_value=LLMResponse(
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="working",
tool_calls=[ToolCallRequest(id="call_1", name="list_dir", arguments={})],
))
@@ -425,8 +425,8 @@ async def test_loop_goal_turn_uses_standard_iteration_budget(tmp_path):
)
assert result.stop_reason == "max_iterations"
assert loop.provider.chat_with_retry.await_count == 3
assert loop.provider.chat_with_retry.await_args_list[-1].kwargs["tools"] is None
assert loop.provider.chat_stream_with_retry.await_count == 3
assert loop.provider.chat_stream_with_retry.await_args_list[-1].kwargs["tools"] is None
assert result.final_content == (
"I reached the maximum number of tool call iterations (2) "
"without completing the task. You can try breaking the task into smaller steps."
@@ -521,13 +521,13 @@ async def test_loop_retries_think_only_final_response(tmp_path):
loop = _make_loop(tmp_path)
call_count = {"n": 0}
async def chat_with_retry(**kwargs):
async def chat_stream_with_retry(**kwargs):
call_count["n"] += 1
if call_count["n"] == 1:
return LLMResponse(content="<think>hidden</think>", tool_calls=[], usage=None)
return LLMResponse(content="Recovered answer", tool_calls=[], usage=None)
loop.provider.chat_with_retry = chat_with_retry
loop.provider.chat_stream_with_retry = chat_stream_with_retry
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
@@ -553,7 +553,6 @@ async def test_streamed_flag_not_set_on_llm_error(tmp_path):
error_resp = LLMResponse(
content="503 service unavailable", finish_reason="error", tool_calls=[], usage=None,
)
loop.provider.chat_with_retry = AsyncMock(return_value=error_resp)
loop.provider.chat_stream_with_retry = AsyncMock(return_value=error_resp)
loop.tools.get_definitions = MagicMock(return_value=[])
@@ -634,7 +633,7 @@ async def test_next_turn_after_llm_error_keeps_turn_boundary(tmp_path):
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.chat_with_retry = AsyncMock(side_effect=[
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="429 rate limit exceeded", finish_reason="error", tool_calls=[], usage=None),
LLMResponse(content="Recovered answer", tool_calls=[], usage=None),
])
@@ -663,7 +662,7 @@ async def test_next_turn_after_llm_error_keeps_turn_boundary(tmp_path):
assert second is not None
assert second.content == "Recovered answer"
request_messages = provider.chat_with_retry.await_args_list[1].kwargs["messages"]
request_messages = provider.chat_stream_with_retry.await_args_list[1].kwargs["messages"]
non_system = [message for message in request_messages if message.get("role") != "system"]
assert non_system[0]["role"] == "user"
assert "first question" in non_system[0]["content"]
@@ -681,7 +680,7 @@ async def test_subagent_max_iterations_announces_existing_fallback(tmp_path, mon
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.chat_with_retry = AsyncMock(return_value=LLMResponse(
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
content="working",
tool_calls=[ToolCallRequest(id="call_1", name="list_dir", arguments={"path": "."})],
))