AI Tool Call

Tool calls made visible: an inline chip that unfolds into a result peek, a wire a packet travels between request and response, and a hub with lines drawing out to real services.

Installation

Installation

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

import * as React from "react"
import { FileText, Search, Terminal } from "lucide-react"

import { AiDemo } from "@/lib/ai-demo"
import {
  AiStyle,
  Face,
  typeInto,
  useAiLoop,
  useIdleHands,
  type AiStatus,
} from "@/lib/ai-kit"
import {
  AiToolChip,
  AiToolHub,
  AiToolWire,
  type AiHubCall,
  type AiHubService,
  type AiWirePhase,
} from "@/registry/tween/ai-tool"

const CSS = `
.aik-tcd-turn{display:grid;grid-template-columns:32px minmax(0,1fr);gap:14px;align-content:start;width:min(100%,540px);min-height:330px}
.aik-tcd-turn > div > b{display:block;padding:4px 0 6px;font-size:15px;font-weight:600}
.aik-tcd-turn p{font-size:16px;line-height:34px;color:var(--aik-text)}
@container (max-width:420px){.aik-tcd-turn{grid-template-columns:minmax(0,1fr)}.aik-tcd-turn > .aik-face{display:none}.aik-tcd-turn p{font-size:15px;line-height:32px}}
`

const realSleep = (ms: number) =>
  new Promise<void>((resolve) => window.setTimeout(resolve, ms))

function Chips() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [state, setState] = React.useState<AiStatus[]>(["done", "done", "run"])
  const [open, setOpen] = React.useState(-1)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setOpen(-1)
      setState(["todo", "todo", "todo"])
      await sleep(600)
      for (let index = 0; index < 3; index++) {
        setState((list) =>
          list.map((item, at) => (at === index ? "run" : item))
        )
        await sleep(1100)
        setState((list) =>
          list.map((item, at) => (at === index ? "done" : item))
        )
        await sleep(350)
      }
      for (const index of [0, 1, 2]) {
        setOpen(index)
        await sleep(2100)
        setOpen(-1)
        await sleep(500)
      }
    },
    {
      gap: 600,
      enabled: !hands,
      still: () => {
        setState(["done", "done", "done"])
        setOpen(0)
      },
    }
  )

  const controlled = (index: number) => (hands ? undefined : open === index)
  return (
    <div
      ref={root}
      className="aik aik-tcd-turn"
      onPointerDown={touch}
      onKeyDown={touch}
      onPointerMove={hands ? touch : undefined}
    >
      <Face
        size={32}
        shape="orb"
        mood={state.includes("run") ? "work" : "talk"}
      />
      <div>
        <b>Mira</b>
        <p>
          I opened{" "}
          <AiToolChip
            name="read_file"
            arg="hero.tsx"
            icon={<FileText size={13} />}
            status={state[0]}
            open={controlled(0)}
            peekTitle="hero.tsx · lines 12 to 14"
            peek={
              <>
                <code>{'<h1 className="hero-title">'}</code>
                <code>{"  Motion, considered."}</code>
                <code>{"</h1>"}</code>
              </>
            }
          />{" "}
          to see how the headline is built, searched{" "}
          <AiToolChip
            name="search_registry"
            arg={'"skew"'}
            icon={<Search size={13} />}
            status={state[1]}
            open={controlled(1)}
            peekTitle="3 matches"
            peek={
              <>
                <code>text-skew-reveal · registry/tween</code>
                <code>skew-scroll-gallery · registry/tween</code>
                <code>text-skew-reveal-demo · example</code>
              </>
            }
          />{" "}
          for a reveal that already exists, then ran{" "}
          <AiToolChip
            name="run_command"
            arg="pnpm typecheck"
            icon={<Terminal size={13} />}
            status={state[2]}
            open={controlled(2)}
            peekTitle="Exit 0 · 2.6s"
            peek={
              <>
                <code>$ tsc --noEmit</code>
                <code>checked 214 files</code>
                <code>0 errors</code>
              </>
            }
          />{" "}
          to make sure nothing broke.
        </p>
      </div>
    </div>
  )
}

