AI Notch

Ways a run reaches you: a notch that grows into a status card, a toast stack for done, needs-you and failed, and an inline reconnect banner.

Installation

Installation

One command adds ai-notch and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.

$npx shadcn@latest add https://tweenui.dev/r/ai-notch.json
ai-notch-demo
components/ui/ai-notch-demo.tsx
"use client"

import * as React from "react"

import { AiDemo } from "@/lib/ai-demo"
import {
  AiStyle,
  paceToken,
  useAiLoop,
  type AiStatus,
} from "@/lib/ai-kit"
import {
  AiBanner,
  AiNotch,
  AiToasts,
  type AiToast,
} from "@/registry/tween/ai-notch"

const CSS = `
.aik-nt-win{position:relative;width:min(100%,380px);height:232px;border-radius:16px;background:var(--aik-sunk);box-shadow:inset 0 0 0 1px var(--aik-line);overflow:hidden}
.aik-nt-chrome{display:flex;gap:6px;align-items:center;height:34px;padding:0 13px;border-bottom:1px solid var(--aik-line)}
.aik-nt-chrome i{inline-size:9px;block-size:9px;border-radius:50%;background:var(--aik-line-3)}
.aik-nt-page{display:grid;gap:10px;padding:26px 22px}
.aik-nt-page i{display:block;height:9px;border-radius:5px;background:var(--aik-line-2)}
.aik-nt-page i:first-child{height:15px;background:var(--aik-line-3);margin-bottom:6px}
.aik-nt-win[data-open] .aik-nt-card{opacity:1;transform:none;transition:opacity var(--aik-d-state) var(--aik-ease-out),transform var(--aik-d-panel) var(--aik-ease-soft)}
.aik-nt-win[data-open] .aik-nt-nub{opacity:0;transform:scale(1.5,1.3)}
.aik-nt-flow{display:grid;gap:14px;width:min(100%,400px)}
.aik-nt-msg{font-size:14.5px;line-height:23px;color:var(--aik-text);min-height:69px}
.aik-nt-msg code{font:12.5px var(--aik-mono);padding:2px 5px;border-radius:5px;background:var(--aik-raised)}
.aik-nt-page{padding-top:58px}
.aik-nt-win .aik-nt-notch{position:absolute;left:50%;top:40px;translate:-50% 0;inline-size:min(268px,calc(100% - 24px))}
.aik-nt-col{display:grid;gap:14px;justify-items:center;width:min(100%,340px)}
`

const clock = (seconds: number) =>
  `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`

const NOTCH_STEPS: Array<[AiStatus, string, number, number]> = [
  ["run", "Building pricing", 0.12, 4],
  ["run", "Running 24 tests", 0.62, 4],
  ["ask", "Needs your OK to publish", 0.8, 4],
  ["run", "Publishing", 0.94, 3],
]

function Notch() {
  const root = React.useRef<HTMLDivElement>(null)
  const [open, setOpen] = React.useState(true)
  const [status, setStatus] = React.useState<AiStatus>("ask")
  const [label, setLabel] = React.useState("Needs your OK to publish")
  const [progress, setProgress] = React.useState(0.8)
  const [seconds, setSeconds] = React.useState(16)
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      let elapsed = 0
      setOpen(false)
      setStatus("todo")
      setLabel("Starting")
      setProgress(0)
      setSeconds(0)
      await sleep(1100)
      setStatus("run")
      setLabel("Building pricing")
      setProgress(0.12)
      await sleep(900)
      setOpen(true)
      for (const [nextStatus, nextLabel, nextProgress, ticks] of NOTCH_STEPS) {
        setStatus(nextStatus)
        setLabel(nextLabel)
        setProgress(nextProgress)
        for (let tick = 0; tick < ticks; tick++) {
          setSeconds(elapsed)
          elapsed += 2
          await sleep(430)
        }
      }
      setStatus("done")
      setLabel(`Done in ${clock(elapsed)}`)
      setProgress(1)
      await sleep(1500)
      setOpen(false)
      await sleep(1500)
    },
    { gap: 300, enabled: !hands }
  )

  return (
    <div
      ref={root}
      className="aik-nt-win"
      onPointerDown={() => setHands(true)}
      onKeyDown={() => setHands(true)}
    >
      <div className="aik-nt-chrome">
        <i />
        <i />
        <i />
      </div>
      <div className="aik-nt-page">
        <i style={{ width: "44%" }} />
        <i />
        <i />
        <i style={{ width: "72%" }} />
      </div>
      <AiNotch
        name="Mira"
        status={status}
        label={label}
        progress={progress}
        time={status === "done" ? undefined : clock(seconds)}
        nubLabel={status === "done" ? "Done" : undefined}
        open={open}
        onOpenChange={setOpen}
      />
    </div>
  )
}

