AI Panel.
The Forge with AI / Build with AI side panel: prompt, Generate, Fix and Explain, a model Select, a running state with an elapsed clock and Thinking and Writing stream boxes, and a result card with a checks badge, evidence, changed files and Apply or Discard. The preview runs against a mock.
"use client";
import * as React from "react";
import { SendIcon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Eyebrow } from "@/components/ui/eyebrow";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { UsageMeter, UsageMeterGroup, UsageMeterGroupLabel } from "@/components/ui/usage-meter";
import { useMockAiRun, type MockFlavor } from "./mock";
import { AiPanel } from "./panel";
const states = ["idle", "running", "result", "error"] as const;
/** A working demo of the AI panel against a mock backend. Import AiPanel from ./panel to wire your own. */
export default function AIPanel() {
const [flavor, setFlavor] = React.useState<MockFlavor>("turtledeck");
return (
<div className="min-h-svh bg-background bg-grid px-4 py-6 sm:px-8 sm:py-10">
<div className="mx-auto flex max-w-[440px] flex-col gap-4">
<div className="flex flex-col gap-3">
<Eyebrow>Preview</Eyebrow>
<ToggleGroup
type="single"
variant="outline"
size="sm"
value={flavor}
onValueChange={(v) => v && setFlavor(v as MockFlavor)}
aria-label="App"
>
<ToggleGroupItem value="turtledeck">TurtleDeck</ToggleGroupItem>
<ToggleGroupItem value="lantern">Lantern Hub</ToggleGroupItem>
</ToggleGroup>
</div>
<Demo key={flavor} flavor={flavor} />
</div>
</div>
);
}
function Demo({ flavor }: { flavor: MockFlavor }) {
const { panelProps, status, show } = useMockAiRun(flavor, () => toast.success("Applied to the editor"));
return (
<>
<ToggleGroup
type="single"
variant="outline"
size="sm"
value={status}
onValueChange={(v) => v && show(v as (typeof states)[number])}
aria-label="Panel state"
className="w-full"
>
{states.map((s) => (
<ToggleGroupItem key={s} value={s} className="capitalize">
{s}
</ToggleGroupItem>
))}
</ToggleGroup>
<AiPanel
{...panelProps}
className="min-h-[640px] rounded-lg border shadow-block"
resultActions={
flavor === "turtledeck" ? (
<Button size="sm" variant="secondary" onClick={() => toast.success("Sent to Testy")}>
<SendIcon /> Send to Testy
</Button>
) : undefined
}
allowance={
<UsageMeterGroup aria-label="AI allowance" className="w-full justify-between border-0 px-0 py-0">
<UsageMeterGroupLabel>AI allowance</UsageMeterGroupLabel>
<UsageMeter size="compact" label="5-hour" value={32} />
<UsageMeter size="compact" label="Week" value={18} />
</UsageMeterGroup>
}
/>
</>
);
}"use client";
import * as React from "react";
import {
CheckIcon,
CircleAlertIcon,
CircleXIcon,
MessageSquareTextIcon,
SparklesIcon,
SquareIcon,
WrenchIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Eyebrow } from "@/components/ui/eyebrow";
import { formatElapsed, useElapsed } from "@/components/ui/job-card";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { StreamBox } from "@/components/ui/stream-box";
import { Textarea } from "@/components/ui/textarea";
export type AiPanelStatus = "idle" | "running" | "result" | "error";
export type AiPanelModel = { value: string; label: string };
export type AiPanelFile = {
path: string;
/** Short description, e.g. "new, 23 lines" or "+12 lines". */
detail?: string;
status?: "new" | "changed" | "deleted";
};
export type AiPanelResult = {
/** One or two sentences on what the change does. */
summary: React.ReactNode;
/** Whether the app's own checks passed. Leave undefined to hide the badge. */
checksPassed?: boolean;
/** Badge text, e.g. "Passed TurtleDeck's checks" or "2 checks failed". */
checksLabel?: string;
/** The model that wrote it, shown as "by <model>". */
model?: string;
/** Dry-run tiles, test requests or anything else that shows the result works. */
evidence?: React.ReactNode;
files?: AiPanelFile[];
};
export type AiPanelProps = Omit<React.ComponentProps<"section">, "title"> & {
title?: React.ReactNode;
/** Small text on the right of the header, e.g. "Shared allowance". */
badge?: React.ReactNode;
promptLabel?: string;
placeholder?: string;
prompt: string;
onPromptChange: (value: string) => void;
models: AiPanelModel[];
model: string;
onModelChange: (value: string) => void;
status: AiPanelStatus;
/** Date.now() when the current request started. Drives the elapsed clock while running. */
startedAt?: number | null;
/** Streamed reasoning so far. */
thinking?: string;
/** Streamed output (code) so far. */
writing?: string;
/** After a run: how long the model thought and how long the whole request took, e.g. "1:31" and "2:16". */
thought?: { duration: string; total?: string };
result?: AiPanelResult | null;
error?: React.ReactNode;
/** Allowance meters shown at the bottom of the panel. */
allowance?: React.ReactNode;
generateLabel?: string;
applyLabel?: string;
/** Extra buttons between Apply and Discard, e.g. "Send to Testy". */
resultActions?: React.ReactNode;
onGenerate: () => void;
onFix?: () => void;
onExplain?: () => void;
onCancel?: () => void;
onApply?: () => void;
onDiscard?: () => void;
};
const fileTone = { new: "text-primary", changed: "text-warning", deleted: "text-destructive" } as const;
/**
* The AI side panel: prompt, actions and model picker; a running state with an elapsed clock and
* Thinking / Writing stream boxes; and a result card with checks, evidence, changed files and
* Apply / Discard. Request state comes in through props, so any backend can drive it.
*/
export function AiPanel({
className,
title = "Forge with AI",
badge = "Shared allowance",
promptLabel = "What should it do?",
placeholder = "Describe the change in a sentence or two.",
prompt,
onPromptChange,
models,
model,
onModelChange,
status,
startedAt,
thinking = "",
writing = "",
thought,
result,
error,
allowance,
generateLabel = "Generate",
applyLabel = "Apply to editor",
resultActions,
onGenerate,
onFix,
onExplain,
onCancel,
onApply,
onDiscard,
...props
}: AiPanelProps) {
const promptId = React.useId();
const running = status === "running";
const elapsed = useElapsed(running ? startedAt : null);
const canSend = prompt.trim().length > 0 && !running;
const hasWriting = writing.length > 0;
// Thinking starts open and folds away once the model starts writing.
const [thinkingOpen, setThinkingOpen] = React.useState(true);
React.useEffect(() => setThinkingOpen(!hasWriting), [hasWriting]);
const announcement = running ? (hasWriting ? "Writing" : "Thinking") : status === "result" ? "Result ready" : "";
return (
<section
data-slot="ai-panel"
aria-label={typeof title === "string" ? title : "AI"}
aria-busy={running}
className={cn("flex min-h-0 min-w-0 flex-col gap-3.5 bg-card p-4", className)}
{...props}
>
<span className="sr-only" aria-live="polite">
{announcement}
</span>
<div className="flex items-center gap-2">
<SparklesIcon aria-hidden="true" className="size-4 text-primary" />
<Eyebrow>{title}</Eyebrow>
{badge && (
<span className="ml-auto font-mono text-[10px] tracking-[0.12em] text-muted-foreground uppercase">{badge}</span>
)}
</div>
<div className="grid gap-2">
<Label htmlFor={promptId} className="text-xs font-normal text-muted-foreground">
{promptLabel}
</Label>
<Textarea
id={promptId}
rows={3}
value={prompt}
placeholder={placeholder}
disabled={running}
onChange={(e) => onPromptChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && canSend) {
e.preventDefault();
onGenerate();
}
}}
aria-describedby={`${promptId}-hint`}
className="max-h-48 min-h-[5.5rem] resize-none text-[13px]"
/>
<span id={`${promptId}-hint`} className="sr-only">
Press Control or Command and Enter to generate.
</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button size="sm" onClick={onGenerate} disabled={!canSend}>
<SparklesIcon /> {generateLabel}
</Button>
{onFix && (
<Button size="sm" variant="secondary" onClick={onFix} disabled={running}>
<WrenchIcon /> Fix
</Button>
)}
{onExplain && (
<Button size="sm" variant="secondary" onClick={onExplain} disabled={running}>
<MessageSquareTextIcon /> Explain
</Button>
)}
<Select value={model} onValueChange={onModelChange} disabled={running}>
<SelectTrigger size="sm" aria-label="Model" className="min-w-40 flex-1 font-mono text-[11px]">
<SelectValue placeholder="Model" />
</SelectTrigger>
<SelectContent align="end">
{models.map((m) => (
<SelectItem key={m.value} value={m.value} className="font-mono text-xs">
{m.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="-mr-2 flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto pr-2 pb-2 empty:hidden">
{running && (
<>
<div className="flex items-center gap-2.5">
<span aria-hidden="true" className="size-1.5 animate-lantern-pulse rounded-full bg-primary [animation-duration:1.2s]" />
<span className="font-mono text-[10px] tracking-[0.2em] text-primary uppercase">
{hasWriting ? "Writing" : "Thinking"}
</span>
<span className="font-mono text-xs text-muted-foreground tabular-nums">
{elapsed != null ? formatElapsed(elapsed) : "0:00"}
</span>
{onCancel && (
<Button size="sm" variant="ghost" className="ml-auto h-7 px-2" onClick={onCancel}>
<SquareIcon /> Cancel
</Button>
)}
</div>
<StreamBox
title="Thinking"
text={thinking}
streaming={!hasWriting}
open={thinkingOpen}
onOpenChange={setThinkingOpen}
/>
{hasWriting && <StreamBox title="Writing" text={writing} streaming maxHeight={200} />}
</>
)}
{status === "error" && error && (
<div
role="alert"
className="flex gap-2.5 rounded-md border border-destructive/40 bg-destructive/10 p-3 text-[13px] text-destructive"
>
<CircleAlertIcon aria-hidden="true" className="mt-0.5 size-4 shrink-0" />
<div className="min-w-0">{error}</div>
</div>
)}
{status === "result" && result && (
<>
{thought && thinking && (
<StreamBox
title={`Thought for ${thought.duration}`}
meta={thought.total ? `Whole request ${thought.total}` : undefined}
text={thinking}
defaultOpen={false}
/>
)}
<div
data-slot="ai-panel-result"
className="flex flex-col gap-3 rounded-lg border border-input bg-background p-3.5 shadow-block-sm"
>
{(result.checksPassed !== undefined || result.model) && (
<div className="flex flex-wrap items-center gap-2">
{result.checksPassed !== undefined && (
<Badge variant={result.checksPassed ? "success" : "destructive"}>
{result.checksPassed ? <CheckIcon /> : <CircleXIcon />}
{result.checksLabel ?? (result.checksPassed ? "Checks passed" : "Checks failed")}
</Badge>
)}
{result.model && (
<span className="ml-auto font-mono text-[11px] text-muted-foreground">by {result.model}</span>
)}
</div>
)}
<p className="text-[13px] leading-relaxed">{result.summary}</p>
{result.evidence}
{result.files && result.files.length > 0 && (
<ul aria-label="Changed files" className="flex flex-col gap-1 border-t pt-2.5">
{result.files.map((f) => (
<li key={f.path} className="flex min-w-0 items-baseline gap-3 font-mono text-xs">
<span className={cn("min-w-0 truncate", f.status && fileTone[f.status])}>{f.path}</span>
{f.detail && <span className="ml-auto shrink-0 text-muted-foreground">{f.detail}</span>}
</li>
))}
</ul>
)}
<div className="flex flex-wrap gap-2">
{onApply && (
<Button size="sm" onClick={onApply}>
{applyLabel}
</Button>
)}
{resultActions}
{onDiscard && (
<Button size="sm" variant="outline" onClick={onDiscard}>
Discard
</Button>
)}
</div>
</div>
</>
)}
</div>
{allowance && <div className="mt-auto border-t pt-3">{allowance}</div>}
</section>
);
}
/** An eyebrow title over evidence content, for the result card. */
export function AiPanelEvidence({
title,
className,
children,
...props
}: Omit<React.ComponentProps<"div">, "title"> & { title: React.ReactNode }) {
return (
<div data-slot="ai-panel-evidence" className={cn("flex flex-col gap-2", className)} {...props}>
<Eyebrow>{title}</Eyebrow>
{children}
</div>
);
}
/** A list of checks with a mark each, e.g. test requests and their responses. */
export function AiPanelChecklist({
items,
className,
...props
}: React.ComponentProps<"ul"> & { items: { label: React.ReactNode; ok: boolean }[] }) {
return (
<ul className={cn("flex flex-col gap-1.5 font-mono text-[11px] leading-snug", className)} {...props}>
{items.map((item, i) => (
<li key={i} className="flex gap-2">
{item.ok ? (
<CheckIcon aria-label="Passed" className="mt-px size-3.5 shrink-0 text-success" />
) : (
<CircleXIcon aria-label="Failed" className="mt-px size-3.5 shrink-0 text-destructive" />
)}
<span className="min-w-0 break-words">{item.label}</span>
</li>
))}
</ul>
);
}"use client";
import * as React from "react";
import { Stat, StatGroup, StatLabel, StatValue } from "@/components/ui/stat";
import { formatElapsed } from "@/components/ui/job-card";
import { AiPanelChecklist, AiPanelEvidence, type AiPanelProps, type AiPanelResult, type AiPanelStatus } from "./panel";
// Canned responses so the block runs without a backend. Replace useMockAiRun with calls to your own API.
export const mockModels = [
{ value: "auto", label: "Auto (fast)" },
{ value: "deepseek-flash", label: "DeepSeek V4.1 Flash (thinks)" },
{ value: "qwen-coder", label: "Qwen3 Coder 480B" },
];
const flavors = {
turtledeck: {
title: "Forge with AI",
prompt:
"Strip mine at y=-59 for diamonds: 3 branches of 32, a torch every 8 blocks, come home to unload when full.",
thinking: `Diamonds peak between y=-64 and y=-54, so -59 sits in the middle of the band.
Three branches of 32 blocks, 3 apart, so nothing is skipped between tunnels.
td.mine.stairs walks down first; td.run wraps the loop so a full inventory sends it home to unload.
Each step: check(), dig and move forward, clear the block above for a 2-high tunnel.
Torch on the left wall every 8 blocks.
Fuel estimate: about 480 including the stairs. Testy has 3,602, which is plenty.`,
writing: `local BRANCHES, LENGTH, SPACING = 3, 32, 3
local TORCH_EVERY = 8
td.setHome()
td.mine.stairs{ toY = -59, returnHome = false }
td.run("Diamond strip mine", {}, function(check)
for b = 1, BRANCHES do
for step = 1, LENGTH do
check()
assert(td.digMove("forward"))
td.clear("up")
if step % TORCH_EVERY == 0 then td.placeTorch("left") end
end
td.face((td.facing() + 1) % 4)
for _ = 1, SPACING do td.digMove("forward") end
end
end)`,
result: {
summary:
"Walks down to y=-59 by stairs, mines three 32-block branches three apart with a torch every 8 blocks, and lets td.run bring it home and unload when the inventory fills.",
checksPassed: true,
checksLabel: "Passed TurtleDeck's checks",
files: [{ path: "strip_mine.lua", detail: "new, 23 lines", status: "new" }],
evidence: (
<AiPanelEvidence title="Dry run in a simulated world">
<StatGroup variant="tiles">
<Stat>
<StatLabel>Dug</StatLabel>
<StatValue>214</StatValue>
</Stat>
<Stat>
<StatLabel>Torches</StatLabel>
<StatValue>12</StatValue>
</Stat>
<Stat>
<StatLabel>Fuel</StatLabel>
<StatValue>486</StatValue>
</Stat>
<Stat>
<StatLabel>Ends</StatLabel>
<StatValue>Home</StatValue>
</Stat>
</StatGroup>
</AiPanelEvidence>
),
} satisfies Omit<AiPanelResult, "model">,
},
lantern: {
title: "Build with AI",
prompt:
"Add a guestbook: the form posts to /sign with name and message, show the 10 newest entries, reject empty ones.",
thinking: `Entries live in ctx.read("entries"). Validate the name before writing; a blank or 60+ character name gets a 400.
Keep only the newest 10 so the page stays short.
Redirect back to / after a post so a refresh does not sign twice.
index.json needs the form and a list bound to entries.`,
writing: `local MAX = 10
return function(ctx)
local entries = ctx.read("entries", {})
if ctx.method == "POST" and ctx.path == "/sign" then
local name = ctx.fields.name or ""
local message = ctx.fields.message or ""
if not name:match("%S") or #name > 60 then
return {kind="error", status=400, message="Enter a name."}
end
table.insert(entries, 1, {name=name, message=message})
while #entries > MAX do table.remove(entries) end
ctx.write("entries", entries)
return {kind="redirect", path="/"}
end
end`,
result: {
summary:
"Adds app.lua with a /sign handler that validates the name, keeps the newest 10 entries, and lists them on the home page under the form.",
checksPassed: true,
checksLabel: "Passed Lantern's checks",
files: [
{ path: "app.lua", detail: "new, 47 lines", status: "new" },
{ path: "index.json", detail: "+12 lines", status: "changed" },
],
evidence: (
<AiPanelEvidence title="Test requests">
<AiPanelChecklist
items={[
{ ok: true, label: "POST /sign name=Tim -> redirect /" },
{ ok: true, label: 'POST /sign name="" -> 400 Enter a name' },
{ ok: true, label: 'GET / shows "Tim: Nice base!"' },
]}
/>
</AiPanelEvidence>
),
} satisfies Omit<AiPanelResult, "model">,
},
};
export type MockFlavor = keyof typeof flavors;
/**
* Drives AiPanel with canned streaming text. Returns props to spread on AiPanel, the written code,
* and `show` to jump straight to a state.
*/
export function useMockAiRun(flavor: MockFlavor = "turtledeck", onApply?: (code: string) => void) {
const data = flavors[flavor];
const [prompt, setPrompt] = React.useState(data.prompt);
const [model, setModel] = React.useState("deepseek-flash");
const [status, setStatus] = React.useState<AiPanelStatus>("idle");
const [startedAt, setStartedAt] = React.useState<number | null>(null);
const [thinking, setThinking] = React.useState("");
const [writing, setWriting] = React.useState("");
const [thought, setThought] = React.useState<{ duration: string; total: string } | undefined>();
const timer = React.useRef<ReturnType<typeof setInterval> | null>(null);
const stop = React.useCallback(() => {
if (timer.current) clearInterval(timer.current);
timer.current = null;
}, []);
React.useEffect(() => stop, [stop]);
const finish = React.useCallback(
(start: number, thinkEnd: number) => {
stop();
setThinking(data.thinking);
setWriting(data.writing);
const now = Date.now();
// Scale the demo's seconds up so the summary line reads like a real run.
setThought({ duration: formatElapsed(((thinkEnd - start) / 1000) * 12), total: formatElapsed(((now - start) / 1000) * 12) });
setStatus("result");
},
[data, stop],
);
const generate = React.useCallback(() => {
stop();
const start = Date.now();
let thinkEnd = 0;
let t = 0;
let w = 0;
setStartedAt(start);
setThinking("");
setWriting("");
setThought(undefined);
setStatus("running");
timer.current = setInterval(() => {
if (t < data.thinking.length) {
t = Math.min(data.thinking.length, t + 7);
setThinking(data.thinking.slice(0, t));
if (t === data.thinking.length) thinkEnd = Date.now();
} else if (w < data.writing.length) {
w = Math.min(data.writing.length, w + 9);
setWriting(data.writing.slice(0, w));
} else {
finish(start, thinkEnd);
}
}, 40);
}, [data, finish, stop]);
const reset = React.useCallback(() => {
stop();
setStatus("idle");
setStartedAt(null);
setThinking("");
setWriting("");
setThought(undefined);
}, [stop]);
const show = React.useCallback(
(next: AiPanelStatus) => {
if (next === "running") generate();
else if (next === "result") {
const start = Date.now() - 11_000;
finish(start, start + 7_600);
} else if (next === "error") {
stop();
setStatus("error");
} else reset();
},
[finish, generate, reset, stop],
);
const modelLabel = mockModels.find((m) => m.value === model)?.label.replace(/ \(.*\)$/, "");
const panelProps = {
title: data.title,
prompt,
onPromptChange: setPrompt,
models: mockModels,
model,
onModelChange: setModel,
status,
startedAt,
thinking,
writing,
thought,
result: status === "result" ? { ...data.result, model: modelLabel } : null,
error:
status === "error" ? "The model stopped before finishing. Nothing was charged to your allowance. Try again." : undefined,
onGenerate: generate,
onFix: generate,
onExplain: generate,
onCancel: reset,
onApply: () => {
onApply?.(data.writing);
reset();
},
onDiscard: reset,
} satisfies AiPanelProps;
return { panelProps, status, show, code: data.writing };
}Installation#
$npx lanterncn add ai-panelThis copies all 3 files into components/ai-panel and installs every component it uses. With the shadcn CLI: npx shadcn@latest add httptim/lantern-ui/ai-panel.
Usage#
Render it from any page.
import AIPanel from "@/components/ai-panel/ai-panel";
export default function Page() {
return <AIPanel />;
}ai-panel.tsx is a demo wired to mock.tsx. In your app, import { AiPanel } from "@/components/ai-panel/panel" and drive it from your own backend: set status to running and pass startedAt, then append streamed text to thinking and writing; when the request ends, set status to result and pass result, plus thought for the collapsed "Thought for 1:31" line. Delete mock.tsx once you do.
result.evidence is a slot. The mock shows both kinds from the mockups: dry-run stat tiles (Stat with variant="tiles") and a test-request checklist (AiPanelChecklist). Wrap either in AiPanelEvidence for the eyebrow title.
Ctrl or Cmd and Enter in the prompt runs Generate. Fix and Explain appear only when you pass onFix and onExplain; Cancel only with onCancel. The model picker is the Lantern Select, not a native select.
The panel announces Thinking, Writing and Result ready through one polite live region; the streamed text itself is not announced. Toasts in the demo need the Toaster from the sonner component in your root layout.