Agent Zero AI framework
feat: Add chat branching plugin
keyboardstaff4633ebdd82d5
diff --git a/plugins/chat_branching/api/branch_chat.py b/plugins/chat_branching/api/branch_chat.pynew file mode 100644index 000000000..16655856a--- /dev/null+++ b/plugins/chat_branching/api/branch_chat.py@@ -0,0 +1,75 @@+from datetime import datetime++from python.helpers.api import ApiHandler, Input, Output, Request, Response+from python.helpers.persist_chat import (+ _serialize_context,+ _deserialize_context,+ save_tmp_chat,+)+from agent import AgentContext+++class BranchChat(ApiHandler):+ """Create a new chat branched from an existing chat at a specific log message."""++ async def process(self, input: Input, request: Request) -> Output:+ ctxid = input.get("context", "")+ log_no = input.get("log_no") # LogItem.no from frontend++ if not ctxid:+ return Response("Missing context id", 400)+ if log_no is None:+ return Response("Missing log_no", 400)++ context = AgentContext.get(ctxid)+ if not context:+ return Response("Context not found", 404)++ # Serialize the source context+ data = _serialize_context(context)++ # Remove id so _deserialize_context generates a new one+ 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 = None+ for i, item in enumerate(src_logs):+ if item["no"] == log_no:+ cut_idx = i+ break++ if 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_no+ else:+ return Response("log_no not found in chat log", 400)++ data["log"]["logs"] = src_logs[: cut_idx + 1]++ # Give the branch a distinguishable name+ src_name = data.get("name") or "Chat"+ data["name"] = f"{src_name} (branch)"+ data["created_at"] = datetime.now().isoformat()++ # Deserialize into a brand-new context (new id, fresh agent config)+ new_context = _deserialize_context(data)++ # Persist immediately+ save_tmp_chat(new_context)++ # Notify all tabs+ from python.helpers.state_monitor_integration import mark_dirty_all+ mark_dirty_all(reason="plugins.chat_branching.BranchChat")++ return {+ "ok": True,+ "ctxid": new_context.id,+ "message": "Chat branched successfully.",+ }\ No newline at end of filediff --git a/plugins/chat_branching/extensions/webui/set_messages_after_loop/inject-branch-buttons.js b/plugins/chat_branching/extensions/webui/set_messages_after_loop/inject-branch-buttons.jsnew file mode 100644index 000000000..27e8e33da--- /dev/null+++ b/plugins/chat_branching/extensions/webui/set_messages_after_loop/inject-branch-buttons.js@@ -0,0 +1,58 @@+// Chat Branching Plugin — injects a "branch" button into every message's action bar.+// Runs as a set_messages_after_loop JS extension.++import { createActionButton } from "/components/messages/action-buttons/simple-action-buttons.js";+import { callJsonApi } from "/js/api.js";++const BRANCH_ATTR = "data-branch-injected";+const LOG_NO_ATTR = "data-log-no";++/**+ * default export called by callJsExtensions("set_messages_after_loop", context)+ * context.messages is the raw log items array with { no, id, type, ... }+ */+export default async function injectBranchButtons(context) {+ if (!context?.messages?.length) return;++ // 1. Stamp every rendered element with its log "no" so the button can read it.+ for (const msg of context.messages) {+ const domId = msg.id || msg.no;+ // message containers use id="message-{id}", process steps use id="process-step-{id}"+ const el =+ document.getElementById(`message-${domId}`) ||+ document.getElementById(`process-step-${domId}`);+ if (el) el.setAttribute(LOG_NO_ATTR, String(msg.no));+ }++ // 2. Find every action-button bar that hasn't been patched yet and append a branch btn.+ const bars = document.querySelectorAll(`.step-action-buttons:not([${BRANCH_ATTR}])`);+ for (const bar of bars) {+ bar.setAttribute(BRANCH_ATTR, "1");++ // Resolve the log no from the nearest stamped ancestor+ const stamped = bar.closest(`[${LOG_NO_ATTR}]`);+ if (!stamped) continue;+ const logNo = Number(stamped.getAttribute(LOG_NO_ATTR));+ if (Number.isNaN(logNo)) continue;++ const btn = createActionButton("fork_right", "Branch chat", async () => {+ const ctxid = globalThis.getContext?.();+ if (!ctxid) throw new Error("No active chat");++ const res = await callJsonApi("/plugins/chat_branching/branch_chat", {+ context: ctxid,+ log_no: logNo,+ });++ if (!res?.ok) throw new Error(res?.message || "Branch failed");++ // Select the newly created branch chat+ const chatsStore = Alpine.store("chats");+ if (chatsStore) {+ chatsStore.selectChat(res.ctxid);+ }+ });++ if (btn) bar.appendChild(btn);+ }+}\ No newline at end of filediff --git a/plugins/chat_branching/plugin.yaml b/plugins/chat_branching/plugin.yamlnew file mode 100644index 000000000..bb382ed22--- /dev/null+++ b/plugins/chat_branching/plugin.yaml@@ -0,0 +1,4 @@+name: Chat Branching+description: Branch a chat from any message, creating a new chat with history up to that point.+version: 1.0.0+always_enabled: true\ No newline at end of file