| 1 | # Chat Branching |
| 2 | |
| 3 | Create a new chat from any existing point in a conversation. |
| 4 | |
| 5 | ## What It Does |
| 6 | |
| 7 | Adds a **Branch** button to every chat message. Clicking it clones the current chat up to that message, creating a new conversation you can continue independently. |
| 8 | |
| 9 | ## How It Works |
| 10 | |
| 11 | 1. **ID-based log ↔ history linking** |
| 12 | Every `LogItem` and `history.Message` share a UUID generated at creation time. The branch button is only shown on messages that carry this ID. |
| 13 | |
| 14 | 2. **Clone & trim** |
| 15 | - Serializes the source context → deserializes into a new context with a fresh ID. |
| 16 | - Walks log entries: keeps everything up to the selected `log_no`, discards the rest. |
| 17 | - Collects the IDs of kept entries and uses them to trim `history.messages` so log and history stay consistent. |
| 18 | - Detaches inherited provider-response state and clears the cached Context |
| 19 | Window so the branch rebuilds both from its trimmed history. |
| 20 | |
| 21 | 3. **Persist & refresh** |
| 22 | - Saves the branched chat immediately. |
| 23 | - Marks UI state dirty so all connected tabs see the new branch. |
| 24 | |
| 25 | ## Entry Points |
| 26 | |
| 27 | | Path | Purpose | |
| 28 | |---|---| |
| 29 | | `api/branch_chat.py` | API endpoint — clone, trim, persist | |
| 30 | | `extensions/webui/set_messages_after_loop/inject-branch-buttons.js` | Injects the Branch button into each message DOM element | |
| 31 | |
| 32 | ## Plugin Metadata |
| 33 | |
| 34 | - **Name**: `_chat_branching` |
| 35 | - **Title**: `Chat Branching` |
| 36 | - **Description**: Branch a chat from any message, creating a new chat with history up to that point. |