AI chat memory
Split chat and live memory workspace with one-click prompts, Use memory toggle, in-place contradiction updates and inline edit or forget.
pnpm dlx shadcn@latest add @haze/ai-memory---
import { ArrowUp, Check, Pencil, Trash2, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
type MemoryGroup = "About you" | "Food" | "Work";
interface ChatMemoryItem {
id: string;
slot?: "name" | "city" | "diet" | "coffee" | "role" | "tools";
category: MemoryGroup;
text: string;
date: string;
updated?: boolean;
}
interface Props {
id?: string;
title?: string;
greeting?: string;
suggestions?: string[];
memories?: ChatMemoryItem[];
class?: string;
}
const {
id = "haze-ai-memory",
title = "Assistant",
greeting = "Hi Alex. What's new? Tell me anything and I'll keep what matters.",
suggestions = [
"I just moved to Lisbon",
"I'm vegetarian now",
"Please call me Sam",
],
memories = [
{ id: "cm-1", slot: "name", category: "About you", text: "Goes by Alex", date: "Aug 3" },
{ id: "cm-2", slot: "city", category: "About you", text: "Lives in Berlin", date: "Aug 3" },
{ id: "cm-3", slot: "diet", category: "Food", text: "Is pescatarian", date: "Sep 12" },
{ id: "cm-4", slot: "coffee", category: "Food", text: "Likes oat flat whites", date: "Sep 12" },
{ id: "cm-5", slot: "role", category: "Work", text: "Design engineer at Northline", date: "Jul 28" },
{ id: "cm-6", slot: "tools", category: "Work", text: "Wants short, direct answers", date: "Jul 28" },
],
class: className,
} = Astro.props;
const groups: MemoryGroup[] = ["About you", "Food", "Work"];
---
<section
aria-labelledby={`${id}-title`}
data-haze-ai-memory
data-instance-id={id}
data-initial-memories={JSON.stringify(memories)}
class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
<div class="mx-auto grid max-w-2xl grid-cols-1 overflow-hidden rounded-2xl border border-border bg-card shadow-key md:grid-cols-2">
<div class="flex min-h-88 min-w-0 flex-col justify-between border-b border-border md:border-r md:border-b-0">
<header class="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>
</header>
<ol role="list" data-chat-feed class="flex flex-1 flex-col gap-4 overflow-y-auto p-5">
<li class="text-sm/6 break-words text-pretty text-foreground">
{greeting}
</li>
</ol>
<div class="space-y-3 p-4">
<div class="flex flex-wrap gap-2" role="group" aria-label="Quick update prompts">
{
suggestions.map((prompt) => (
<button
type="button"
data-quick-prompt={prompt}
class="inline-flex min-h-8 cursor-pointer items-center rounded-full border border-border bg-transparent px-3 py-1 text-xs text-foreground transition-colors duration-150 ease-snappy hover:border-border-strong hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95"
>
{prompt}
</button>
))
}
</div>
<form
data-chat-form
class="flex items-center gap-2 rounded-full border border-frame bg-muted/30 py-1.5 pr-1.5 pl-4 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}-chat-input`} class="sr-only">Tell the assistant something about you</label>
<input
id={`${id}-chat-input`}
data-chat-input
type="text"
placeholder="Tell it something about you..."
class="min-w-0 flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-hidden"
/>
<button
type="submit"
aria-label="Send message"
class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-muted text-foreground transition-colors duration-150 ease-snappy hover:bg-primary hover:text-primary-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95"
>
<ArrowUp class="size-3.5" aria-hidden="true" />
</button>
</form>
</div>
</div>
<div class="flex min-w-0 flex-col">
<header class="flex items-center justify-between gap-3 border-b border-border px-5 py-3.5">
<div class="flex items-baseline gap-2">
<h3 class="text-sm/5 font-semibold tracking-tight text-foreground">Memory</h3>
<span data-mem-total class="text-xs/4 text-muted-foreground tabular-nums">
{memories.length}
</span>
</div>
<label class="inline-flex cursor-pointer items-center gap-2 select-none">
<span class="sr-only">Use memory</span>
<span data-mem-toggle-label class="text-xs/4 text-muted-foreground">On</span>
<span class="relative inline-flex h-5 w-9 shrink-0 items-center">
<input
id={`${id}-use-memory`}
data-use-memory
type="checkbox"
role="switch"
checked
class="peer sr-only"
/>
<span
aria-hidden="true"
class="h-5 w-9 rounded-full border border-transparent bg-input transition-colors duration-150 ease-snappy peer-checked:border-primary peer-checked:bg-primary peer-focus-visible:outline-2 peer-focus-visible:outline-offset-1 peer-focus-visible:outline-ring"
></span>
<span
aria-hidden="true"
class="pointer-events-none absolute left-0.5 size-4 rounded-full bg-foreground shadow-key transition-[translate,background-color] duration-150 ease-snappy peer-checked:translate-x-4 peer-checked:bg-primary-foreground"
></span>
</span>
</label>
</header>
<div data-memory-groups class="flex-1 space-y-5 p-5 transition-opacity duration-200 ease-smooth">
{
groups.map((group) => (
<div class="space-y-2">
<h4 class="text-xs/4 font-normal text-muted-foreground">{group}</h4>
<ul role="list" class="space-y-1">
{memories
.filter((m) => m.category === group)
.map((item) => (
<li class="group -mx-2 flex items-start justify-between gap-2 rounded-lg px-2 py-1 transition-colors duration-150 ease-snappy hover:bg-muted/40">
<p class="min-w-0 flex-1 text-sm/5 break-words text-foreground">
<span>{item.text}</span>
<span class="ml-1.5 text-xs text-muted-foreground tabular-nums">{item.date}</span>
</p>
<div class="flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-snappy group-hover:opacity-100 group-focus-within:opacity-100">
<button
type="button"
aria-label={`Edit memory: ${item.text}`}
class="inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground 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>
<button
type="button"
aria-label={`Forget memory: ${item.text}`}
class="inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-destructive/14 hover:text-destructive focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<Trash2 class="size-3" aria-hidden="true" />
</button>
</div>
</li>
))}
</ul>
</div>
))
}
</div>
</div>
<p data-mem-status role="status" class="sr-only"></p>
</div>
<template data-mem-icons>
<span data-mi-edit><Pencil class="size-3" aria-hidden="true" /></span>
<span data-mi-trash><Trash2 class="size-3" aria-hidden="true" /></span>
<span data-mi-check><Check class="size-3" aria-hidden="true" /></span>
<span data-mi-close><X class="size-3" aria-hidden="true" /></span>
</template>
</section>
<script>
type MemoryGroup = "About you" | "Food" | "Work";
interface ChatMemoryItem {
id: string;
slot?: "name" | "city" | "diet" | "coffee" | "role" | "tools";
category: MemoryGroup;
text: string;
date: string;
updated?: boolean;
}
function initAiMemory() {
document.querySelectorAll<HTMLElement>("[data-haze-ai-memory]").forEach((root) => {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const instanceId = root.dataset.instanceId ?? "haze-ai-memory";
const raw = root.dataset.initialMemories;
const feedEl = root.querySelector<HTMLOListElement>("[data-chat-feed]");
const form = root.querySelector<HTMLFormElement>("[data-chat-form]");
const input = root.querySelector<HTMLInputElement>("[data-chat-input]");
const totalEl = root.querySelector<HTMLElement>("[data-mem-total]");
const useMemoryToggle = root.querySelector<HTMLInputElement>("[data-use-memory]");
const toggleLabel = root.querySelector<HTMLElement>("[data-mem-toggle-label]");
const groupsWrap = root.querySelector<HTMLElement>("[data-memory-groups]");
const statusEl = root.querySelector<HTMLElement>("[data-mem-status]");
const iconTpl = root.querySelector<HTMLTemplateElement>("[data-mem-icons]");
if (!raw || !feedEl || !groupsWrap) return;
let memories: ChatMemoryItem[] = [];
try {
memories = JSON.parse(raw) as ChatMemoryItem[];
} catch {
return;
}
const groups: MemoryGroup[] = ["About you", "Food", "Work"];
let editingId: string | null = null;
let nextCounter = memories.length + 1;
const cloneIcon = (sel: string): Node | null => {
const el = iconTpl?.content.querySelector(sel)?.firstElementChild;
return el ? el.cloneNode(true) : null;
};
const appendChatTurn = (role: "user" | "assistant", text: string) => {
const li = document.createElement("li");
if (role === "user") {
li.className = "flex justify-end";
const bubble = document.createElement("div");
bubble.className = "max-w-[85%] rounded-2xl bg-muted px-3.5 py-2 text-sm/6 break-words text-foreground";
bubble.textContent = text;
li.append(bubble);
} else {
li.className = "text-sm/6 break-words text-pretty text-foreground";
li.textContent = text;
}
feedEl.append(li);
feedEl.scrollTop = feedEl.scrollHeight;
};
const renderMemories = () => {
if (totalEl) totalEl.textContent = String(memories.length);
const memoryOn = useMemoryToggle?.checked ?? true;
if (toggleLabel) toggleLabel.textContent = memoryOn ? "On" : "Off";
groupsWrap.classList.toggle("opacity-45", !memoryOn);
const frag = document.createDocumentFragment();
groups.forEach((group) => {
const items = memories.filter((m) => m.category === group);
if (items.length === 0) return;
const block = document.createElement("div");
block.className = "space-y-2";
const heading = document.createElement("h4");
heading.className = "text-xs/4 font-normal text-muted-foreground";
heading.textContent = group;
block.append(heading);
const ul = document.createElement("ul");
ul.setAttribute("role", "list");
ul.className = "space-y-1";
items.forEach((item) => {
const li = document.createElement("li");
li.className = `group -mx-2 flex items-start justify-between gap-2 rounded-lg px-2 py-1 transition-colors duration-200 ease-smooth ${
item.updated ? "bg-accent" : "hover:bg-muted/40"
}`;
if (editingId === item.id) {
const editForm = document.createElement("form");
editForm.className = "flex w-full items-center gap-1.5";
const fieldId = `${instanceId}-edit-${item.id}`;
const label = document.createElement("label");
label.htmlFor = fieldId;
label.className = "sr-only";
label.textContent = "Edit memory fact";
const editInput = document.createElement("input");
editInput.id = fieldId;
editInput.type = "text";
editInput.value = item.text;
editInput.className =
"h-7 min-w-0 flex-1 rounded-md border border-frame-input bg-field px-2 text-xs text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden";
const saveBtn = document.createElement("button");
saveBtn.type = "submit";
saveBtn.setAttribute("aria-label", "Save memory");
saveBtn.className =
"inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md bg-primary text-primary-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const ck = cloneIcon("[data-mi-check]");
if (ck) saveBtn.append(ck);
const cancelBtn = document.createElement("button");
cancelBtn.type = "button";
cancelBtn.setAttribute("aria-label", "Cancel edit");
cancelBtn.className =
"inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const cl = cloneIcon("[data-mi-close]");
if (cl) cancelBtn.append(cl);
cancelBtn.addEventListener("click", () => {
editingId = null;
renderMemories();
});
editForm.addEventListener("submit", (ev) => {
ev.preventDefault();
const val = editInput.value.trim();
if (!val) return;
item.text = val;
item.date = "Now";
item.updated = true;
editingId = null;
renderMemories();
if (statusEl) statusEl.textContent = "Memory updated.";
});
editForm.append(label, editInput, saveBtn, cancelBtn);
li.append(editForm);
window.requestAnimationFrame(() => editInput.focus());
} else {
const p = document.createElement("p");
p.className = "min-w-0 flex-1 text-sm/5 break-words text-foreground";
const textSpan = document.createElement("span");
textSpan.textContent = item.text;
const dateSpan = document.createElement("span");
dateSpan.className = "ml-1.5 text-xs text-muted-foreground tabular-nums";
dateSpan.textContent = item.date;
p.append(textSpan, dateSpan);
const actions = document.createElement("div");
actions.className =
"flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-snappy group-hover:opacity-100 group-focus-within:opacity-100";
const editBtn = document.createElement("button");
editBtn.type = "button";
editBtn.setAttribute("aria-label", `Edit memory: ${item.text}`);
editBtn.className =
"inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground 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 editIc = cloneIcon("[data-mi-edit]");
if (editIc) editBtn.append(editIc);
editBtn.addEventListener("click", () => {
editingId = item.id;
renderMemories();
});
const delBtn = document.createElement("button");
delBtn.type = "button";
delBtn.setAttribute("aria-label", `Forget memory: ${item.text}`);
delBtn.className =
"inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-destructive/14 hover:text-destructive focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
const delIc = cloneIcon("[data-mi-trash]");
if (delIc) delBtn.append(delIc);
delBtn.addEventListener("click", () => {
memories = memories.filter((m) => m.id !== item.id);
renderMemories();
if (statusEl) statusEl.textContent = `Forgot memory. ${memories.length} remaining.`;
});
actions.append(editBtn, delBtn);
li.append(p, actions);
}
ul.append(li);
});
block.append(ul);
frag.append(block);
});
if (memories.length === 0) {
const empty = document.createElement("p");
empty.className = "text-xs/5 text-muted-foreground";
empty.textContent = "No saved memories yet. Share a detail in chat to save it.";
frag.append(empty);
}
groupsWrap.replaceChildren(frag);
};
const processUserMessage = (rawMessage: string) => {
const message = rawMessage.trim();
if (!message) return;
appendChatTurn("user", message);
const memoryEnabled = useMemoryToggle?.checked ?? true;
if (!memoryEnabled) {
appendChatTurn("assistant", "Got it. Memory is paused, so I won't save that for later.");
if (statusEl) statusEl.textContent = "Replied with memory paused.";
return;
}
memories.forEach((m) => {
m.updated = false;
});
const moveMatch = message.match(/(?:moved to|live in|relocated to)\s+([A-Za-z][A-Za-z\s]{1,28})/i);
const nameMatch = message.match(/(?:call me|name is)\s+([A-Za-z]{2,24})/i);
const dietMatch = message.match(/\b(vegetarian|vegan|pescatarian|plant)\b/i);
if (moveMatch) {
const city = moveMatch[1].replace(/[.!?]+$/, "").trim();
const existing = memories.find((m) => m.slot === "city");
if (existing) {
existing.text = `Lives in ${city}`;
existing.date = "Just now";
existing.updated = true;
} else {
memories.unshift({
id: `cm-${nextCounter++}`,
slot: "city",
category: "About you",
text: `Lives in ${city}`,
date: "Just now",
updated: true,
});
}
renderMemories();
appendChatTurn("assistant", `Nice move — updated your city to ${city}.`);
if (statusEl) statusEl.textContent = `Updated city memory to Lives in ${city}.`;
return;
}
if (dietMatch) {
const dietLabel = dietMatch[1].toLowerCase() === "plant" ? "plant-forward" : dietMatch[1].toLowerCase();
const existing = memories.find((m) => m.slot === "diet");
if (existing) {
existing.text = `Is ${dietLabel}`;
existing.date = "Just now";
existing.updated = true;
} else {
memories.push({
id: `cm-${nextCounter++}`,
slot: "diet",
category: "Food",
text: `Is ${dietLabel}`,
date: "Just now",
updated: true,
});
}
renderMemories();
appendChatTurn("assistant", `Noted — I updated your food preference to ${dietLabel}.`);
if (statusEl) statusEl.textContent = `Updated Food memory to Is ${dietLabel}.`;
return;
}
if (nameMatch) {
const newName = nameMatch[1].trim();
const existing = memories.find((m) => m.slot === "name");
if (existing) {
existing.text = `Goes by ${newName}`;
existing.date = "Just now";
existing.updated = true;
} else {
memories.unshift({
id: `cm-${nextCounter++}`,
slot: "name",
category: "About you",
text: `Goes by ${newName}`,
date: "Just now",
updated: true,
});
}
renderMemories();
appendChatTurn("assistant", `Got it, ${newName}. Updated in Memory.`);
if (statusEl) statusEl.textContent = `Updated name memory to Goes by ${newName}.`;
return;
}
const lower = message.toLowerCase();
const inferredGroup: MemoryGroup =
lower.includes("coffee") || lower.includes("tea") || lower.includes("eat") || lower.includes("lunch")
? "Food"
: lower.includes("team") || lower.includes("code") || lower.includes("deploy") || lower.includes("work")
? "Work"
: "About you";
memories.push({
id: `cm-${nextCounter++}`,
category: inferredGroup,
text: message.replace(/[.!?]+$/, ""),
date: "Just now",
updated: true,
});
renderMemories();
appendChatTurn("assistant", `Saved that under ${inferredGroup}.`);
if (statusEl) statusEl.textContent = `Saved new memory under ${inferredGroup}.`;
};
root.querySelectorAll<HTMLButtonElement>("[data-quick-prompt]").forEach((btn) => {
btn.addEventListener("click", () => {
const text = btn.dataset.quickPrompt ?? "";
processUserMessage(text);
});
});
form?.addEventListener("submit", (ev) => {
ev.preventDefault();
const text = input?.value.trim() ?? "";
if (!text) return;
if (input) input.value = "";
processUserMessage(text);
});
useMemoryToggle?.addEventListener("change", () => {
renderMemories();
if (statusEl) {
statusEl.textContent = useMemoryToggle.checked
? "Memory enabled."
: "Memory paused.";
}
});
renderMemories();
});
}
initAiMemory();
document.addEventListener("astro:page-load", initAiMemory);
</script>When to use
- Demonstrating how conversational facts automatically overwrite older assistant memories in real time
- Pairing a live assistant chat alongside grouped personal memories with Use memory, edit and forget controls
When not to use
- Providing a standalone memory settings screen without a live chat pane; use agent-memory instead
- Building a multi-thread chat with reasoning and citations rather than memory updates; use ai-chat
Installation
Add the Haze registry to components.json once, then install AI chat memory with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-memorynpx shadcn@latest add @haze/ai-memoryyarn dlx shadcn@latest add @haze/ai-memorybunx --bun shadcn@latest add @haze/ai-memoryFirst 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-memory" | Unique prefix for headings, chat input and switch IDs. |
| title | string | "Assistant" | Heading for the left chat panel. |
| greeting | string | Demo assistant greeting | Initial assistant message shown in the chat log. |
| suggestions | string[] | 3 contradiction prompts | One-click prompt chips that update matching memories. |
| memories | ChatMemoryItem[] | 6 categorized memories | Dated memory records grouped under About you, Food and Work. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- Tab
- Move across quick prompt chips, chat input, Send button, Use memory switch and memory row actions
- EnterSpace
- Trigger a quick prompt, submit a message, toggle memory usage or edit and forget a record
Accessibility
- The Use memory toggle uses a native checkbox with role="switch" and visible label, and every memory row exposes item-specific Edit and Forget buttons.
- Contradiction updates, inline edits, forget actions and pause states announce cleanly via 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 memory" with `npx shadcn@latest add @haze/ai-memory`. 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 AiMemory from "@/components/haze/blocks/ai-memory.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-memory.md
Customize with real content
Adapt the Haze ai-memory block for our product. Replace the demo values of these props with our real content: id, title, greeting, suggestions, memories, class. Keep the layout, the heading level rules and these accessibility details: The Use memory toggle uses a native checkbox with role="switch" and visible label, and every memory row exposes item-specific Edit and Forget buttons. Contradiction updates, inline edits, forget actions and pause states announce cleanly via a polite role="status" region. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ai-memory, check it fits: use it when demonstrating how conversational facts automatically overwrite older assistant memories in real time; pairing a live assistant chat alongside grouped personal memories with use memory, edit and forget controls. Avoid it when providing a standalone memory settings screen without a live chat pane; use agent-memory instead; building a multi-thread chat with reasoning and citations rather than memory updates; use ai-chat. Alternatives: @haze/agent-memory, @haze/ai-chat, @haze/switch.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.