Agent Zero AI framework
fix(chat_branching): not trimming agent history
keyboardstaffaafe7f4aa886
diff --git a/plugins/_chat_branching/api/branch_chat.py b/plugins/_chat_branching/api/branch_chat.pyindex e427ab161..e9f652c35 100644--- a/plugins/_chat_branching/api/branch_chat.py+++ b/plugins/_chat_branching/api/branch_chat.py@@ -1,3 +1,4 @@+import jsonfrom datetime import datetimefrom helpers.api import ApiHandler, Input, Output, Request, Response@@ -8,6 +9,57 @@ from helpers.persist_chat import ()from agent import AgentContext+# Log types that produce a history message (via hist_add_* in Agent)+_HIST_LOG_TYPES = {"user", "agent", "tool", "warning"}+++def _count_history_msgs(logs, agent_no):+ """Count log items that produced history messages for a specific agent."""+ return sum(+ 1 for item in logs+ if item["type"] in _HIST_LOG_TYPES and item.get("agentno", 0) == agent_no+ )+++def _trim_history_json(history_json, keep_count):+ """Trim a serialized history JSON string to keep only the first+ *keep_count* un-summarized messages. Summarized bulks/topics are+ always preserved (they represent older history before any cut point)."""+ if not history_json:+ return history_json+ hist = json.loads(history_json)++ # Flatten messages from topics + current, count and trim+ remaining = keep_count+ trimmed_topics = []++ for topic in hist.get("topics", []):+ if topic.get("summary"):+ # Summarized topic — keep whole, don't count+ trimmed_topics.append(topic)+ continue+ msgs = topic.get("messages", [])+ if remaining >= len(msgs):+ trimmed_topics.append(topic)+ remaining -= len(msgs)+ elif remaining > 0:+ topic["messages"] = msgs[:remaining]+ trimmed_topics.append(topic)+ remaining = 0+ # else: drop entirely++ hist["topics"] = trimmed_topics++ # Trim current topic+ current = hist.get("current", {})+ if not current.get("summary"):+ msgs = current.get("messages", [])+ if remaining < len(msgs):+ current["messages"] = msgs[:remaining]++ hist["counter"] = keep_count+ return json.dumps(hist, ensure_ascii=False)+class BranchChat(ApiHandler):"""Create a new chat branched from an existing chat at a specific log message."""@@ -32,9 +84,6 @@ class BranchChat(ApiHandler):del data["id"]# Trim log entries: keep only items up to and including log_no.- # _serialize_log uses log.logs[-LOG_SIZE:], so the serialized "no"- # values may start above 0 for long chats. We match against the- # original "no" field that each LogItem.output() emits.src_logs = data["log"]["logs"]cut_idx = Nonefor i, item in enumerate(src_logs):@@ -43,15 +92,18 @@ class BranchChat(ApiHandler):breakif cut_idx is None:- # Fallback: log_no might already be a 0-based index within the- # serialized array (e.g. after a reload where _deserialize_log- # resets "no" to sequential). Accept if within bounds.if 0 <= log_no < len(src_logs):cut_idx = log_noelse:return Response("log_no not found in chat log", 400)- data["log"]["logs"] = src_logs[: cut_idx + 1]+ kept_logs = src_logs[: cut_idx + 1]+ data["log"]["logs"] = kept_logs++ # Trim agent history to match the log cut point+ for ag in data.get("agents", []):+ msg_count = _count_history_msgs(kept_logs, ag["number"])+ ag["history"] = _trim_history_json(ag.get("history", ""), msg_count)# Give the branch a distinguishable namesrc_name = data.get("name") or "Chat"