const FEED: AiToast[] = [
  {
    id: "built",
    status: "done",
    title: "Registry rebuilt",
    detail: "102 items, no warnings",
  },
  {
    id: "publish",
    status: "ask",
    title: "Publish to tweenui.dev?",
    detail: "Mira is waiting for you",
    action: "Approve",
  },
  {
    id: "tests",
    status: "fail",
    title: "3 tests failed",
    detail: "Odo is fixing them now",
    action: "View",
  },
  {
    id: "fixed",
    status: "done",
    title: "24 tests pass",
    detail: "Odo fixed all 3 failures",
  },
]

function Toasts() {
  const root = React.useRef<HTMLDivElement>(null)
  const [list, setList] = React.useState<AiToast[]>(FEED.slice(0, 3))
  const [sent, setSent] = React.useState(3)
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setList([])
      await sleep(500)
      for (const toast of FEED) {
        setList((current) => [...current, toast])
        await sleep(1500)
      }
      for (let left = 3; left > 0; left--) {
        setList((current) => current.slice(0, -1))
        await sleep(420)
      }
      setList([])
      await sleep(500)
    },
    { gap: 300, enabled: !hands, still: () => setList(FEED.slice(0, 3)) }
  )

  const drop = (id: string) =>
    setList((current) => current.filter((toast) => toast.id !== id))

  return (
    <div ref={root} className="aik-nt-col" onPointerDown={() => setHands(true)}>
      <AiToasts toasts={list} onDismiss={drop} onAction={drop} />
      <button
        type="button"
        className="aik-btn sm line"
        onClick={() => {
          const next = FEED[sent % FEED.length]
          if (!next) return
          setList((current) => [
            ...current,
            { ...next, id: `${next.id}-${sent}` },
          ])
          setSent(sent + 1)
        }}
      >
        Send a toast
      </button>
    </div>
  )
}

const TAIL = "animates in 180ms. Next I will rebuild the registry."

interface Ban {
  status: AiStatus
  title: string
  detail?: string
  retryIn?: number
  retryLabel?: string
}
const DROPPED: Ban = {
  status: "fail",
  title: "The stream dropped",
  detail: "212 tokens arrived. Retry keeps them.",
}
const RECONNECT: Ban = {
  status: "run",
  title: "Reconnecting",
  detail: "Picking up from token 212",
}
const RESUMED: Ban = {
  status: "done",
  title: "Stream resumed",
  detail: "Nothing was lost.",
}