const REQUEST = `{
  "repo": "tween-www",
  "title": "Add pricing section",
  "base": "main"
}`
const RESPONSE = [
  "201 Created",
  "number: 482",
  "files: 3 (+126 −8)",
  "url: github.com/tween/www/pull/482",
]

function Wire() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [phase, setPhase] = React.useState<AiWirePhase>("waiting")
  const [request, setRequest] = React.useState(REQUEST)
  const [lines, setLines] = React.useState(0)
  const [ms, setMs] = React.useState(420)
  const run = React.useRef(0)

  const play = React.useCallback(
    async (
      sleep: (ms: number) => Promise<void>,
      mine: number,
      type: boolean
    ) => {
      const alive = () => run.current === mine
      setPhase("idle")
      setLines(0)
      setMs(0)
      if (type) {
        setRequest("")
        await sleep(400)
        await typeInto(
          (value) => alive() && setRequest(value),
          REQUEST,
          sleep,
          14
        )
      } else setRequest(REQUEST)
      await sleep(500)
      if (!alive()) return
      setPhase("sending")
      for (let tick = 0; tick < 4; tick++) {
        await sleep(170)
        setMs((value) => value + 170)
      }
      if (!alive()) return
      setPhase("waiting")
      for (let tick = 0; tick < 7; tick++) {
        await sleep(170)
        setMs((value) => value + 170)
      }
      if (!alive()) return
      setPhase("receiving")
      for (let line = 1; line <= RESPONSE.length; line++) {
        await sleep(240)
        if (!alive()) return
        setMs((value) => value + 60)
        setLines(line)
      }
      setPhase("done")
    },
    []
  )

  useAiLoop(
    root,
    async ({ sleep }) => {
      const mine = ++run.current
      await play(sleep, mine, true)
      await sleep(2600)
    },
    {
      gap: 500,
      enabled: !hands,
      still: () => {
        setPhase("done")
        setLines(RESPONSE.length)
        setMs(1840)
      },
    }
  )

  return (
    <div
      ref={root}
      style={{ display: "grid", width: "min(100%, 560px)" }}
      onPointerDown={touch}
      onKeyDown={touch}
    >
      <AiToolWire
        name="github.create_pull_request"
        agent="Mira"
        service={{ label: "GitHub", brand: "github" }}
        phase={phase}
        request={request}
        response={RESPONSE.slice(0, lines)}
        latency={phase === "idle" ? "" : `${(ms / 1000).toFixed(2)}s`}
        onRetry={() => {
          const mine = ++run.current
          void play(realSleep, mine, false)
        }}
      />
    </div>
  )
}

const SERVICES: AiHubService[] = [
  { id: "github", label: "GitHub", brand: "github" },
  { id: "linear", label: "Linear", brand: "linear" },
  { id: "figma", label: "Figma", brand: "figma" },
  { id: "vercel", label: "Vercel", brand: "vercel" },
  { id: "notion", label: "Notion", brand: "notion" },
]
const RESULT: Record<string, string> = {
  github: "PR #482 opened",
  linear: "TW-91 moved",
  figma: "3 frames read",
  vercel: "Preview ready",
  notion: "Notes saved",
}

