# AI code run

> Assistant Python execution card with line-by-line stepping, streaming stdout or ValueError traceback, responsive bar chart and synthesis.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-code-run`
- File: `src/components/haze/blocks/ai-code-run.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-code-run

## Use when
- Showing an assistant executing a short data-analysis script directly inside a chat reply
- Pairing numbered code execution with live stdout, error tracebacks and a visual summary chart
- Letting users re-run a computation or inspect structured failure handling inline

## Avoid when
- Displaying static syntax documentation without execution state or chart output; use code-block
- Simulating a raw interactive shell session without structured code stepping; use terminal-window

## Alternatives
- [code-block](https://hazeui.com/ui/code-block.md)
- [terminal-window](https://hazeui.com/ui/terminal-window.md)
- [agent-run](https://hazeui.com/blocks/agent-run.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-code-run" | no | Unique prefix for section heading IDs. |
| heading | `string` | "Python analysis run" | no | Card header title. |
| userPrompt | `string` | "Summarize this week's signups and plot the daily breakdown." | no | User prompt rendered above the script card. |
| filename | `string` | "signups.py" | no | Script filename displayed in the runner header and traceback. |
| data | `DayDatum[]` | Mon–Fri signup totals | no | Daily signup counts plotted in the bar chart and embedded in the script. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Code lines and terminal output sit in horizontally scrollable containers so narrow mobile viewports never clip or overflow.
- Reduced-motion preferences skip line-by-line animation frames and announce completion or ValueError failure immediately via role="status".
- Key Tab: Move between the Run again and Simulate error buttons
- Key Enter / Space: Re-execute the Python script or trigger the structured ValueError traceback

## Agent prompts

### Install and use

Install the Haze UI block "AI code run" with `npx shadcn@latest add @haze/ai-code-run`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiCodeRun from "@/components/haze/blocks/ai-code-run.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/ai-code-run.md

### Customize with real content

Adapt the Haze ai-code-run block for our product. Replace the demo values of these props with our real content: id, heading, userPrompt, filename, data, class. Keep the layout, the heading level rules and these accessibility details: Code lines and terminal output sit in horizontally scrollable containers so narrow mobile viewports never clip or overflow. Reduced-motion preferences skip line-by-line animation frames and announce completion or ValueError failure immediately via role="status". Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-code-run, check it fits: use it when showing an assistant executing a short data-analysis script directly inside a chat reply; pairing numbered code execution with live stdout, error tracebacks and a visual summary chart; letting users re-run a computation or inspect structured failure handling inline. Avoid it when displaying static syntax documentation without execution state or chart output; use code-block; simulating a raw interactive shell session without structured code stepping; use terminal-window. Alternatives: @haze/code-block, @haze/terminal-window, @haze/agent-run.

## Example requests that should lead here
- Build an AI code execution card that steps through a Python signup script, streams stdout, and animates a Mon–Fri bar chart
- Create an assistant code runner block with Run again and Simulate error controls plus a one-sentence summary

## Source

```astro
---
import { CircleX, Play } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface DayDatum {
  day: string;
  count: number;
}

interface Props {
  id?: string;
  heading?: string;
  userPrompt?: string;
  filename?: string;
  data?: DayDatum[];
  class?: string;
}

const {
  id = "haze-ai-code-run",
  heading = "Python analysis run",
  userPrompt = "How did signups do over the last five days?",
  filename = "signups.py",
  data = [
    { day: "Mon", count: 142 },
    { day: "Tue", count: 188 },
    { day: "Wed", count: 215 },
    { day: "Thu", count: 264 },
    { day: "Fri", count: 231 },
  ],
  class: className,
} = Astro.props;

const total = data.reduce((sum, item) => sum + item.count, 0);
const maxCount = Math.max(...data.map((d) => d.count), 1);
const peak = data.reduce((best, item) => (item.count > best.count ? item : best), data[0]);
const first = data[0]?.count ?? 1;
const last = data[data.length - 1]?.count ?? first;
const growthPct = Math.round(((last - first) / Math.max(first, 1)) * 100);
const growthStr = `${growthPct >= 0 ? "+" : ""}${growthPct}%`;

const codeLines = [
  "import pandas as pd",
  "",
  'df = pd.read_csv("signups.csv")',
  'daily = df.groupby("day").size().tail(5)',
  "growth = daily.iloc[-1] / daily.iloc[0] - 1",
  "",
  'print(f"{daily.sum():,} signups, {growth:+.0%}")',
  "daily.plot.bar()",
];

const stdoutLine = `${total.toLocaleString("en-US")} signups, ${growthStr} · peak ${peak.day} (${peak.count})`;
---

<section aria-labelledby={`${id}-title`} data-haze-ai-code-run class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}>
  <h2 id={`${id}-title`} class="sr-only">{heading}</h2>

  <div class="mx-auto max-w-md space-y-3.5">
    {/* User bubble */}
    <div class="flex justify-end">
      <p class="max-w-[85%] rounded-2xl rounded-br-sm bg-muted px-4 py-2.5 text-sm/6 text-foreground">
        {userPrompt}
      </p>
    </div>

    {/* Plain 1-line assistant intro */}
    <p class="text-sm/6 text-foreground">I&apos;ll pull them from the export and plot it.</p>

    {/* Nested code execution card */}
    <div class="rounded-2xl border border-border bg-muted/40 p-1.5 shadow-key">
      {/* Slim header */}
      <div class="flex items-center justify-between gap-2 px-3 py-2">
        <div class="flex min-w-0 items-center gap-2">
          <span class="rounded-md bg-muted px-1.5 py-0.5 font-mono text-[0.6875rem]/4 font-medium text-foreground">py</span>
          <span class="truncate font-mono text-xs text-foreground">{filename}</span>
        </div>

        <div class="flex shrink-0 items-center gap-1">
          <span class="mr-1.5 inline-flex items-center gap-1.5 text-xs text-muted-foreground">
            <span data-acr-dot class="size-1.5 rounded-full bg-success" aria-hidden="true"></span>
            <span data-acr-status-label>Done</span>
          </span>
          <button
            type="button"
            data-acr-run
            aria-label={`Run ${filename} again`}
            class="grid size-8 cursor-pointer place-items-center rounded-lg text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            <Play class="size-3.5" aria-hidden="true" />
          </button>
          <button
            type="button"
            data-acr-error
            aria-label={`Simulate error in ${filename}`}
            class="grid size-8 cursor-pointer place-items-center rounded-lg text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-destructive/10 hover:text-destructive focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            <CircleX class="size-3.5" aria-hidden="true" />
          </button>
        </div>
      </div>

      {/* Inner code + output surface */}
      <div class="overflow-hidden rounded-xl border border-border bg-card">
        {/* Numbered Python listing */}
        <div class="overflow-x-auto py-3">
          <ol role="list" class="min-w-max font-mono text-xs/6">
            {
              codeLines.map((line, index) => (
                <li
                  data-acr-line={String(index + 1)}
                  data-state="idle"
                  class="flex items-center gap-3.5 border-l-2 border-transparent px-3.5 transition-colors duration-150 ease-snappy data-[state=active]:border-foreground data-[state=active]:bg-accent data-[state=error]:border-destructive data-[state=error]:bg-destructive/14"
                >
                  <span class="w-4 shrink-0 text-right text-[0.6875rem] text-muted-foreground select-none tabular-nums">{index + 1}</span>
                  <code class="text-foreground">{line || " "}</code>
                </li>
              ))
            }
          </ol>
        </div>

        {/* Compact stdout + bar chart */}
        <div data-acr-output class="space-y-3 border-t border-border bg-muted/25 px-3.5 py-3">
          <div class="flex items-baseline justify-between gap-2 font-mono text-xs/5">
            <pre data-acr-stdout class="min-w-0 flex-1 overflow-x-auto text-foreground">{stdoutLine}</pre>
            <span data-acr-runtime class="shrink-0 text-[0.6875rem] text-muted-foreground tabular-nums">0.42s</span>
          </div>

          <div data-acr-chart>
            <ul role="list" aria-label="Daily signups from Monday to Friday" class="grid grid-cols-5 items-end gap-2.5 pt-1">
              {
                data.map((item) => {
                  const pct = Math.max(14, Math.round((item.count / maxCount) * 100));
                  const isPeak = item.day === peak.day;
                  return (
                    <li class="flex min-w-0 flex-col items-center gap-1.5">
                      <span class="font-mono text-[0.6875rem]/4 text-muted-foreground tabular-nums">{item.count}</span>
                      <div class="flex h-20 w-full items-end rounded-sm bg-muted/60 p-0.5">
                        <div
                          data-acr-bar
                          data-target-height={String(pct)}
                          style={`height: ${pct}%`}
                          class={cn(
                            "w-full rounded-xs transition-[height] duration-500 ease-snappy",
                            isPeak ? "bg-primary" : "bg-primary/50",
                          )}
                        />
                      </div>
                      <span class="font-mono text-[0.6875rem]/4 text-muted-foreground">{item.day}</span>
                    </li>
                  );
                })
              }
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div hidden data-acr-config data-stdout={stdoutLine} data-filename={filename}></div>
  <p data-acr-status role="status" class="sr-only"></p>
</section>

<script>
  function initAiCodeRun() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-code-run]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const cfg = root.querySelector<HTMLElement>("[data-acr-config]");
      const dot = root.querySelector<HTMLElement>("[data-acr-dot]");
      const statusLabel = root.querySelector<HTMLElement>("[data-acr-status-label]");
      const outputBand = root.querySelector<HTMLElement>("[data-acr-output]");
      const runtimeEl = root.querySelector<HTMLElement>("[data-acr-runtime]");
      const stdoutEl = root.querySelector<HTMLElement>("[data-acr-stdout]");
      const chartEl = root.querySelector<HTMLElement>("[data-acr-chart]");
      const status = root.querySelector<HTMLElement>("[data-acr-status]");
      const runBtn = root.querySelector<HTMLButtonElement>("[data-acr-run]");
      const errBtn = root.querySelector<HTMLButtonElement>("[data-acr-error]");
      const lines = Array.from(root.querySelectorAll<HTMLElement>("[data-acr-line]"));
      const bars = Array.from(root.querySelectorAll<HTMLElement>("[data-acr-bar]"));

      if (!cfg || !dot || !statusLabel || !outputBand || !stdoutEl || !chartEl) return;

      const stdoutOk = cfg.dataset.stdout ?? "";
      const file = cfg.dataset.filename ?? "signups.py";

      let runId = 0;
      const timers: number[] = [];

      const clearTimers = () => {
        while (timers.length) window.clearTimeout(timers.pop());
      };

      const setIndicator = (state: "done" | "running" | "error") => {
        if (state === "done") {
          dot.className = "size-1.5 rounded-full bg-success";
          statusLabel.textContent = "Done";
        } else if (state === "running") {
          dot.className = "size-1.5 rounded-full bg-brand animate-pulse";
          statusLabel.textContent = "Running";
        } else {
          dot.className = "size-1.5 rounded-full bg-destructive";
          statusLabel.textContent = "Error";
        }
      };

      const clearHighlights = () => {
        lines.forEach((l) => l.setAttribute("data-state", "idle"));
      };

      const setBars = (filled: boolean) => {
        bars.forEach((b) => {
          const target = b.dataset.targetHeight ?? "50";
          b.style.height = filled ? `${target}%` : "0%";
        });
      };

      const applyErrorState = () => {
        clearHighlights();
        const failLine = lines[4];
        if (failLine) failLine.setAttribute("data-state", "error");
        setIndicator("error");
        outputBand.hidden = false;
        if (runtimeEl) runtimeEl.textContent = "0.19s";
        stdoutEl.className = "min-w-0 flex-1 overflow-x-auto text-destructive";
        stdoutEl.textContent = `ValueError: missing signup count in ${file}, line 5`;
        chartEl.hidden = true;
        if (status) status.textContent = `Execution failed in ${file} on line 5 with ValueError.`;
      };

      const applyDoneState = (announce: boolean) => {
        clearHighlights();
        setIndicator("done");
        outputBand.hidden = false;
        if (runtimeEl) runtimeEl.textContent = "0.42s";
        stdoutEl.className = "min-w-0 flex-1 overflow-x-auto text-foreground";
        stdoutEl.textContent = stdoutOk;
        chartEl.hidden = false;
        requestAnimationFrame(() => setBars(true));
        if (announce && status) status.textContent = `Finished running ${file}. Daily signup chart ready.`;
      };

      const runScript = (simulateError: boolean, announce: boolean) => {
        const myRun = ++runId;
        clearTimers();
        const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

        if (reduced) {
          if (simulateError) applyErrorState();
          else applyDoneState(announce);
          return;
        }

        setIndicator("running");
        outputBand.hidden = true;
        setBars(false);
        if (announce && status) {
          status.textContent = simulateError ? `Running ${file} with simulated error…` : `Running ${file}…`;
        }

        const execOrder = simulateError ? [0, 2, 3, 4] : [0, 2, 3, 4, 6, 7];
        const stepMs = 190;

        execOrder.forEach((lineIdx, stepIdx) => {
          timers.push(
            window.setTimeout(() => {
              if (myRun !== runId) return;
              clearHighlights();
              lines[lineIdx]?.setAttribute("data-state", "active");
            }, stepIdx * stepMs),
          );
        });

        timers.push(
          window.setTimeout(() => {
            if (myRun !== runId) return;
            if (simulateError) applyErrorState();
            else applyDoneState(announce);
          }, execOrder.length * stepMs + 140),
        );
      };

      runBtn?.addEventListener("click", () => runScript(false, true));
      errBtn?.addEventListener("click", () => runScript(true, true));
      runScript(false, false);
    });
  }
  initAiCodeRun();
  document.addEventListener("astro:page-load", initAiCodeRun);
</script>
```
