About
A sandbox an agent runs code in: status from cloning and installing to ready, live CPU and memory, open ports with their URLs, a streaming log and the file count, with Stop and restart.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Sandbox to your project and fits it to your theme.
Code
How Sandbox is used: the demo's code. The component's own source comes with a free account.
Usage.tsx
"use client"
import * as React from "react"
import { Sandbox, SandboxPort, SandboxStatus } from "@/components/ui/sandbox"
const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches
const E = "\u001b["
const gray = (s: string) => `${E}90m${s}${E}39m`
const bold = (s: string) => `${E}1m${s}${E}22m`
const green = (s: string) => `${E}32m${s}${E}39m`
/** Boot script: [delay before the line, log line, status text or null to keep]. Short enough to fit the drawer. */
const BOOT: [number, string, string | null][] = [
[300, gray("$ git clone quarry/checkout --depth 1"), "Cloning the repository"],
[400, "Cloning into 'checkout'... done.", null],
[300, gray("$ pnpm install --frozen-lockfile"), "Installing dependencies"],
[600, `Packages: ${bold("+412")} Done in 2.4s`, null],
[300, gray("$ pnpm dev"), "Starting the dev server"],
[400, " Local: http://localhost:3000", null],
[300, ` ${green("✓")} Ready in 1.1s`, null],
]
const HOLD_MS = 7000
const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"
/**
* 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
* phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
* render white on dark pages. FitFrame fills the frame exactly instead.
*
* - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
* - "crop": the content stays at full size from the top and fades out at the bottom. For text
* that streams in, where a changing scale would make the page breathe.
*
* `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
* to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
* shrinks evenly on both sides.
*
* Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
* shorter than `hideBelow`, so a profile card shows the visual alone.
*/
function FitFrame({
children,
mode = "scale",
hideBelow = 360,
minWidth,
}: {
children: React.ReactNode
mode?: "scale" | "crop"
hideBelow?: number
minWidth?: string
}) {
const content = React.useRef<HTMLDivElement>(null)
const [cropped, setCropped] = React.useState(false)
React.useLayoutEffect(() => {
const el = content.current
if (!el) return
const measure = () => {
const vw = window.innerWidth
const vh = window.innerHeight
el.toggleAttribute("data-fit-small", vh < hideBelow)
// Layout sizes ignore the transform, so measuring never feeds back.
const w = Math.max(el.offsetWidth, el.scrollWidth)
const h = Math.max(el.offsetHeight, el.scrollHeight)
const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
el.style.transform = scale < 1 ? `scale(${scale})` : ""
setCropped(mode === "crop" && h > vh + 1)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
// Content that changes inside a fixed width box (a headline that cycles words) never resizes
// the box itself, so changes below it measure again on the next frame.
let frame = 0
const mutations = new MutationObserver(() => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(measure)
})
mutations.observe(el, { subtree: true, childList: true, characterData: true })
window.addEventListener("resize", measure)
return () => {
observer.disconnect()
mutations.disconnect()
cancelAnimationFrame(frame)
window.removeEventListener("resize", measure)
}
}, [mode, hideBelow])
const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
return (
<div
className="flex w-full justify-center overflow-hidden"
style={{
height: "100dvh",
alignItems: mode === "crop" ? "flex-start" : "center",
maskImage: cropped ? fade : undefined,
WebkitMaskImage: cropped ? fade : undefined,
}}
>
<style>{FIT_CSS}</style>
<div
ref={content}
className="w-full shrink-0"
style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
>
{children}
</div>
</div>
)
}
const CPU = [0.34, 0.22, 0.41, 0.28, 0.19, 0.37, 0.25]
const MEM = [0.61, 0.63, 0.62, 0.66, 0.64, 0.63, 0.65]
const GB = 1024 * 1024 * 1024
/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
return (
<p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
{children}{" "}
<a
href={`https://chatcn.dev/docs/components/${slug}`}
target="_blank"
rel="noopener"
className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
>
chatcn.dev
</a>
</p>
)
}
/**
* A sandbox an agent spins up for a repo: it clones, installs and starts the dev server while the
* logs stream in, then goes ready with its port live and CPU and memory ticking. After a while it
* boots again. Loops.
*/
export default function SandboxPreview() {
const [status, setStatus] = React.useState<SandboxStatus>("starting")
const [step, setStep] = React.useState(0)
const [readyAt, setReadyAt] = React.useState<number>()
const [tick, setTick] = React.useState(0)
React.useEffect(() => {
if (reducedMotion()) {
setStep(BOOT.length)
setStatus("ready")
setReadyAt(Date.now() - 42_000)
}
}, [])
// The boot script, one line at a time.
React.useEffect(() => {
if (status !== "starting") return
if (step >= BOOT.length) {
setStatus("ready")
setReadyAt(Date.now())
return
}
const id = window.setTimeout(() => setStep((s) => s + 1), BOOT[step]?.[0] ?? 400)
return () => window.clearTimeout(id)
}, [status, step])
// Resource readings while ready, then a fresh boot.
React.useEffect(() => {
if (status !== "ready" || reducedMotion()) return
const id = window.setInterval(() => setTick((t) => t + 1), 1200)
const again = window.setTimeout(() => {
setStatus("starting")
setStep(0)
setReadyAt(undefined)
}, HOLD_MS)
return () => {
window.clearInterval(id)
window.clearTimeout(again)
}
}, [status])
const ready = status === "ready"
const statusText = ready
? undefined
: (BOOT.slice(0, step).reduce<string | null>((s, b) => b[2] ?? s, null) ?? "Provisioning")
const logs = BOOT.slice(0, step)
.map((b) => `${b[1]}\n`)
.join("")
const ports: SandboxPort[] =
step >= 6
? [{ port: 3000, label: "next dev", url: "https://3000-sb-7f3a2c.chatcn.run", state: ready ? "open" : "starting" }]
: []
return (
<FitFrame minWidth="32rem">
<div className="flex w-full flex-col items-center justify-center gap-4 p-6">
<div className="w-full max-w-lg">
<Sandbox
name="sb-7f3a2c"
status={status}
statusText={statusText}
meta="Node 22, iad1"
readyAt={readyAt}
cpu={ready ? CPU[tick % CPU.length] : 0.62}
memory={{ used: (ready ? (MEM[tick % MEM.length] ?? 0.6) : 0.48) * 2 * GB, total: 2 * GB }}
ports={ports}
logs={logs}
defaultLogsOpen
fileCount={214}
onOpenFiles={() => {}}
onStop={() => {}}
/>
</div>
<MoreOn slug="sandbox">The sandbox an agent runs code in: status, ports and logs. On</MoreOn>
</div>
</FitFrame>
)
}








