Aadi

Memory Manager

AI chats 1

About

Settings for what an assistant remembers: memories grouped by topic, with search, inline edit, delete and a capacity meter.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Memory Manager to your project and fits it to your theme.

Code

How Memory Manager is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { Memory, MemoryManager } from "@/components/ui/memory-manager"

const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

const QUERY = "pnpm"

/** The tour: the list, a memory saved from a chat, then a search that narrows it. */
const BEATS = [
  { added: false, typed: 0, ms: 2600 },
  { added: true, typed: 0, ms: 2200 },
  ...Array.from({ length: QUERY.length }, (_, i) => ({ added: true, typed: i + 1, ms: 160 })),
  { added: true, typed: QUERY.length, ms: 2200 },
]

/** Saved during the tour, from the chat that is open. */
const NEW_MEMORY: Memory = {
  id: "pref-commits",
  topic: "Preferences",
  text: "Writes commit messages in the imperative, under 60 characters.",
  source: "Write the release notes",
  updatedAt: "Just now",
}

/** One developer's saved memories. The company is made up. */
const SAVED: Memory[] = [
  {
    id: "pref-pnpm",
    topic: "Preferences",
    text: "Uses pnpm, never npm or yarn, in every command and script.",
    source: "Update the CI workflow",
    updatedAt: "Oct 17",
  },
  {
    id: "pref-short",
    topic: "Preferences",
    text: "Wants the answer first, then the reasoning, in under five sentences.",
    source: "Settings",
    updatedAt: "Sep 28",
  },
  {
    id: "work-role",
    topic: "Work",
    text: "Frontend lead at Tidewater Payments. Owns the checkout and billing pages.",
    source: "Plan the Q4 billing migration",
    updatedAt: "Oct 2",
  },
  {
    id: "work-stack",
    topic: "Work",
    text: "Stack is Next.js with the App Router, strict TypeScript and Postgres.",
    source: "Debug the schema migration",
    updatedAt: "Oct 9",
  },
]

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/**
 * Settings for what an assistant remembers: memories grouped by topic, each with the chat it
 * came from. The tour saves a new one from a chat, then searches for "pnpm". Edit, delete or
 * search yourself and the tour stops.
 */
export default function MemoryManagerPreview() {
  const [beat, setBeat] = React.useState(0)
  const [touched, setTouched] = React.useState(false)
  const [own, setOwn] = React.useState<Memory[] | null>(null)
  const [ownQuery, setOwnQuery] = React.useState("")

  React.useEffect(() => {
    if (touched || reducedMotion()) return
    const id = window.setTimeout(() => setBeat((n) => (n + 1) % BEATS.length), BEATS[beat]!.ms)
    return () => window.clearTimeout(id)
  }, [beat, touched])

  const b = BEATS[beat]!
  const tourList = b.added ? [NEW_MEMORY, ...SAVED] : SAVED
  const list = own ?? tourList
  const query = touched ? ownQuery : QUERY.slice(0, b.typed)

  const take = () => {
    if (!touched) {
      setTouched(true)
      setOwn(tourList)
      setOwnQuery(query)
    }
  }

  return (
    <FitFrame minWidth="42rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div className="bg-(color:--chatcn-card) border-(color:--chatcn-border) rounded-(--chatcn-radius-lg) shadow-(--chatcn-shadow-xs) flex h-[23rem] w-[38rem] shrink-0 flex-col gap-3 overflow-hidden border p-5">
          <div className="flex flex-col gap-0.5">
            <h3 className="text-[0.9375rem]/[1.5rem] tracking-[-0.006em] text-(color:--chatcn-fg) font-medium">Memory</h3>
            <p className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted)">
              What the assistant keeps between chats. Edit or delete anything.
            </p>
          </div>
          {/* The list runs past the card; it fades out instead of being cut. */}
          <div className="-mx-5 min-h-0 flex-1 overflow-hidden px-5 [mask-image:linear-gradient(to_bottom,black_calc(100%-2.5rem),transparent)]">
          <MemoryManager
            onPointerDown={take}
            memories={list}
            usage={b.added || touched ? 0.64 : 0.58}
            query={query}
            onQueryChange={(q) => {
              take()
              setOwnQuery(q)
            }}
            onUpdate={(id, text) =>
              setOwn((prev) =>
                (prev ?? tourList).map((m) => (m.id === id ? { ...m, text, updatedAt: "Just now" } : m)),
              )
            }
            onDelete={(id) => setOwn((prev) => (prev ?? tourList).filter((m) => m.id !== id))}
            onDeleteAll={() => setOwn([])}
          />
          </div>
        </div>
        <MoreOn slug="memory-manager">What an assistant remembers, to search, edit and delete. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aadi

View all
  • Audio Visualizer

    Audio Visualizer

    29
  • Stat Card

    Stat Card

    24
  • Dither Orb

    Dither Orb

    23
  • Voice Orb

    Voice Orb

    17
  • Waveform

    Waveform

    13
  • Message Feedback

    Message Feedback

    12
  • Agent Lanes

    Agent Lanes

    11
  • Voice Controls

    Voice Controls

    10

More in AI chats

View all
  • AI Actions

    AI Actions

    349
  • Aquarium Prompt

    Aquarium Prompt

    95
  • Generation Stats

    Generation Stats

  • Chat Bubble

    Chat Bubble

    202
  • Commit

    Commit

    36
  • Color Picker

    Color Picker

    190
  • Environment Variables

    Environment Variables

    27
  • Message With Header And Delivery Status

    Message With Header And Delivery Status

    57

Explore more

Part of chatcn — browse the full library on 21st.dev.