AI conversation branches
Branching AI conversation workspace with inline message editing, version steppers, tailored fork replies and a clickable branch tree.
pnpm dlx shadcn@latest add @haze/ai-branches---
import { Check, ChevronLeft, ChevronRight, Pencil, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface BranchTurn {
role: "user" | "assistant";
text: string;
}
interface ConversationBranch {
id: string;
label: string;
parentId: string | null;
forkTurnIndex: number;
turns: BranchTurn[];
}
interface Props {
id?: string;
title?: string;
branches?: ConversationBranch[];
class?: string;
}
const {
id = "haze-ai-branches",
title = "Trip planning",
branches = [
{
id: "main",
label: "Zurich to Milan · Regional rail",
parentId: null,
forkTurnIndex: 0,
turns: [
{
role: "user",
text: "Plan three days from Zurich to Milan in early October.",
},
{
role: "assistant",
text: "Day 1: Morning train to Chur, cross the Albula pass to St. Moritz, dinner by the lake.\nDay 2: Descend via Tirano, afternoon espresso along Lake Como.\nDay 3: Regional rail into Milano Centrale, walk Brera and Navigli.",
},
{
role: "user",
text: "Make day 3 quieter and closer to the water.",
},
{
role: "assistant",
text: "Skip central Milan until dusk. Take the morning ferry from Varenna to Bellagio, walk the Villa Melzi gardens, and linger over lakeside lunch before the 18:20 regional train south.",
},
],
},
{
id: "mountain-pass",
label: "Day 3 · Lugano detour",
parentId: "main",
forkTurnIndex: 2,
turns: [
{
role: "user",
text: "Plan three days from Zurich to Milan in early October.",
},
{
role: "assistant",
text: "Day 1: Morning train to Chur, cross the Albula pass to St. Moritz, dinner by the lake.\nDay 2: Descend via Tirano, afternoon espresso along Lake Como.\nDay 3: Regional rail into Milano Centrale, walk Brera and Navigli.",
},
{
role: "user",
text: "Keep lodging near stations with fast transfers under 20 minutes.",
},
{
role: "assistant",
text: "Stay beside Chur Bahnhof on night one and Como San Giovanni on night two. Every connection stays on Saver Day Passes with 14 to 18 minute platform transfers into Milano Centrale.",
},
],
},
{
id: "geneva-turin",
label: "Alternate · Geneva to Turin",
parentId: "main",
forkTurnIndex: 0,
turns: [
{
role: "user",
text: "Plan three days from Geneva to Turin by mountain rail.",
},
{
role: "assistant",
text: "Day 1: Rhone valley train to Brig, evening stroll through the old town.\nDay 2: Cross the Simplon pass into Domodossola, local wine bar for dinner.\nDay 3: Morning train to Torino Porta Nuova, visit the cinema museum and Piazza Vittorio.",
},
],
},
],
class: className,
} = Astro.props;
const activeBranch = branches[0];
const rootSiblingCount = new Set(branches.map((b) => b.turns[0]?.text ?? "")).size;
const turn2Siblings = branches.filter(
(b) => b.turns.length > 2 && b.turns[0]?.text === activeBranch?.turns[0]?.text,
);
const turn2Count = new Set(turn2Siblings.map((b) => b.turns[2]?.text ?? "")).size;
---
<section
aria-labelledby={`${id}-title`}
data-haze-ai-branches
data-initial-branches={JSON.stringify(branches)}
data-instance-id={id}
class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
<div class="mx-auto max-w-xl overflow-hidden rounded-2xl border border-border bg-card shadow-key">
<header class="flex items-center justify-between gap-3 border-b border-border px-5 py-3.5">
<h2 id={`${id}-title`} class="truncate text-sm/5 font-semibold tracking-tight text-foreground">
{title}
</h2>
<span data-branch-count class="shrink-0 text-xs/4 text-muted-foreground tabular-nums">
{branches.length} {branches.length === 1 ? "branch" : "branches"}
</span>
</header>
<div class="grid grid-cols-1 sm:grid-cols-[minmax(0,1fr)_7rem]">
<div class="min-w-0 p-5 sm:p-6">
<ol role="list" data-branch-thread class="space-y-5">
{
activeBranch?.turns.map((turn, idx) => (
<li class={cn("flex min-w-0 flex-col gap-1.5", turn.role === "user" ? "items-end" : "items-start")}>
{turn.role === "user" ? (
<div class="flex w-full flex-col items-end gap-1.5">
<div class="max-w-[88%] rounded-2xl bg-muted px-4 py-2.5 text-sm/6 break-words text-foreground">
{turn.text}
</div>
<div class="flex items-center justify-end gap-1 text-xs text-muted-foreground">
{(idx === 0 ? rootSiblingCount : idx === 2 ? turn2Count : 1) > 1 && (
<div class="inline-flex items-center gap-0.5">
<button
type="button"
aria-label="Previous version"
disabled
class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-35 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<ChevronLeft class="size-3.5" aria-hidden="true" />
</button>
<span class="px-1 text-xs text-muted-foreground tabular-nums">
1/{idx === 0 ? rootSiblingCount : turn2Count}
</span>
<button
type="button"
aria-label="Next version"
class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-35 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<ChevronRight class="size-3.5" aria-hidden="true" />
</button>
</div>
)}
<button
type="button"
data-branch-edit={idx}
aria-label="Edit message"
class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground/70 transition-colors duration-150 ease-snappy hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<Pencil class="size-3" aria-hidden="true" />
</button>
</div>
</div>
) : (
<div class="w-full space-y-1 text-sm/6 break-words text-pretty text-foreground">
{turn.text.split("\n").map((line) => (
<p>{line}</p>
))}
</div>
)}
</li>
))
}
</ol>
</div>
<aside
aria-label="Conversation branch tree"
class="flex items-start justify-center border-t border-border bg-muted/15 px-3 py-5 sm:border-t-0 sm:border-l"
>
<div data-branch-graph class="relative h-56 w-16 shrink-0">
<svg
data-branch-svg
viewBox="0 0 64 216"
class="pointer-events-none size-full overflow-visible"
aria-hidden="true"
>
<path d="M 16 14 C 16 32, 48 30, 48 52 L 48 92" fill="none" class="stroke-border-strong stroke-[1.5]" />
<path d="M 16 92 C 16 110, 34 108, 34 130 L 34 170" fill="none" class="stroke-border-strong stroke-[1.5]" />
<path d="M 16 14 L 16 170" fill="none" class="stroke-foreground stroke-[1.75]" />
<circle cx="16" cy="14" r="3.5" class="fill-card stroke-foreground stroke-[1.75]" />
<circle cx="16" cy="52" r="3.5" class="fill-card stroke-foreground stroke-[1.75]" />
<circle cx="16" cy="92" r="4" class="fill-foreground" />
<circle cx="16" cy="130" r="3.5" class="fill-card stroke-foreground stroke-[1.75]" />
<circle cx="16" cy="170" r="4" class="fill-foreground" />
<circle cx="34" cy="130" r="3" class="fill-card stroke-border-strong stroke-[1.5]" />
<circle cx="34" cy="170" r="3.5" class="fill-muted-foreground/50" />
<circle cx="48" cy="52" r="3" class="fill-card stroke-border-strong stroke-[1.5]" />
<circle cx="48" cy="92" r="3.5" class="fill-muted-foreground/50" />
</svg>
<div data-branch-nodes class="absolute inset-0"></div>
</div>
</aside>
</div>
<p data-branch-status role="status" class="sr-only"></p>
</div>
<template data-tpl-icons>
<span data-icon-prev><ChevronLeft class="size-3.5" aria-hidden="true" /></span>
<span data-icon-next><ChevronRight class="size-3.5" aria-hidden="true" /></span>
<span data-icon-edit><Pencil class="size-3" aria-hidden="true" /></span>
<span data-icon-check><Check class="size-3.5" aria-hidden="true" /></span>
<span data-icon-close><X class="size-3.5" aria-hidden="true" /></span>
</template>
</section>
<script>
interface BranchTurn {
role: "user" | "assistant";
text: string;
}
interface ConversationBranch {
id: string;
label: string;
parentId: string | null;
forkTurnIndex: number;
turns: BranchTurn[];
}
const SVG_NS = "http://www.w3.org/2000/svg";
function initAiBranches() {
document.querySelectorAll<HTMLElement>("[data-haze-ai-branches]").forEach((root) => {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const raw = root.dataset.initialBranches;
const instanceId = root.dataset.instanceId ?? "haze-ai-branches";
const threadEl = root.querySelector<HTMLOListElement>("[data-branch-thread]");
const countEl = root.querySelector<HTMLElement>("[data-branch-count]");
const graphEl = root.querySelector<HTMLElement>("[data-branch-graph]");
const svgEl = root.querySelector<SVGSVGElement>("[data-branch-svg]");
const nodesLayer = root.querySelector<HTMLElement>("[data-branch-nodes]");
const statusEl = root.querySelector<HTMLElement>("[data-branch-status]");
const iconTpl = root.querySelector<HTMLTemplateElement>("[data-tpl-icons]");
if (!raw || !threadEl || !svgEl || !nodesLayer || !graphEl) return;
let branches: ConversationBranch[] = [];
try {
branches = JSON.parse(raw) as ConversationBranch[];
} catch {
return;
}
if (branches.length === 0) return;
let activeId = branches[0].id;
let editingTurnIndex: number | null = null;
const cloneIcon = (selector: string): Node | null => {
const node = iconTpl?.content.querySelector(selector)?.firstElementChild;
return node ? node.cloneNode(true) : null;
};
const makeShortLabel = (prompt: string, index: number): string => {
const words = prompt
.replace(/[^\p{L}\p{N}\s]/gu, " ")
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 3);
const suffix = words.length > 0 ? words.join(" ") : "Custom edit";
const capped = suffix.charAt(0).toUpperCase() + suffix.slice(1);
return `Branch ${index} · ${capped}`;
};
const buildTailoredReply = (prompt: string, turnIndex: number): string => {
const lower = prompt.toLowerCase();
if (lower.includes("bike") || lower.includes("cycl")) {
return "Day 1: Regional train to Thusis, cycle the Albula valley with luggage courier.\nDay 2: Descend toward Chiavenna, lakeside stop near Gravedona.\nDay 3: Ferry across to Varenna and roll into Milan by late afternoon.";
}
if (lower.includes("food") || lower.includes("dinner") || lower.includes("wine") || lower.includes("coffee")) {
return "Swap the express stop for a Valtellina lunch in Tirano, espresso overlooking Varenna harbor, and a late dinner table in Milan Brera.";
}
if (lower.includes("fast") || lower.includes("direct") || lower.includes("short") || lower.includes("quick")) {
return "Take the direct morning EuroCity from Zurich HB to Milano Centrale in 3h 17m, leaving two full days for galleries and neighborhood walks.";
}
if (turnIndex === 0) {
return `Day 1: Morning departure tailored around "${prompt}".\nDay 2: Slow scenic transit leg with local stops.\nDay 3: Flexible afternoon arrival with easy rail connections.`;
}
return `Adjusted day 3 for "${prompt}": shifted departure times, kept transfers unhurried, and balanced transit with time outdoors.`;
};
const getSiblingsAtTurn = (branch: ConversationBranch, turnIndex: number): ConversationBranch[] => {
return branches.filter((candidate) => {
if (candidate.turns.length <= turnIndex) return false;
for (let i = 0; i < turnIndex; i++) {
if (candidate.turns[i]?.text !== branch.turns[i]?.text) return false;
}
return true;
});
};
const renderGraph = (current: ConversationBranch) => {
const colSpacing = 26;
const rowSpacing = 40;
const topY = 14;
const leftX = 16;
const maxTurns = Math.max(4, ...branches.map((b) => b.turns.length));
const viewW = Math.max(84, leftX * 2 + (branches.length - 1) * colSpacing);
const viewH = topY + maxTurns * rowSpacing + 18;
svgEl.setAttribute("viewBox", `0 0 ${viewW} ${viewH}`);
graphEl.style.width = `${Math.max(84, viewW)}px`;
graphEl.style.height = `${viewH}px`;
const svgFrag = document.createDocumentFragment();
const btnFrag = document.createDocumentFragment();
const makeEl = (tag: string, attrs: Record<string, string>, cls: string): SVGElement => {
const el = document.createElementNS(SVG_NS, tag);
Object.entries(attrs).forEach(([k, v]) => el.setAttribute(k, v));
el.setAttribute("class", cls);
return el;
};
// Draw inactive branches first, active branch on top
const ordered = [
...branches.map((b, idx) => ({ b, idx })).filter(({ b }) => b.id !== current.id),
...branches.map((b, idx) => ({ b, idx })).filter(({ b }) => b.id === current.id),
];
ordered.forEach(({ b, idx }) => {
const isCurrent = b.id === current.id;
const x = leftX + idx * colSpacing;
const forkRow = idx === 0 ? 0 : Math.max(0, b.forkTurnIndex);
const startY = topY + forkRow * rowSpacing;
const firstNodeY = topY + (forkRow + 1) * rowSpacing;
const lastNodeY = topY + b.turns.length * rowSpacing;
const parentIdx = b.parentId ? Math.max(0, branches.findIndex((p) => p.id === b.parentId)) : 0;
const parentX = leftX + parentIdx * colSpacing;
const strokeCls = isCurrent
? "fill-none stroke-foreground stroke-[1.75]"
: "fill-none stroke-border-strong stroke-[1.5]";
// If this is the active branch and it forked off a parent, highlight the shared trunk too
if (isCurrent && idx > 0) {
const trunk = makeEl("path", { d: `M ${parentX} ${topY} L ${parentX} ${startY}` }, strokeCls);
svgFrag.append(trunk);
}
if (idx === 0) {
const trunk = makeEl("path", { d: `M ${x} ${topY} L ${x} ${lastNodeY}` }, strokeCls);
svgFrag.append(trunk);
} else {
const midY = startY + rowSpacing * 0.55;
const d = `M ${parentX} ${startY} C ${parentX} ${midY}, ${x} ${midY - 6}, ${x} ${firstNodeY} L ${x} ${lastNodeY}`;
const curve = makeEl("path", { d }, strokeCls);
svgFrag.append(curve);
}
});
// Root node at top of trunk
svgFrag.append(
makeEl(
"circle",
{ cx: String(leftX), cy: String(topY), r: "3.5" },
"fill-card stroke-foreground stroke-[1.75]",
),
);
// Draw branch nodes and interactive buttons at each branch's leaf + fork point
ordered.forEach(({ b, idx }) => {
const isCurrent = b.id === current.id;
const x = leftX + idx * colSpacing;
const startTurn = idx === 0 ? 0 : Math.max(0, b.forkTurnIndex);
if (isCurrent && idx > 0) {
const parentIdx = b.parentId ? Math.max(0, branches.findIndex((p) => p.id === b.parentId)) : 0;
const parentX = leftX + parentIdx * colSpacing;
for (let t = 0; t < startTurn; t++) {
const y = topY + (t + 1) * rowSpacing;
const isUser = b.turns[t]?.role === "user";
const sharedCls = isUser ? "fill-card stroke-foreground stroke-[1.75]" : "fill-foreground";
svgFrag.append(
makeEl("circle", { cx: String(parentX), cy: String(y), r: isUser ? "3.25" : "4" }, sharedCls),
);
}
}
for (let t = startTurn; t < b.turns.length; t++) {
const y = topY + (t + 1) * rowSpacing;
const isUser = b.turns[t].role === "user";
const cls = isCurrent
? isUser
? "fill-card stroke-foreground stroke-[1.75]"
: "fill-foreground"
: isUser
? "fill-card stroke-border-strong stroke-[1.5]"
: "fill-muted-foreground/50";
svgFrag.append(
makeEl("circle", { cx: String(x), cy: String(y), r: isCurrent && !isUser ? "4" : "3.25" }, cls),
);
}
// Interactive accessible button positioned at the branch's leaf node
const leafY = topY + b.turns.length * rowSpacing;
const btn = document.createElement("button");
btn.type = "button";
btn.setAttribute("aria-label", `Switch to ${b.label}`);
btn.title = b.label;
if (isCurrent) btn.setAttribute("aria-current", "true");
btn.style.left = `${(x / viewW) * 100}%`;
btn.style.top = `${(leafY / viewH) * 100}%`;
btn.className =
"absolute -translate-x-1/2 -translate-y-1/2 size-6 cursor-pointer rounded-full bg-transparent transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
btn.addEventListener("click", () => {
activeId = b.id;
editingTurnIndex = null;
render(`Switched to ${b.label}.`);
});
btnFrag.append(btn);
});
svgEl.replaceChildren(svgFrag);
nodesLayer.replaceChildren(btnFrag);
};
const render = (announce?: string) => {
const current = branches.find((b) => b.id === activeId) ?? branches[0];
activeId = current.id;
if (countEl) {
countEl.textContent = `${branches.length} ${branches.length === 1 ? "branch" : "branches"}`;
}
if (announce && statusEl) {
statusEl.textContent = announce;
}
const threadFrag = document.createDocumentFragment();
current.turns.forEach((turn, idx) => {
const li = document.createElement("li");
li.className = `flex min-w-0 flex-col gap-1.5 ${turn.role === "user" ? "items-end" : "items-start"}`;
if (turn.role === "user") {
const wrapper = document.createElement("div");
wrapper.className = "flex w-full flex-col items-end gap-1.5";
if (editingTurnIndex === idx) {
const form = document.createElement("form");
form.className = "w-full rounded-2xl border border-border bg-muted/40 p-3";
const label = document.createElement("label");
const textareaId = `${instanceId}-edit-${idx}`;
label.htmlFor = textareaId;
label.className = "mb-1.5 block text-xs font-medium text-muted-foreground";
label.textContent = "Edit prompt to fork a new branch";
const textarea = document.createElement("textarea");
textarea.id = textareaId;
textarea.rows = 2;
textarea.value = turn.text;
textarea.className =
"w-full resize-y rounded-lg border border-frame-input bg-field px-3 py-2 text-sm/6 text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden";
const actions = document.createElement("div");
actions.className = "mt-2 flex flex-wrap items-center justify-end gap-1.5";
const cancelBtn = document.createElement("button");
cancelBtn.type = "button";
cancelBtn.className =
"inline-flex h-8 cursor-pointer items-center gap-1 rounded-full border border-frame bg-field px-3 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const closeIcon = cloneIcon("[data-icon-close]");
if (closeIcon) cancelBtn.append(closeIcon);
cancelBtn.append(document.createTextNode("Cancel"));
cancelBtn.addEventListener("click", () => {
editingTurnIndex = null;
render("Edit cancelled.");
});
const saveBtn = document.createElement("button");
saveBtn.type = "submit";
saveBtn.className =
"inline-flex h-8 cursor-pointer items-center gap-1 rounded-full bg-primary px-3 text-xs font-medium text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-90 active:scale-95 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const checkIcon = cloneIcon("[data-icon-check]");
if (checkIcon) saveBtn.append(checkIcon);
saveBtn.append(document.createTextNode("Fork"));
form.addEventListener("submit", (ev) => {
ev.preventDefault();
const nextText = textarea.value.trim();
if (!nextText) return;
const prefixTurns = current.turns.slice(0, idx).map((t) => ({ ...t }));
const newBranchNum = branches.length + 1;
const newBranch: ConversationBranch = {
id: `branch-${Date.now()}-${newBranchNum}`,
label: makeShortLabel(nextText, newBranchNum),
parentId: current.id,
forkTurnIndex: idx,
turns: [
...prefixTurns,
{ role: "user", text: nextText },
{ role: "assistant", text: buildTailoredReply(nextText, idx) },
],
};
branches.push(newBranch);
activeId = newBranch.id;
editingTurnIndex = null;
render(`Created ${newBranch.label}. Total ${branches.length} branches.`);
});
actions.append(cancelBtn, saveBtn);
form.append(label, textarea, actions);
wrapper.append(form);
window.requestAnimationFrame(() => {
textarea.focus();
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
});
} else {
const bubble = document.createElement("div");
bubble.className = "max-w-[88%] rounded-2xl bg-muted px-4 py-2.5 text-sm/6 break-words text-foreground";
bubble.textContent = turn.text;
wrapper.append(bubble);
const controls = document.createElement("div");
controls.className = "flex items-center justify-end gap-1 text-xs text-muted-foreground";
const siblings = getSiblingsAtTurn(current, idx);
const distinctVersions: ConversationBranch[] = [];
const seenTexts = new Set<string>();
siblings.forEach((sib) => {
const key = sib.turns[idx]?.text ?? "";
if (!seenTexts.has(key)) {
seenTexts.add(key);
distinctVersions.push(sib);
}
});
if (distinctVersions.length > 1) {
const currentPos = Math.max(
0,
distinctVersions.findIndex((sib) => sib.turns[idx]?.text === turn.text),
);
const stepper = document.createElement("div");
stepper.className = "inline-flex items-center gap-0.5";
const prevBtn = document.createElement("button");
prevBtn.type = "button";
prevBtn.setAttribute("aria-label", "Previous version");
prevBtn.disabled = currentPos === 0;
prevBtn.className =
"inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-35 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const prevIcon = cloneIcon("[data-icon-prev]");
if (prevIcon) prevBtn.append(prevIcon);
prevBtn.addEventListener("click", () => {
const target = distinctVersions[currentPos - 1];
if (!target) return;
activeId = target.id;
editingTurnIndex = null;
render(`Switched to ${target.label} (${currentPos} of ${distinctVersions.length}).`);
});
const counter = document.createElement("span");
counter.className = "px-1 text-xs text-muted-foreground tabular-nums";
counter.textContent = `${currentPos + 1}/${distinctVersions.length}`;
const nextBtn = document.createElement("button");
nextBtn.type = "button";
nextBtn.setAttribute("aria-label", "Next version");
nextBtn.disabled = currentPos >= distinctVersions.length - 1;
nextBtn.className =
"inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-35 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const nextIcon = cloneIcon("[data-icon-next]");
if (nextIcon) nextBtn.append(nextIcon);
nextBtn.addEventListener("click", () => {
const target = distinctVersions[currentPos + 1];
if (!target) return;
activeId = target.id;
editingTurnIndex = null;
render(`Switched to ${target.label} (${currentPos + 2} of ${distinctVersions.length}).`);
});
stepper.append(prevBtn, counter, nextBtn);
controls.append(stepper);
}
const editBtn = document.createElement("button");
editBtn.type = "button";
editBtn.setAttribute("aria-label", "Edit message");
editBtn.className =
"inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground/70 transition-colors duration-150 ease-snappy hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const editIcon = cloneIcon("[data-icon-edit]");
if (editIcon) editBtn.append(editIcon);
editBtn.addEventListener("click", () => {
editingTurnIndex = idx;
render("Editing user message. Submit to create a new branch.");
});
controls.append(editBtn);
wrapper.append(controls);
}
li.append(wrapper);
} else {
const body = document.createElement("div");
body.className = "w-full space-y-1 text-sm/6 break-words text-pretty text-foreground";
turn.text.split("\n").forEach((line) => {
const p = document.createElement("p");
p.textContent = line;
body.append(p);
});
li.append(body);
}
threadFrag.append(li);
});
threadEl.replaceChildren(threadFrag);
renderGraph(current);
};
render();
});
}
initAiBranches();
document.addEventListener("astro:page-load", initAiBranches);
</script>When to use
- Letting users explore alternate directions from an earlier chat turn without losing the original thread
- Comparing multiple prompt variations side by side through version steppers and a branch tree sidebar
When not to use
- You only need a linear multi-turn conversation without prompt forking; use ai-chat instead
- You want token-level wording alternatives rather than full conversation forks; use ai-token-alternatives
Installation
Add the Haze registry to components.json once, then install AI conversation branches with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-branchesnpx shadcn@latest add @haze/ai-branchesyarn dlx shadcn@latest add @haze/ai-branchesbunx --bun shadcn@latest add @haze/ai-branchesFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | "haze-ai-branches" | Unique prefix for headings and inline edit inputs. |
| title | string | "Trip planning" | Workspace title shown in the card header. |
| branches | ConversationBranch[] | 3 demo branches | Initial conversation forks with parent links and turns. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- Tab
- Move across version steppers, Edit message buttons, inline edit forms and branch tree nodes
- EnterSpace
- Step between versions, open inline prompt editing, save a new fork or switch branches
Accessibility
- Version steppers expose explicit Previous version and Next version labels, while the active node in the Branches tree sets aria-current="true".
- Branch creation, edit cancellation, and path switches are announced in a polite role="status" live region.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI block "AI conversation branches" with `npx shadcn@latest add @haze/ai-branches`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiBranches from "@/components/haze/blocks/ai-branches.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/blocks/ai-branches.md
Customize with real content
Adapt the Haze ai-branches block for our product. Replace the demo values of these props with our real content: id, title, branches, class. Keep the layout, the heading level rules and these accessibility details: Version steppers expose explicit Previous version and Next version labels, while the active node in the Branches tree sets aria-current="true". Branch creation, edit cancellation, and path switches are announced in a polite role="status" live region. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ai-branches, check it fits: use it when letting users explore alternate directions from an earlier chat turn without losing the original thread; comparing multiple prompt variations side by side through version steppers and a branch tree sidebar. Avoid it when you only need a linear multi-turn conversation without prompt forking; use ai-chat instead; you want token-level wording alternatives rather than full conversation forks; use ai-token-alternatives. Alternatives: @haze/ai-chat, @haze/ai-token-alternatives, @haze/chat-thread.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.