From 757e84482f7319f039512a71e9497a770e8541ed Mon Sep 17 00:00:00 2001
From: huanghuang358 <178640467+huanghuang358@users.noreply.github.com>
Date: Sun, 19 Apr 2026 12:53:46 +0800
Subject: [PATCH] fix(s08): avoid consecutive user messages when draining
background notifications
The previous implementation always appended a new user message for background
results regardless of the trailing message's role. After a tool round-trip
(or right after the user query), the messages list could end up with two
adjacent user messages, which is messy for prompt caching, token accounting
and stricter API gateways.
Now we merge the background-results block into the trailing user message
when its role is already user, and only append a fresh user message
otherwise. tool_result blocks still immediately follow their tool_use, so
the protocol contract is preserved.
---
agents/s08_background_tasks.py | 20 ++++++++++++++++++--
1 file changed, 18 insertions(+), 2 deletions(-)
diff --git a/agents/s08_background_tasks.py b/agents/s08_background_tasks.py
index 390a77780..410732b1c 100644
--- a/agents/s08_background_tasks.py
+++ b/agents/s08_background_tasks.py
@@ -187,13 +187,29 @@ def run_edit(path: str, old_text: str, new_text: str) -> str:
def agent_loop(messages: list):
while True:
- # Drain background notifications and inject as system message before LLM call
+ # Drain background notifications and inject before the next LLM call.
+ # Merge into the trailing user message when possible to avoid emitting
+ # two consecutive user messages (which is messy for caching/debugging).
notifs = BG.drain_notifications()
if notifs and messages:
notif_text = "\n".join(
f"[bg:{n['task_id']}] {n['status']}: {n['result']}" for n in notifs
)
- messages.append({"role": "user", "content": f"\n{notif_text}\n"})
+ bg_block = {
+ "type": "text",
+ "text": f"\n{notif_text}\n",
+ }
+ last = messages[-1]
+ if last["role"] == "user":
+ if isinstance(last["content"], str):
+ last["content"] = [
+ {"type": "text", "text": last["content"]},
+ bg_block,
+ ]
+ else:
+ last["content"] = list(last["content"]) + [bg_block]
+ else:
+ messages.append({"role": "user", "content": [bg_block]})
response = client.messages.create(
model=MODEL, system=SYSTEM, messages=messages,
tools=TOOLS, max_tokens=8000,