AI Code

Code an agent writes, changes and runs: a streaming file with line numbers, a hunk-by-hunk diff with keep and undo, and a terminal with an exit status.

Installation

Installation

One command adds ai-code 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-code.json
ai-code-demo
components/ui/ai-code-demo.tsx
"use client"

import * as React from "react"

import { AiDemo } from "@/lib/ai-demo"
import { typeInto, useAiLoop } from "@/lib/ai-kit"
import {
  AiCodeStream,
  AiDiff,
  AiTerminal,
  type AiCodeLine,
  type AiDiffHunk,
  type AiTerminalLine,
} from "@/registry/tween/ai-code"

const FILE: AiCodeLine[] = [
  [
    { text: "export", kind: "keyword" },
    { text: " " },
    { text: "function", kind: "keyword" },
    { text: " " },
    { text: "Hero", kind: "function" },
    { text: "() {" },
  ],
  [
    { text: "  " },
    { text: "const", kind: "keyword" },
    { text: " ref = " },
    { text: "useRef", kind: "function" },
    { text: "(" },
    { text: "null", kind: "keyword" },
    { text: ")" },
  ],
  [
    { text: "  " },
    { text: "useReveal", kind: "function" },
    { text: "(ref, {" },
  ],
  [{ text: "    stagger: " }, { text: "0.05", kind: "number" }, { text: "," }],
  [
    { text: "    ease: " },
    { text: '"power3.out"', kind: "string" },
    { text: "," },
  ],
  [{ text: "  })" }],
  [
    { text: "  " },
    { text: "return", kind: "keyword" },
    { text: " <" },
    { text: "h1", kind: "function" },
    { text: " ref={ref}>Motion, considered.</" },
    { text: "h1", kind: "function" },
    { text: ">" },
  ],
  [{ text: "}" }],
]

function Stream() {
  const root = React.useRef<HTMLDivElement>(null)
  const [lines, setLines] = React.useState<AiCodeLine[]>(FILE)
  const [status, setStatus] = React.useState<"writing" | "saved">("saved")
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setStatus("writing")
      setLines([])
      await sleep(500)
      for (let row = 0; row < FILE.length; row++) {
        const full = FILE[row] ?? []
        for (let end = 1; end <= full.length; end++) {
          setLines([...FILE.slice(0, row), full.slice(0, end)])
          await sleep((full[end - 1]?.text.trim() ? 90 : 20) + end * 4)
        }
        await sleep(120)
      }
      setStatus("saved")
      await sleep(2600)
    },
    { gap: 500, enabled: !hands }
  )

  return (
    <div
      ref={root}
      style={{ display: "grid", width: "min(100%, 400px)" }}
      onPointerDown={() => {
        setHands(true)
        setLines(FILE)
        setStatus("saved")
      }}
    >
      <AiCodeStream filename="hero.tsx" lines={lines} status={status} />
    </div>
  )
}

const HUNKS: AiDiffHunk[] = [
  {
    id: "stagger",
    header: "@@ 12,4",
    lines: [
      { type: "ctx", text: "useReveal(ref, {" },
      { type: "del", text: "  stagger: 0.1," },
      { type: "add", text: "  stagger: 0.05," },
      { type: "add", text: '  ease: "power3.out",' },
    ],
  },
  {
    id: "markup",
    header: "@@ 21,2",
    lines: [
      { type: "del", text: "<h1>Motion.</h1>" },
      { type: "add", text: "<h1 ref={ref}>Motion, considered.</h1>" },
      { type: "add", text: "<p>Built for products.</p>" },
    ],
  },
]

type Verdicts = Record<string, "open" | "kept" | "undone">

function Diff() {
  const root = React.useRef<HTMLDivElement>(null)
  const [verdicts, setVerdicts] = React.useState<Verdicts>({})
  const [round, setRound] = React.useState(0)
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setVerdicts({})
      setRound((now) => now + 1)
      await sleep(1900)
      setVerdicts({ stagger: "kept" })
      await sleep(1500)
      setVerdicts({ stagger: "kept", markup: "undone" })
      await sleep(2600)
    },
    { gap: 500, enabled: !hands }
  )

  return (
    <div
      ref={root}
      style={{ display: "grid", width: "min(100%, 400px)" }}
      onPointerDown={() => setHands(true)}
    >
      <AiDiff
        key={round}
        filename="hero.tsx"
        hunks={HUNKS.map((hunk) => ({
          ...hunk,
          state: verdicts[hunk.id] ?? "open",
        }))}
        onResolve={(id, state) =>
          setVerdicts((now) => ({ ...now, [id]: state }))
        }
      />
      {hands && HUNKS.every((hunk) => verdicts[hunk.id]) ? (
        <button
          type="button"
          className="aik-btn sm ghost"
          style={{ justifySelf: "start", marginTop: 8 }}
          onClick={() => setVerdicts({})}
        >
          Reset the diff
        </button>
      ) : null}
    </div>
  )
}