function Banner() {
  const root = React.useRef<HTMLDivElement>(null)
  const [ban, setBan] = React.useState<Ban>(DROPPED)
  const [hidden, setHidden] = React.useState(false)
  const [words, setWords] = React.useState<string[]>([])
  const [hands, setHands] = React.useState(false)
  const round = React.useRef(0)
  const timers = React.useRef<number[]>([])

  React.useEffect(() => {
    const pending = timers.current
    return () => pending.forEach((timer) => window.clearTimeout(timer))
  }, [])

  useAiLoop(
    root,
    async ({ sleep }) => {
      setWords([])
      setHidden(false)
      if (round.current++ % 2 === 0) {
        setBan(DROPPED)
        await sleep(2300)
      } else {
        for (let left = 5; left > 0; left--) {
          setBan({
            status: "ask",
            title: "Rate limit reached",
            retryIn: left,
            retryLabel: "Retry now",
          })
          await sleep(800)
        }
      }
      setBan(RECONNECT)
      await sleep(1800)
      setBan(RESUMED)
      for (const word of TAIL.split(" ")) {
        setWords((current) => [...current, word])
        await sleep(paceToken(word, 60))
      }
      await sleep(900)
      setHidden(true)
      await sleep(1100)
    },
    {
      gap: 300,
      enabled: !hands,
      still: () => {
        setBan(DROPPED)
        setHidden(false)
      },
    }
  )

  const retry = () => {
    setBan(RECONNECT)
    timers.current.push(
      window.setTimeout(() => {
        setBan(RESUMED)
        setWords(TAIL.split(" "))
      }, 1600)
    )
  }

  return (
    <div
      ref={root}
      className="aik-nt-flow"
      onPointerDown={() => setHands(true)}
    >
      <p className="aik-nt-msg">
        The pricing section is in <code>pricing-section.tsx</code> and the
        toggle{" "}
        {words.map((word, at) => (
          <span key={at} className="aik-w">
            {word}{" "}
          </span>
        ))}
      </p>
      <AiBanner
        status={ban.status}
        title={ban.title}
        detail={ban.detail}
        retryIn={ban.retryIn}
        retryLabel={ban.retryLabel}
        hidden={hidden}
        onRetry={retry}
      />
    </div>
  )
}

export function AiNotchDemo({ only }: { only?: string }) {
  return (
    <>
      <AiStyle id="ai-notch-demo" css={CSS} />
      <AiDemo
        only={only}
        tabs={[
          { name: "Notch", node: <Notch /> },
          { name: "Toast stack", node: <Toasts /> },
          { name: "Banner", node: <Banner /> },
        ]}
      />
    </>
  )
}

Installation

pnpm dlx shadcn@latest add https://tweenui.dev/r/ai-notch.json

Usage

import { AiBanner, AiNotch, AiToasts } from "@/components/ui/ai-notch"
<AiNotch name="Mira" status="run" label="Running 24 tests" time="0:14" progress={0.62} />
 
<AiToasts
  toasts={toasts}
  onDismiss={(id) => setToasts((list) => list.filter((toast) => toast.id !== id))}
  onAction={approve}
/>
 
<AiBanner
  status="fail"
  title="The stream dropped"
  detail="212 tokens arrived. Retry keeps them."
  onRetry={reconnect}
/>

Versions

  • AiNotch is a small dark pill that grows into a status card from its top edge. It opens on click and closes on Escape or a second click. Pass open and onOpenChange to control it, for example to open it when the agent needs you.
  • AiToasts stacks up to three notifications. The newest sits at the front; older ones move up and back, and removed ones leave downward. Only the front toast takes clicks.
  • AiBanner sits in the thread where the trouble happened. fail and ask wait for the person, run shows a reconnecting state and disables the button, done confirms recovery. retryIn adds a countdown.

Props

AiNotch

PropTypeDefaultDescription
namestringThe agent's name.
status"todo" | "run" | "ask" | "done" | "fail"Drives the colour and the face's mood.
labelstringWhat the agent is doing. Rolls when it changes.
timestringElapsed time, already formatted.
progressnumber0 to 1, drawn as a line under the card.
openbooleanControls the card. Omit to let the notch manage it.
defaultOpenbooleanfalseStarting state when uncontrolled.
onOpenChange(open: boolean) => voidCalled on click and Escape.
nubLabelstringnameText on the closed pill.

AiToasts

PropTypeDefaultDescription
toasts{ id, status, title, detail?, action? }[]Oldest first. The last one is in front.
onDismiss(id: string) => voidAdds a dismiss button to each toast.
onAction(id: string) => voidCalled from a toast's action button.

AiBanner

PropTypeDefaultDescription
status"todo" | "run" | "ask" | "done" | "fail"Sets the colour and the mark.
titlestringThe headline. Rolls when it changes.
detailReactNodeA line under the title.
retryInnumberSeconds until an automatic retry.
retryLabelstring"Retry"The button's label.
onRetry() => voidShows the button.
hiddenbooleanfalseFades the banner out but keeps its space.