ai code run.md

AI Code Run

The assistant runs a short Python script in the reply. A marker steps down the lines, the output prints, and the chart it draws grows in.

Installation

npx shadcn@latest add @kokonutui/ai-code-run

Props

Prop Type Default Description
prompt? string The user's message, drawn as a bubble. Only the demo draws one by default.
message? string What the assistant says before the code.
filename? string
code? string The script. While writing, pass it as it streams in.
stdout? string What the script prints, or the error when it fails.
bars? CodeRunBar[] The chart the script draws, shown once it's done.
answer? ReactNode The reply under the run, shown once it's done.
status? CodeRunStatus Pass it to drive the card from your run; leave it out and the code plays through line by line on lineMs.
activeLine? number The line running now, from 1, while running.
duration? number How long the run took, in seconds, shown once it's done.
onRunAgain? () => void Shows Run again once the run is over. The demo replays by itself.
lineMs? number 320 Demo only: how long each line takes, in ms.
className? string Extra classes for the root element.

CodeRunBar

Field Type Description
label string
value number

CodeRunStatus

Where the run is: the model writing the code, the code running, then done or error. Matches a code tool's part going from input-streaming to input-available to output-available or output-error.

type CodeRunStatus = "writing" | "running" | "done" | "error";

Source

"use client";

/**
 * @author: @kokonutui
 * @description: AI Code Run
 * @version: 1.1.0
 * @date: 2026-11-05
 * @license: MIT
 * @website: https://kokonutui.com
 * @github: https://github.com/kokonut-labs/kokonutui
 */

import { RotateCcw } from "lucide-react";
import { AnimatePresence, MotionConfig, motion } from "motion/react";
import { type ReactNode, useEffect, useId, useRef, useState } from "react";
import { cn } from "@/lib/utils";

export interface CodeRunBar {
  label: string;
  value: number;
}

/**
 * Where the run is: the model `writing` the code, the code `running`, then
 * `done` or `error`. Matches a code tool's part going from input-streaming
 * to input-available to output-available or output-error.
 */
export type CodeRunStatus = "writing" | "running" | "done" | "error";

export interface AICodeRunProps {
  /** The user's message, drawn as a bubble. Only the demo draws one by default. */
  prompt?: string;
  /** What the assistant says before the code. */
  message?: string;
  filename?: string;
  /** The script. While `writing`, pass it as it streams in. */
  code?: string;
  /** What the script prints, or the error when it fails. */
  stdout?: string;
  /** The chart the script draws, shown once it's done. */
  bars?: CodeRunBar[];
  /** The reply under the run, shown once it's done. */
  answer?: ReactNode;
  /**
   * Pass it to drive the card from your run; leave it out and the code
   * plays through line by line on `lineMs`.
   */
  status?: CodeRunStatus;
  /** The line running now, from 1, while `running`. */
  activeLine?: number;
  /** How long the run took, in seconds, shown once it's done. */
  duration?: number;
  /** Shows Run again once the run is over. The demo replays by itself. */
  onRunAgain?: () => void;
  /** Demo only: how long each line takes, in ms. */
  lineMs?: number;
  className?: string;
}

const DEMO_CODE = `import pandas as pd

df = pd.read_csv("signups.csv")
weekly = df.groupby("week").size().tail(6)
growth = weekly.iloc[-1] / weekly.iloc[0] - 1

print(f"{weekly.sum():,} signups, {growth:+.0%}")
weekly.plot.bar()`;

const DEMO_BARS: CodeRunBar[] = [
  { label: "Oct 5", value: 690 },
  { label: "Oct 12", value: 742 },
  { label: "Oct 19", value: 788 },
  { label: "Oct 26", value: 856 },
  { label: "Nov 2", value: 784 },
  { label: "Nov 9", value: 952 },
];

const DEMO_ANSWER =
  "Signups grew 38% over six weeks, to 952 last week. The one dip, the week of Nov 2, lines up with the pricing page being down for a day.";

export default function AICodeRun({
  prompt,
  message,
  filename,
  code,
  stdout,
  bars,
  answer,
  status: statusProp,
  activeLine,
  duration,
  onRunAgain,
  lineMs = 320,
  className,
}: AICodeRunProps) {
  const outputId = useId();
  const isDemo = !statusProp && code === undefined;
  const shown = shownContent(
    { prompt, message, filename, stdout, bars, answer },
    isDemo
  );
  const lines = (code ?? DEMO_CODE).split("\n");
  const playback = usePlayback(lines, lineMs, !statusProp);
  const status = statusProp ?? playback.status;
  const finished = status === "done" || status === "error";
  const run = playback.run;

return (
    <MotionConfig reducedMotion="user">
      <div
        className={cn("flex w-full max-w-md flex-col gap-4", className)}
        data-state={status}
      >
        {shown.prompt ? (
          <p className="max-w-[85%] self-end rounded-2xl rounded-br-md bg-zinc-100 px-3.5 py-2 text-[14px] text-zinc-800 leading-snug dark:bg-zinc-800 dark:text-zinc-100">
            {shown.prompt}
          </p>
        ) : null}
        {shown.message ? (
          <p className="text-[15px] text-zinc-800 leading-7 dark:text-zinc-200">
            {shown.message}
          </p>
        ) : null}

<div className="overflow-hidden rounded-[18px] bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] ring-1 ring-black/[0.06] dark:bg-zinc-900 dark:ring-white/[0.08]">
          <pre className="relative overflow-x-auto py-2.5 font-mono text-[11.5px] leading-[20px]">
            <code className="relative block min-w-max">
              {lines.map((line, i) => (
                <span className="relative flex pr-4" key={i}>
                  <span className="relative w-8 shrink-0 select-none pr-3 text-right tabular-nums transition-colors duration-200">
                    {i + 1}
                  </span>
                  <span className={cn("relative whitespace-pre text-zinc-800 transition-opacity duration-200 dark:text-zinc-200")}> 
                    {highlight(line)}
                    {line ? "" : " "}
                  </span>
                </span>
              ))}
            </code>
          </pre>
        </div>
      </div>
    </MotionConfig>
  );
}

Usage

With no props it plays the demo. Pass status to drive it from your code tool: writing while the model streams the code in, running while it executes (with activeLine if your sandbox reports it), then done or error. stdout shows as soon as you pass it, and on error it reads as the error. The chart and answer show once it's done. The user's bubble and the line above the card only show when you pass prompt and message.

"use client";

import type { UIMessage } from "ai";
import AICodeRun, { type CodeRunStatus } from "@/components/kokonutui/ai-code-run";

type RunPythonPart = Extract<UIMessage["parts"][number], { type: `tool-${string}` }>;

const STATUS: Record<RunPythonPart["state"], CodeRunStatus> = {  
  "input-streaming": "writing",  
  "input-available": "running",  
  "approval-requested": "running",  
  "approval-responded": "running",  
  "output-available": "done",  
  "output-error": "error",  
  "output-denied": "error",  
};

export function RunPython({ part, answer }: { part: RunPythonPart; answer?: string }) {
  const input = part.input as { code?: string } | undefined;
  const output = part.state === "output-available"
    ? (part.output as { stdout: string; chart?: { label: string; value: number }[] })
    : undefined;

return (
    <AICodeRun
      answer={answer}
      bars={output?.chart}
      code={input?.code ?? ""}
      status={STATUS[part.state]}
      stdout={part.state === "output-error" ? part.errorText : output?.stdout}
    />
  );
}