const COMMAND = "pnpm build:registry"
const GOOD: AiTerminalLine[] = [
  { text: "synced 104 example dependencies", kind: "ok" },
  { text: "wrote registry/__index__.tsx", kind: "ok" },
  { text: "wrote public/r, 104 items", kind: "ok" },
  { text: "generated llms.txt", kind: "ok" },
  { text: "Done in 3.8s", kind: "end" },
]
const BAD: AiTerminalLine[] = [
  { text: "synced 104 example dependencies", kind: "ok" },
  { text: "missing file: example/ai-code-demo.tsx", kind: "err" },
  { text: "Failed after 1.2s", kind: "end" },
]

function Term() {
  const root = React.useRef<HTMLDivElement>(null)
  const [typed, setTyped] = React.useState(COMMAND)
  const [lines, setLines] = React.useState<AiTerminalLine[]>(GOOD)
  const [status, setStatus] = React.useState<"running" | "done" | "failed">(
    "done"
  )
  const [exit, setExit] = React.useState("Exit 0 · 3.8s")
  const turn = React.useRef(0)

  useAiLoop(
    root,
    async ({ sleep }) => {
      const fails = turn.current++ % 2 === 1
      const script = fails ? BAD : GOOD
      setStatus("running")
      setLines([])
      await typeInto(setTyped, COMMAND, sleep, 34)
      await sleep(500)
      for (let end = 1; end <= script.length; end++) {
        setLines(script.slice(0, end))
        await sleep(520)
      }
      setExit(fails ? "Exit 1 · 1.2s" : "Exit 0 · 3.8s")
      setStatus(fails ? "failed" : "done")
      await sleep(2600)
    },
    { gap: 500 }
  )

  return (
    <div ref={root} style={{ display: "grid", width: "min(100%, 400px)" }}>
      <AiTerminal
        command={COMMAND}
        typed={typed}
        lines={lines}
        status={status}
        exit={exit}
      />
    </div>
  )
}

export function AiCodeDemo({ only }: { only?: string }) {
  return (
    <AiDemo
      only={only}
      tabs={[
        { name: "Stream", node: <Stream /> },
        { name: "Diff", node: <Diff /> },
        { name: "Terminal", node: <Term /> },
      ]}
    />
  )
}

Installation

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

Usage

import { AiCodeStream, AiDiff, AiTerminal } from "@/components/ui/ai-code"
<AiCodeStream
  filename="hero.tsx"
  status={writing ? "writing" : "saved"}
  lines={[
    [{ text: "const", kind: "keyword" }, { text: " stagger = " }, { text: "0.05", kind: "number" }],
  ]}
/>
 
<AiDiff
  filename="hero.tsx"
  hunks={hunks}
  onResolve={(id, state) => setState(id, state)}
/>
 
<AiTerminal
  command="pnpm build:registry"
  lines={[{ text: "wrote public/r, 104 items", kind: "ok" }]}
  status="done"
  exit="Exit 0 · 3.8s"
/>

Code is passed as data: each line is a list of { text, kind } spans, so you can feed it from any tokenizer and nothing is injected as HTML.

Versions

  • AiCodeStream is a file being written. Line numbers count up, tokens fade in with syntax colour, a caret follows the last token while status is writing, and the copy button copies the plain text.
  • AiDiff shows added and removed lines per hunk with Keep and Undo. onResolve fires on press; set that hunk's state and the losing lines fade out while the rest settle into plain code. The header counts what is left.
  • AiTerminal shows a command and its output as a live log. The header pill reads Running, then ends on exit in green or red.

Props

AiCodeStream

PropTypeDefaultDescription
filenamestringShown in the tab.
lines{ text, kind? }[][]The code so far. kind is keyword, function, string, number or comment.
status"writing" | "saved""saved"Writing shows the caret and a blue pill.
onCopy() => voidCalled after the code is copied.

AiDiff

PropTypeDefaultDescription
filenamestringShown in the tab.
hunks{ id, header, lines, state? }[]Each line is { type: "add" | "del" | "ctx", text }.
onResolve(id: string, state: "kept" | "undone") => voidCalled from Keep and Undo.

AiTerminal

PropTypeDefaultDescription
commandstringThe command, shown in the header.
typedstringThe command as typed so far, for a typing effect.
lines{ text, kind? }[]Output lines. kind is out, ok, err or end.
status"running" | "done" | "failed"Drives the header pill.
exitstringThe pill's text once finished.