AI chat
Conversational AI workspace with thread switcher, collapsible reasoning, tool chips, source cards, feedback actions and stop control.
pnpm dlx shadcn@latest add @haze/ai-chat---
import { ArrowUp, Bot, Check, ChevronDown, Copy, Plus, RotateCw, Sparkles, Square, ThumbsDown, ThumbsUp, Wrench } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Thread {
id: string;
title: string;
updated: string;
}
interface Source {
label: string;
domain: string;
}
interface Message {
id: string;
role: "user" | "assistant";
content: string;
reasoning?: string;
tools?: string[];
sources?: Source[];
}
interface Props {
id?: string;
title?: string;
models?: string[];
threads?: Thread[];
messages?: Message[];
placeholder?: string;
class?: string;
}
const {
id = "haze-ai-chat",
title = "Workspace assistant",
models = ["Sonnet 4.5", "Opus 4.5", "Flash 3.8"],
threads = [
{ id: "t1", title: "Q4 checkout latency spike", updated: "2m ago" },
{ id: "t2", title: "Migrate billing webhooks", updated: "1h ago" },
{ id: "t3", title: "Draft release notes v2.8", updated: "Yesterday" },
],
messages = [
{
id: "m1",
role: "user",
content: "Why did p95 checkout latency jump after yesterday's deploy?",
},
{
id: "m2",
role: "assistant",
reasoning: "Checked the 24h trace histogram for /api/checkout, correlated deploy sha 9f3c2a1, and inspected the Stripe tax calculation middleware added in PR 418.",
tools: ["query_traces(/api/checkout)", "inspect_pr(418)"],
content: "The p95 increase from 180 ms to 490 ms started 4 minutes after deploy 9f3c2a1. PR 418 moved tax-rate resolution into the synchronous request path without caching postal lookups. Caching normalized postal prefixes in KV recovers ~290 ms.",
sources: [
{ label: "PR 418 diff", domain: "github.com" },
{ label: "Checkout trace 8841", domain: "traces.internal" },
],
},
],
placeholder = "Ask a follow-up or reference a PR…",
class: className,
} = Astro.props;
---
<section aria-labelledby={`${id}-title`} data-haze-ai-chat class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}>
<div class="mx-auto grid max-w-5xl overflow-hidden rounded-2xl border border-border bg-card lg:grid-cols-[15rem_minmax(0,1fr)]">
<aside aria-label="Conversations" class="flex min-w-0 flex-col border-b border-border bg-muted/40 p-3 lg:border-r lg:border-b-0">
<div class="flex items-center justify-between gap-2 px-1 pb-2">
<span class="text-xs/4 font-medium tracking-wider text-muted-foreground uppercase">Threads</span>
<button
type="button"
data-chat-new
class="inline-flex h-7 cursor-pointer items-center gap-1 rounded-md border border-frame bg-field px-2 text-xs/4 font-medium text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
>
<Plus class="size-3.5" aria-hidden="true" />
New
</button>
</div>
<ul role="list" class="flex gap-1 overflow-x-auto lg:flex-col">
{
threads.map((thread, idx) => (
<li class="shrink-0 lg:shrink">
<button
type="button"
data-chat-thread={thread.id}
aria-current={idx === 0 ? "true" : undefined}
class="flex w-full cursor-pointer flex-col items-start rounded-lg px-2.5 py-2 text-left transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-[current=true]:bg-accent aria-[current=true]:text-foreground active:scale-[0.97] active:duration-75"
>
<span class="max-w-44 truncate text-[0.8125rem]/5 font-medium text-foreground">{thread.title}</span>
<span class="text-[0.6875rem]/4 text-muted-foreground">{thread.updated}</span>
</button>
</li>
))
}
</ul>
</aside>
<div class="flex min-w-0 flex-col">
<header class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3 sm:px-5">
<div class="flex min-w-0 items-center gap-2">
<span class="grid size-7 shrink-0 place-items-center rounded-lg border border-frame bg-muted text-foreground" aria-hidden="true">
<Sparkles class="size-3.5" />
</span>
<h2 id={`${id}-title`} class="truncate text-sm/5 font-semibold tracking-tight text-foreground">{title}</h2>
</div>
<div class="flex items-center gap-2">
<label for={`${id}-model`} class="sr-only">Model</label>
<select
id={`${id}-model`}
data-chat-model
class="h-8 cursor-pointer rounded-lg border border-frame bg-field px-2.5 text-xs font-medium text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden"
>
{models.map((m) => <option value={m}>{m}</option>)}
</select>
</div>
</header>
<ol data-chat-log role="list" class="flex flex-1 flex-col gap-5 px-4 py-5 sm:px-6">
{
messages.map((msg) => (
<li data-chat-msg={msg.role} class={cn("flex flex-col gap-2", msg.role === "user" ? "items-end" : "items-start")}>
{msg.role === "user" ? (
<div class="max-w-[85%] rounded-2xl rounded-br-sm border border-border bg-muted px-4 py-2.5 text-sm/6 text-foreground">
{msg.content}
</div>
) : (
<div class="w-full max-w-2xl space-y-3">
{msg.reasoning && (
<details class="group rounded-xl border border-border bg-muted/40 px-3.5 py-2.5 text-xs/5 text-muted-foreground">
<summary class="flex cursor-pointer list-none items-center gap-1.5 font-medium text-foreground select-none focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
<Bot class="size-3.5 text-muted-foreground" aria-hidden="true" />
<span>Thought for 2.1s</span>
<ChevronDown class="ml-auto size-3.5 text-muted-foreground transition-transform duration-150 ease-snappy group-open:rotate-180" aria-hidden="true" />
</summary>
<p class="mt-2 border-t border-border pt-2 text-pretty">{msg.reasoning}</p>
</details>
)}
{msg.tools && msg.tools.length > 0 && (
<div class="flex flex-wrap gap-1.5">
{msg.tools.map((tool) => (
<span class="inline-flex items-center gap-1.5 rounded-md border border-border bg-muted/40 px-2 py-1 font-mono text-[0.6875rem]/4 text-muted-foreground">
<Wrench class="size-3 text-muted-foreground" aria-hidden="true" />
{tool}
</span>
))}
</div>
)}
<p class="text-sm/6 text-pretty text-foreground">{msg.content}</p>
{msg.sources && msg.sources.length > 0 && (
<div class="flex flex-wrap gap-2">
{msg.sources.map((src, i) => (
<span class="inline-flex items-center gap-1.5 rounded-lg border border-border bg-muted/40 px-2.5 py-1 text-xs/4 text-muted-foreground">
<span class="inline-flex size-4 items-center justify-center rounded-sm bg-muted font-mono text-[0.625rem] font-medium text-foreground">{i + 1}</span>
<span class="font-medium text-foreground">{src.label}</span>
<span class="text-[0.6875rem]">{src.domain}</span>
</span>
))}
</div>
)}
<div class="flex flex-wrap items-center gap-1 pt-0.5">
<button type="button" data-chat-copy={msg.content} aria-label="Copy response" class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97] active:duration-75">
<Copy class="size-3.5" aria-hidden="true" />
</button>
<button type="button" data-chat-rate="up" aria-pressed="false" aria-label="Helpful response" class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring aria-pressed:bg-success/14 aria-pressed:text-success active:scale-[0.97] active:duration-75">
<ThumbsUp class="size-3.5" aria-hidden="true" />
</button>
<button type="button" data-chat-rate="down" aria-pressed="false" aria-label="Unhelpful response" class="inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring aria-pressed:bg-destructive/14 aria-pressed:text-destructive active:scale-[0.97] active:duration-75">
<ThumbsDown class="size-3.5" aria-hidden="true" />
</button>
<button type="button" data-chat-retry class="inline-flex h-7 cursor-pointer items-center gap-1 rounded-md px-2 text-xs text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring active:scale-[0.97] active:duration-75">
<RotateCw class="size-3" aria-hidden="true" />
Retry
</button>
</div>
</div>
)}
</li>
))
}
</ol>
<form data-chat-form class="border-t border-border bg-muted/40 p-3 sm:p-4">
<div class="flex items-end gap-2 rounded-xl border border-frame-input bg-field p-2 has-[:is(input,textarea):focus-visible]:border-ring has-[:is(input,textarea):focus-visible]:ring-3 has-[:is(input,textarea):focus-visible]:ring-ring/24">
<label for={`${id}-input`} class="sr-only">Message</label>
<textarea
id={`${id}-input`}
data-chat-input
rows="1"
placeholder={placeholder}
class="min-h-9 flex-1 resize-none bg-transparent px-2 py-1.5 text-sm/6 text-foreground placeholder:text-muted-foreground outline-hidden"
></textarea>
<button
type="submit"
data-chat-send
aria-label="Send message"
class="inline-flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-lg bg-primary 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"
>
<ArrowUp class="size-4" aria-hidden="true" />
</button>
<button
type="button"
data-chat-stop
hidden
aria-label="Stop generating"
class="inline-flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-lg border border-frame-destructive bg-destructive/14 text-destructive transition-colors duration-150 hover:bg-destructive/20 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
>
<Square class="size-3.5 fill-current" aria-hidden="true" />
</button>
</div>
<p data-chat-status role="status" class="mt-2 min-h-4 text-xs/4 text-muted-foreground"></p>
</form>
</div>
</div>
</section>
<script>
function initAiChats() {
document.querySelectorAll<HTMLElement>("[data-haze-ai-chat]").forEach((root) => {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const form = root.querySelector<HTMLFormElement>("[data-chat-form]");
const input = root.querySelector<HTMLTextAreaElement>("[data-chat-input]");
const log = root.querySelector<HTMLOListElement>("[data-chat-log]");
const sendBtn = root.querySelector<HTMLButtonElement>("[data-chat-send]");
const stopBtn = root.querySelector<HTMLButtonElement>("[data-chat-stop]");
const status = root.querySelector<HTMLElement>("[data-chat-status]");
const modelSel = root.querySelector<HTMLSelectElement>("[data-chat-model]");
let timer: number | undefined;
const setStreaming = (on: boolean) => {
if (sendBtn) sendBtn.hidden = on;
if (stopBtn) stopBtn.hidden = !on;
};
root.querySelectorAll<HTMLButtonElement>("[data-chat-thread]").forEach((btn) => {
btn.addEventListener("click", () => {
root.querySelectorAll<HTMLButtonElement>("[data-chat-thread]").forEach((b) => b.removeAttribute("aria-current"));
btn.setAttribute("aria-current", "true");
if (status) status.textContent = `Switched to "${btn.querySelector("span")?.textContent ?? "thread"}".`;
});
});
root.querySelector<HTMLButtonElement>("[data-chat-new]")?.addEventListener("click", () => {
if (input) { input.value = ""; input.focus(); }
if (status) status.textContent = "Started a new draft conversation.";
});
root.addEventListener("click", (ev) => {
const target = ev.target as HTMLElement | null;
const copy = target?.closest<HTMLButtonElement>("[data-chat-copy]");
if (copy) {
navigator.clipboard?.writeText(copy.dataset.chatCopy ?? "").catch(() => {});
if (status) status.textContent = "Response copied.";
return;
}
const rate = target?.closest<HTMLButtonElement>("[data-chat-rate]");
if (rate) {
const next = rate.getAttribute("aria-pressed") !== "true";
rate.parentElement?.querySelectorAll<HTMLButtonElement>("[data-chat-rate]").forEach((b) => b.setAttribute("aria-pressed", "false"));
rate.setAttribute("aria-pressed", String(next));
if (status) status.textContent = next ? `Marked response as ${rate.dataset.chatRate === "up" ? "helpful" : "unhelpful"}.` : "Feedback cleared.";
return;
}
if (target?.closest("[data-chat-retry]")) {
if (status) status.textContent = `Regenerated with ${modelSel?.value ?? "selected model"}.`;
}
});
stopBtn?.addEventListener("click", () => {
if (timer) window.clearTimeout(timer);
setStreaming(false);
if (status) status.textContent = "Generation stopped.";
});
form?.addEventListener("submit", (ev) => {
ev.preventDefault();
const text = input?.value.trim();
if (!text || !log) return;
const userLi = document.createElement("li");
userLi.className = "flex flex-col items-end gap-2";
const bubble = document.createElement("div");
bubble.className = "max-w-[85%] rounded-2xl rounded-br-sm border border-border bg-muted px-4 py-2.5 text-sm/6 text-foreground";
bubble.textContent = text;
userLi.append(bubble);
log.append(userLi);
if (input) input.value = "";
setStreaming(true);
if (status) status.textContent = `Streaming reply from ${modelSel?.value ?? "model"}…`;
timer = window.setTimeout(() => {
const botLi = document.createElement("li");
botLi.className = "flex flex-col items-start gap-2";
const p = document.createElement("p");
p.className = "max-w-2xl text-sm/6 text-pretty text-foreground";
p.textContent = `Using ${modelSel?.value ?? "the selected model"}, I checked the workspace context for "${text}" and prepared a concise action plan ready to apply.`;
botLi.append(p);
log.append(botLi);
setStreaming(false);
if (status) status.textContent = "Reply complete.";
}, 550);
});
});
}
initAiChats();
document.addEventListener("astro:page-load", initAiChats);
</script>When to use
- Building a full workspace assistant where replies include reasoning steps, tool calls and cited sources
- Users need to switch between recent threads, pick a model and stop or regenerate answers
When not to use
- You only need a single prompt input bar without a message history; use ai-composer instead
- You want an editorial single-answer layout rather than a multi-turn chat; use ai-answer
Installation
Add the Haze registry to components.json once, then install AI chat with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-chatnpx shadcn@latest add @haze/ai-chatyarn dlx shadcn@latest add @haze/ai-chatbunx --bun shadcn@latest add @haze/ai-chatFirst 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-chat" | Unique prefix for headings and form controls. |
| title | string | "Workspace assistant" | Header title for the active chat workspace. |
| models | string[] | 3 demo models | Model choices shown in the header selector. |
| threads | { id: string; title: string; updated: string }[] | 3 demo threads | Sidebar conversation list. |
| messages | Message[] | 2 demo messages | Initial conversation turns with optional reasoning, tools and sources. |
| placeholder | string | "Ask a follow-up or reference a PR…" | Composer textarea placeholder. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- Tab
- Move across thread buttons, model select, reasoning disclosures, message actions and composer
- EnterSpace
- Toggle reasoning disclosure, rate a reply, switch threads or submit a message
Accessibility
- Reasoning uses a native details disclosure so keyboard and screen-reader users can expand or collapse thinking steps without script.
- Live status updates (thread switch, copy, feedback, streaming state) are announced through a polite role="status" 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 chat" with `npx shadcn@latest add @haze/ai-chat`. 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 AiChat from "@/components/haze/blocks/ai-chat.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-chat.md
Customize with real content
Adapt the Haze ai-chat block for our product. Replace the demo values of these props with our real content: id, title, models, threads, messages, placeholder, class. Keep the layout, the heading level rules and these accessibility details: Reasoning uses a native details disclosure so keyboard and screen-reader users can expand or collapse thinking steps without script. Live status updates (thread switch, copy, feedback, streaming state) are announced through a polite role="status" region. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ai-chat, check it fits: use it when building a full workspace assistant where replies include reasoning steps, tool calls and cited sources; users need to switch between recent threads, pick a model and stop or regenerate answers. Avoid it when you only need a single prompt input bar without a message history; use ai-composer instead; you want an editorial single-answer layout rather than a multi-turn chat; use ai-answer. Alternatives: @haze/chat-thread, @haze/bento-assistant.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.