Skip to content

Agent Zero AI framework

Detach provider state when branching chats

Alessandrobb5d305091de
diff --git a/plugins/_chat_branching/AGENTS.md b/plugins/_chat_branching/AGENTS.md
index b10df9993..37241d7fd 100644
--- a/plugins/_chat_branching/AGENTS.md
+++ b/plugins/_chat_branching/AGENTS.md
@@ -16,6 +16,9 @@
- Preserve UUID-based linking between log entries and history messages.
- Branched chats must include history only up to the selected message.
+- Detach inherited Responses continuation and response-ID ownership, while
+ retaining structured output metadata needed for local replay.
+- Clear cached Context Window state after trimming each cloned agent.
- Do not mutate the source chat while creating a branch.
## Work Guidance
@@ -24,6 +27,7 @@
## Verification
+- Run `conda run -n a0 pytest plugins/_chat_branching/tests`.
- Smoke-test branching from several message positions and confirm source chat remains unchanged.
## Child DOX Index
diff --git a/plugins/_chat_branching/README.md b/plugins/_chat_branching/README.md
index 2d4be43c5..0ac91a4f6 100644
--- a/plugins/_chat_branching/README.md
+++ b/plugins/_chat_branching/README.md
@@ -15,6 +15,8 @@ Adds a **Branch** button to every chat message. Clicking it clones the current c
- Serializes the source context → deserializes into a new context with a fresh ID.
- Walks log entries: keeps everything up to the selected `log_no`, discards the rest.
- Collects the IDs of kept entries and uses them to trim `history.messages` so log and history stay consistent.
+ - Detaches inherited provider-response state and clears the cached Context
+ Window so the branch rebuilds both from its trimmed history.
3. **Persist & refresh**
- Saves the branched chat immediately.
diff --git a/plugins/_chat_branching/api/branch_chat.py b/plugins/_chat_branching/api/branch_chat.py
index 56e418f78..47de4b990 100644
--- a/plugins/_chat_branching/api/branch_chat.py
+++ b/plugins/_chat_branching/api/branch_chat.py
@@ -1,5 +1,6 @@
import json
+from agent import Agent, AgentContext
from helpers.api import ApiHandler, Input, Output, Request, Response
from helpers.localization import Localization
from helpers.persist_chat import (
@@ -7,7 +8,20 @@ from helpers.persist_chat import (
_deserialize_context,
save_tmp_chat,
)
-from agent import AgentContext
+
+
+def _detach_response_ids(value: object) -> None:
+ if isinstance(value, dict):
+ metadata = value.get("metadata")
+ responses = metadata.get("responses") if isinstance(metadata, dict) else None
+ if isinstance(responses, dict):
+ responses.pop("response_id", None)
+ responses.pop("previous_response_id", None)
+ for nested in value.values():
+ _detach_response_ids(nested)
+ elif isinstance(value, list):
+ for nested in value:
+ _detach_response_ids(nested)
def _trim_history_json(history_json: str, kept_ids: set[str], after_cut_ids: set[str]) -> str:
@@ -71,6 +85,7 @@ def _trim_history_json(history_json: str, kept_ids: set[str], after_cut_ids: set
len(t.get("messages", [])) for t in hist["topics"] if not t.get("summary")
) + len(hist.get("current", {}).get("messages", []))
hist["counter"] = total
+ _detach_response_ids(hist)
return json.dumps(hist, ensure_ascii=False)
@@ -124,6 +139,10 @@ class BranchChat(ApiHandler):
ag["history"] = _trim_history_json(
ag.get("history", ""), kept_ids, after_cut_ids
)
+ agent_data = ag.get("data")
+ if isinstance(agent_data, dict):
+ agent_data.pop(Agent.DATA_NAME_RESPONSES_STATE, None)
+ agent_data.pop(Agent.DATA_NAME_CTX_WINDOW, None)
# Give the branch a distinguishable name
src_name = data.get("name") or "Chat"
diff --git a/plugins/_chat_branching/tests/test_branch_chat.py b/plugins/_chat_branching/tests/test_branch_chat.py
new file mode 100644
index 000000000..36ec4885a
--- /dev/null
+++ b/plugins/_chat_branching/tests/test_branch_chat.py
@@ -0,0 +1,123 @@
+import copy
+import json
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[3]
+if str(ROOT) not in sys.path:
+ sys.path.insert(0, str(ROOT))
+
+from helpers import state_monitor_integration
+from helpers.persist_chat import _collect_response_ids
+from plugins._chat_branching.api import branch_chat
+
+
+async def test_branch_rebuilds_provider_and_context_state_from_trimmed_history(
+ monkeypatch,
+):
+ history = json.dumps(
+ {
+ "_cls": "History",
+ "counter": 2,
+ "bulks": [],
+ "topics": [],
+ "current": {
+ "summary": "",
+ "messages": [
+ {
+ "id": "kept-message",
+ "content": "before",
+ "metadata": {
+ "responses": {
+ "response_id": "resp_kept",
+ "previous_response_id": "resp_previous",
+ "output_items": [{"type": "message"}],
+ }
+ },
+ },
+ {"id": "removed-message", "content": "after"},
+ ],
+ },
+ }
+ )
+ serialized = {
+ "id": "source-chat",
+ "name": "Source chat",
+ "log": {
+ "logs": [
+ {"no": 4, "id": "kept-message"},
+ {"no": 5, "id": "removed-message"},
+ ]
+ },
+ "agents": [
+ {
+ "history": history,
+ "data": {
+ "responses_state": {
+ "response_id": "resp_current",
+ "response_ids": ["resp_kept", "resp_current"],
+ },
+ "ctx_window": {"text": "source context"},
+ },
+ }
+ for _ in range(2)
+ ],
+ }
+
+ branched = []
+
+ monkeypatch.setattr(
+ branch_chat.AgentContext,
+ "get",
+ lambda context_id: object() if context_id == "source-chat" else None,
+ )
+ monkeypatch.setattr(
+ branch_chat,
+ "_serialize_context",
+ lambda _context: copy.deepcopy(serialized),
+ )
+
+ def deserialize(data):
+ branched.append(copy.deepcopy(data))
+ return SimpleNamespace(id="branch-chat")
+
+ monkeypatch.setattr(branch_chat, "_deserialize_context", deserialize)
+ monkeypatch.setattr(branch_chat, "save_tmp_chat", lambda _context: None)
+ monkeypatch.setattr(
+ state_monitor_integration,
+ "mark_dirty_all",
+ lambda **_kwargs: None,
+ )
+
+ result = await branch_chat.BranchChat.process(
+ None,
+ {"context": "source-chat", "log_no": 4},
+ None,
+ )
+
+ assert result["ctxid"] == "branch-chat"
+ assert len(branched) == 1
+ assert _collect_response_ids(branched[0]) == []
+ for agent_data in branched[0]["agents"]:
+ assert "ctx_window" not in agent_data["data"]
+ assert "responses_state" not in agent_data["data"]
+ trimmed = json.loads(agent_data["history"])
+ messages = trimmed["current"]["messages"]
+ assert [message["id"] for message in messages] == ["kept-message"]
+ responses = messages[0]["metadata"]["responses"]
+ assert "response_id" not in responses
+ assert "previous_response_id" not in responses
+ assert responses["output_items"] == [{"type": "message"}]
+
+ assert serialized["agents"][0]["data"]["responses_state"]["response_id"] == (
+ "resp_current"
+ )
+ original_message = json.loads(serialized["agents"][0]["history"])["current"][
+ "messages"
+ ][0]
+ assert original_message["metadata"]["responses"]["response_id"] == "resp_kept"