function Hub() {
  const root = React.useRef<HTMLDivElement>(null)
  const [hands, touch] = useIdleHands()
  const [calls, setCalls] = React.useState<AiHubCall[]>([
    { id: "seed-1", service: "github", status: "done", label: RESULT.github },
    { id: "seed-2", service: "linear", status: "run" },
  ])
  const serial = React.useRef(0)

  const start = (service: string) => {
    const id = `call-${++serial.current}`
    setCalls((list) => [...list, { id, service, status: "run" }])
    return id
  }
  const finish = (id: string) =>
    setCalls((list) =>
      list.map((call) =>
        call.id === id
          ? { ...call, status: "done", label: RESULT[call.service] }
          : call
      )
    )

  useAiLoop(
    root,
    async ({ sleep }) => {
      setCalls([])
      await sleep(900)
      const github = start("github")
      await sleep(500)
      const linear = start("linear")
      await sleep(1300)
      finish(github)
      await sleep(600)
      const figma = start("figma")
      await sleep(700)
      finish(linear)
      await sleep(900)
      finish(figma)
      await sleep(500)
      const vercel = start("vercel")
      const notion = start("notion")
      await sleep(1500)
      finish(vercel)
      await sleep(500)
      finish(notion)
      await sleep(2400)
    },
    {
      gap: 400,
      enabled: !hands,
      still: () =>
        setCalls([
          { id: "a", service: "github", status: "done", label: RESULT.github },
          { id: "b", service: "figma", status: "done", label: RESULT.figma },
        ]),
    }
  )

  return (
    <div
      ref={root}
      style={{ display: "grid", width: "min(100%, 520px)" }}
      onPointerDown={touch}
      onKeyDown={touch}
    >
      <AiToolHub
        label="Mira's tools"
        services={SERVICES}
        calls={calls}
        onCall={(service) => {
          const id = start(service)
          window.setTimeout(() => finish(id), 1500)
        }}
      />
    </div>
  )
}

export function AiToolDemo({ only }: { only?: string }) {
  return (
    <>
      <AiStyle id="ai-tool-demo" css={CSS} />
      <AiDemo
        only={only}
        tabs={[
          { name: "Unfolding chip", node: <Chips /> },
          { name: "Wire", node: <Wire /> },
          { name: "Hub", node: <Hub /> },
        ]}
      />
    </>
  )
}

Installation

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

Usage

import { AiToolChip, AiToolHub, AiToolWire } from "@/components/ui/ai-tool"
<p>
  I opened{" "}
  <AiToolChip
    name="read_file"
    arg="hero.tsx"
    status="done"
    peekTitle="hero.tsx · lines 12 to 14"
    peek={<code>{'<h1 className="hero-title">'}</code>}
  />{" "}
  to see how the headline is built.
</p>
<AiToolWire
  name="github.create_pull_request"
  agent="Mira"
  service={{ label: "GitHub", brand: "github" }}
  phase={phase}
  request={request}
  response={lines}
  latency="1.84s"
  onRetry={retry}
/>

Brand marks come from the kit's BrandIcon set. Pass icon instead of brand to use your own.

Versions

  • AiToolChip sits inside a sentence. It is tinted and spinning while the call runs, then settles to neutral with a check. Once done it unfolds a small peek at the result on hover, focus or click, and Escape folds it back.
  • AiToolWire draws the call as a wire between the agent and a service. A packet carries the request out on sending, the service tile takes a travelling edge light on waiting, and the packet returns on receiving while the response arrives line by line.
  • AiToolHub puts the agent's face at the centre of its services. Each call draws a line out with a pulse travelling along it, the tile lights, and a result chip lands beside it. Several calls can run at once.

Props

AiToolChip

PropTypeDefaultDescription
namestringThe tool's name, in mono.
argstringThe main argument, such as a file name.
status"todo" | "run" | "ask" | "done" | "fail""done"Drives the tint and the mark.
iconReactNodeA small icon before the name.
peekReactNodeThe result preview. Shown only once the call is done.
peekTitlestringA label at the top of the peek.
openbooleanControls the peek. Omit to let hover and focus do it.
onOpenChange(open: boolean) => voidCalled when the peek opens or closes.

AiToolWire

PropTypeDefaultDescription
namestringThe tool's name in the header.
service{ label, brand?, icon? }The far end of the wire.
phase"idle" | "sending" | "waiting" | "receiving" | "done" | "fail"Where the call is.
requeststringThe request body so far.
responsestring[]Response lines so far.
latencystringElapsed time, already formatted.
agentstring"Agent"The name under the agent's tile.
onRetry() => voidShows a retry button in the header.

AiToolHub

PropTypeDefaultDescription
services{ id, label, brand?, icon? }[]Tiles placed evenly around the face.
calls{ id, service, status, label? }[]status is run, done or fail.
labelstring"Tools"The heading above the hub.
onCall(service: string) => voidCalled when a service tile is pressed.

AiToolWire and AiToolHub also take tone, shape and mood for the face.