Agent State
SaveA calm pill with a small animated dot mark and a verb, for what an agent is doing right now: thinking, searching, working, planning, listening, or shaping.
- Category
- Agent
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React, Vite + Vue
- Styling
- Tailwind CSS v4
Preview
Agent State preview
Sizes
SearchingSearchingSearching
ThinkingSearchingWorkingPlanningListeningShaping
Phases
Writing the summaryWaiting for approvalQueuedDoneFailedCancelled
Installation
npx @shakenui/cli add agent-stateReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add agent-state --dry-runUsage
agent-state-example.tsx
import { AgentState } from "@/components/shaken/agent/agent-state";
export default function AgentStateExample() {
return (
<div className="flex flex-wrap items-center justify-center gap-3">
<AgentState activity="thinking" status />
<AgentState activity="searching" label="Searching the docs" />
<AgentState activity="working" phase="done" label="Opened a pull request" />
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| activity | "thinking" | "searching" | "working" | "planning" | "listening" | "shaping" | "thinking" | Picks the mark (dot sphere, scanning globe, constellation, sparse spinner, dotted ring, dotted triangle) and the default verb. |
| label | ReactNode | — | Replaces the verb, for example "Reading the docs". While active an ellipsis follows it. |
| phase | "active" | "idle" | "waiting" | "done" | "failed" | "cancelled" | "active" | active animates the mark; waiting holds it still; idle, done, failed, and cancelled swap it for a still glyph. |
| size | "sm" | "md" | "lg" | "md" | 24, 32, or 44px tall, with 14, 18, or 26px marks. |
| variant | "pill" | "plain" | "pill" | pill draws the rounded hairline container; plain is the mark and verb alone, for rows and inline use. |
| status | boolean | false | Makes the pill a polite live region (role="status") so label changes are announced. |
| OrbMark, ScanMark, ConstellationMark, SparkMark, RingMark, PrismMark | ({ size?, paused?, className? }) => JSX | — | The marks on their own. They draw in currentColor, so set the color with a text class. AgentMark picks one by activity. |
Accessibility
- Marks are decorative (aria-hidden); the verb is real text. The ellipsis is generated content, so the label text stays exactly what you pass.
- With status set, the pill is a polite live region and announces the new verb when the activity changes.
- Under reduced motion every mark renders one still frame; the verb and phase glyphs still change.
- Marks pause when scrolled out of view or when the tab is hidden, and stop all work when unmounted.
- Settled phases add a shape as well as color: a check for done, an x for failed, a slash for cancelled, a dashed circle for idle.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/agent/agent-state.tsxagent-state- npm packages: noneReact and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/agent-state/0.1.0.json.
agent/agent-state.tsxShowHide
agent/agent-state.tsx
"use client";
import { type ComponentProps, type ReactNode, useEffect, useRef } from "react";
/*
* Agent state: a calm pill with a small animated mark and a verb ("Searching…").
*
* Each mark is a few dozen dots and hairlines drawn on a tiny canvas in `currentColor`,
* so it follows light and dark themes. All marks share one requestAnimationFrame loop;
* a mark only draws while it is on screen, the tab is visible, and motion is allowed.
* Under reduced motion each mark renders one still frame.
*/
export type AgentActivity = "thinking" | "searching" | "working" | "planning" | "listening" | "shaping";
export type AgentPhase = "active" | "idle" | "waiting" | "done" | "failed" | "cancelled";
export type AgentStateSize = "sm" | "md" | "lg";
export const agentActivities: AgentActivity[] = ["thinking", "searching", "working", "planning", "listening", "shaping"];
const verbs: Record<AgentActivity, string> = {
thinking: "Thinking",
searching: "Searching",
working: "Working",
planning: "Planning",
listening: "Listening",
shaping: "Shaping",
};
const phaseLabels: Record<Exclude<AgentPhase, "active">, string> = {
idle: "Queued",
waiting: "Waiting",
done: "Done",
failed: "Failed",
cancelled: "Cancelled",
};
// ---------------------------------------------------------------------------
// Frame loop and canvas plumbing
type Paint = (ctx: CanvasRenderingContext2D, t: number, size: number) => void;
const loops = new Set<(now: number) => void>();
let frame = 0;
function tick(now: number) {
frame = 0;
for (const loop of loops) loop(now);
if (loops.size) frame = requestAnimationFrame(tick);
}
function addLoop(loop: (now: number) => void) {
loops.add(loop);
if (!frame) frame = requestAnimationFrame(tick);
}
function removeLoop(loop: (now: number) => void) {
loops.delete(loop);
if (!loops.size && frame) {
cancelAnimationFrame(frame);
frame = 0;
}
}
export interface MarkProps extends Omit<ComponentProps<"canvas">, "children" | "width" | "height"> {
/** Width and height in CSS pixels. */
size?: number;
/** Holds the current frame instead of animating. */
paused?: boolean;
}
function useMarkCanvas(paint: Paint, size: number, still: number, paused: boolean) {
const ref = useRef<HTMLCanvasElement>(null);
// The last drawn time, so pausing holds the pose instead of jumping to the still frame.
const lastT = useRef<number | null>(null);
useEffect(() => {
const canvas = ref.current;
const ctx = canvas?.getContext("2d");
if (!canvas || !ctx) return;
const dpr = Math.min(window.devicePixelRatio || 1, 3);
canvas.width = Math.round(size * dpr);
canvas.height = Math.round(size * dpr);
let color = "";
let colorCheckedAt = -Infinity;
let visible = true;
let running = false;
let watcher: ReturnType<typeof setInterval> | undefined;
const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
const readColor = () => {
const next = getComputedStyle(canvas).color;
const changed = next !== color;
color = next;
return changed;
};
const draw = (t: number) => {
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, size, size);
ctx.fillStyle = color;
ctx.strokeStyle = color;
ctx.globalAlpha = 1;
paint(ctx, t, size);
ctx.globalAlpha = 1;
};
const stillTime = () => (motion.matches ? still : (lastT.current ?? still));
const loop = (now: number) => {
// Theme switches change currentColor; checking twice a second is plenty.
if (now - colorCheckedAt > 500) {
readColor();
colorCheckedAt = now;
}
const t = now / 1000;
lastT.current = t;
draw(t);
};
const update = () => {
const animate = visible && !document.hidden && !motion.matches && !paused;
if (animate && !running) {
running = true;
readColor();
colorCheckedAt = performance.now();
addLoop(loop);
} else if (!animate && running) {
running = false;
removeLoop(loop);
}
clearInterval(watcher);
watcher = undefined;
if (!animate) {
readColor();
draw(stillTime());
// A still mark still follows theme changes while it is on screen.
if (visible && !document.hidden) {
watcher = setInterval(() => {
if (readColor()) draw(stillTime());
}, 600);
}
}
};
readColor();
draw(stillTime());
const observer = typeof IntersectionObserver === "undefined"
? null
: new IntersectionObserver((entries) => {
visible = entries.some((entry) => entry.isIntersecting);
update();
});
observer?.observe(canvas);
document.addEventListener("visibilitychange", update);
motion.addEventListener("change", update);
update();
return () => {
running = false;
removeLoop(loop);
clearInterval(watcher);
observer?.disconnect();
document.removeEventListener("visibilitychange", update);
motion.removeEventListener("change", update);
};
}, [paint, size, still, paused]);
return ref;
}
function createMark(name: string, paint: Paint, still: number) {
function Mark({ size = 18, paused = false, className, style, ...props }: MarkProps) {
const ref = useMarkCanvas(paint, size, still, paused);
return (
<canvas
ref={ref}
aria-hidden="true"
data-mark={name}
className={["shrink-0", className].filter(Boolean).join(" ")}
style={{ width: size, height: size, ...style }}
{...props}
/>
);
}
Mark.displayName = name;
return Mark;
}
// ---------------------------------------------------------------------------
// Geometry helpers
const TAU = Math.PI * 2;
type Point = [number, number, number];
function dot(ctx: CanvasRenderingContext2D, x: number, y: number, r: number, alpha: number) {
ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
ctx.beginPath();
ctx.arc(x, y, r, 0, TAU);
ctx.fill();
}
/** Rotates around the vertical axis by `yaw`, then tilts toward the viewer by `pitch`. */
function rotate([x, y, z]: Point, yaw: number, pitch: number): Point {
const cy = Math.cos(yaw);
const sy = Math.sin(yaw);
const x1 = x * cy + z * sy;
const z1 = -x * sy + z * cy;
const cp = Math.cos(pitch);
const sp = Math.sin(pitch);
return [x1, y * cp - z1 * sp, y * sp + z1 * cp];
}
const memo = new Map<string, Point[]>();
function cached(key: string, build: () => Point[]): Point[] {
let points = memo.get(key);
if (!points) {
points = build();
memo.set(key, points);
}
return points;
}
/** Evenly spread points on a unit sphere (golden-angle spiral). */
function sphere(count: number): Point[] {
return cached(`sphere:${count}`, () => {
const golden = Math.PI * (3 - Math.sqrt(5));
return Array.from({ length: count }, (_, i) => {
const y = 1 - (i / (count - 1)) * 2;
const r = Math.sqrt(1 - y * y);
return [Math.cos(golden * i) * r, y, Math.sin(golden * i) * r] as Point;
});
});
}
/** Dots laid out on latitude rings, like a wire globe. */
function globe(rows: number): Point[] {
return cached(`globe:${rows}`, () => {
const points: Point[] = [];
for (let i = 1; i <= rows; i++) {
const lat = -Math.PI / 2 + (Math.PI * i) / (rows + 1);
const ring = Math.cos(lat);
const count = Math.max(4, Math.round(ring * rows * 2.3));
for (let j = 0; j < count; j++) {
const lon = (TAU * j) / count + ((i % 2) * Math.PI) / count;
points.push([Math.cos(lon) * ring, Math.sin(lat), Math.sin(lon) * ring]);
}
}
return points;
});
}
/** Dot radius that stays visible at small sizes without turning into blobs at large ones. */
const dotRadius = (size: number) => Math.max(0.6, size * 0.034);
// ---------------------------------------------------------------------------
// Marks
/** A dot sphere turning slowly, nearer dots brighter and larger. A soft ripple drifts over it. */
export const OrbMark = createMark(
"OrbMark",
(ctx, t, s) => {
const c = s / 2;
const R = s * 0.42;
const count = Math.round(Math.min(140, Math.max(36, s * s * 0.2)));
const yaw = t * 1.05;
const pitch = 0.38 + Math.sin(t * 0.7) * 0.08;
const base = dotRadius(s);
for (const point of sphere(count)) {
const [x, y, z] = rotate(point, yaw, pitch);
const depth = (z + 1) / 2;
const ripple = 0.78 + 0.22 * Math.sin(point[1] * 3.2 - t * 2.4);
dot(ctx, c + x * R, c + y * R, base * (0.5 + 0.7 * depth), (0.08 + 0.92 * depth * depth) * ripple);
}
},
0.6,
);
/** A globe of latitude rings with a bright band sweeping up and down, like a scan. */
export const ScanMark = createMark(
"ScanMark",
(ctx, t, s) => {
const c = s / 2;
const R = s * 0.42;
const rows = s < 22 ? 7 : s < 34 ? 9 : 11;
const band = Math.sin(t * 1.6) * 0.82;
const base = dotRadius(s) * 0.9;
// A hairline chord marks where the scan is.
const half = Math.sqrt(Math.max(0, 1 - band * band)) * R;
ctx.globalAlpha = 0.22;
ctx.fillRect(c - half, c + band * R - 0.25, half * 2, 0.5);
for (const point of globe(rows)) {
const [x, y, z] = rotate(point, t * 0.7, 0.24);
const depth = (z + 1) / 2;
const glow = Math.exp(-((y - band) ** 2) / 0.03);
const alpha = 0.06 + 0.36 * depth + glow * (0.35 + 0.6 * depth);
dot(ctx, c + x * R, c + y * R, base * (0.6 + 0.4 * depth) * (1 + 0.5 * glow), alpha);
}
},
0.35,
);
const constellation = cached("constellation", () =>
sphere(14).map(([x, y, z], i) => {
// Deterministic jitter so the nodes read as scattered, not as a grid.
const j = Math.sin(i * 12.9898) * 43758.5453;
const k = (j - Math.floor(j) - 0.5) * 0.5;
const len = Math.hypot(x + k, y - k * 0.6, z + k * 0.4) || 1;
return [(x + k) / len, (y - k * 0.6) / len, (z + k * 0.4) / len] as Point;
}),
);
const links: [number, number][] = (() => {
const pairs = new Set<string>();
constellation.forEach((a, i) => {
constellation
.map((b, j) => ({ j, d: Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) }))
.filter(({ j }) => j !== i)
.sort((p, q) => p.d - q.d)
.slice(0, 2)
.forEach(({ j }) => pairs.add(i < j ? `${i}-${j}` : `${j}-${i}`));
});
return [...pairs].map((pair) => pair.split("-").map(Number) as [number, number]);
})();
/** Scattered nodes joined by hairlines, turning in space; a signal hops from link to link. */
export const ConstellationMark = createMark(
"ConstellationMark",
(ctx, t, s) => {
const c = s / 2;
const R = s * 0.4;
const yaw = t * 0.8;
const pitch = 0.5 + Math.sin(t * 0.5) * 0.15;
const projected = constellation.map((point) => rotate(point, yaw, pitch));
const base = dotRadius(s);
ctx.lineWidth = Math.max(0.5, s * 0.022);
for (const [a, b] of links) {
const p = projected[a]!;
const q = projected[b]!;
ctx.globalAlpha = 0.08 + 0.3 * ((p[2] + q[2] + 2) / 4);
ctx.beginPath();
ctx.moveTo(c + p[0] * R, c + p[1] * R);
ctx.lineTo(c + q[0] * R, c + q[1] * R);
ctx.stroke();
}
for (const [x, y, z] of projected) {
const depth = (z + 1) / 2;
dot(ctx, c + x * R, c + y * R, base * 1.1 * (0.6 + 0.6 * depth), 0.25 + 0.75 * depth);
}
// The signal eases along one link, then moves to the next.
const step = t * 1.2;
const [a, b] = links[Math.floor(step) % links.length]!;
const p = projected[a]!;
const q = projected[b]!;
const f = step - Math.floor(step);
const e = f * f * (3 - 2 * f);
const depth = (p[2] + (q[2] - p[2]) * e + 1) / 2;
dot(ctx, c + (p[0] + (q[0] - p[0]) * e) * R, c + (p[1] + (q[1] - p[1]) * e) * R, base * 1.5, 0.55 + 0.45 * depth);
},
1.1,
);
/** A dotted ring whose dots lift and brighten unevenly, like a voice level. */
export const RingMark = createMark(
"RingMark",
(ctx, t, s) => {
const c = s / 2;
const count = s < 22 ? 12 : 16;
const R = s * 0.34;
const base = dotRadius(s) * 1.05;
for (let i = 0; i < count; i++) {
const angle = (TAU * i) / count + t * 0.5;
const level = (Math.sin(t * 3.1 + i * 1.3) * Math.sin(t * 1.7 + i * 0.7) + 1) / 2;
const r = R + level * s * 0.07;
dot(ctx, c + Math.cos(angle) * r, c + Math.sin(angle) * r, base * (0.75 + 0.6 * level), 0.22 + 0.78 * level);
}
},
1.2,
);
/** Sparse dots on two radii; a light sweeps around them and leaves a fading trail. */
export const SparkMark = createMark(
"SparkMark",
(ctx, t, s) => {
const c = s / 2;
const count = 10;
const head = t * 2.2;
const base = dotRadius(s) * 1.1;
for (let i = 0; i < count; i++) {
const angle = (TAU * i) / count - Math.PI / 2;
const behind = (((head - angle) % TAU) + TAU) % TAU;
const lit = Math.exp(-behind * 0.8);
const r = (i % 2 ? 0.25 : 0.4) * s * (1 + 0.06 * lit);
dot(ctx, c + Math.cos(angle) * r, c + Math.sin(angle) * r, base * (0.85 + 0.65 * lit), 0.22 + 0.78 * lit);
}
},
0.9,
);
/** A dotted triangle that turns gently while light travels along its edges. */
export const PrismMark = createMark(
"PrismMark",
(ctx, t, s) => {
const c = s / 2;
const R = s * 0.42;
const perEdge = s < 22 ? 5 : 7;
const turn = Math.cos(Math.sin(t * 0.9) * 0.55);
// Lower the centroid slightly so the triangle looks centered, not top heavy.
const cy = c + s * 0.05;
const corners = [-Math.PI / 2, Math.PI / 6, (5 * Math.PI) / 6].map((angle) => [c + Math.cos(angle) * R * turn, cy + Math.sin(angle) * R]);
const headU = (t * 0.28) % 1;
const base = dotRadius(s);
for (let edge = 0; edge < 3; edge++) {
const [ax, ay] = corners[edge]!;
const [bx, by] = corners[(edge + 1) % 3]!;
for (let m = 0; m < perEdge; m++) {
const f = m / perEdge;
const u = (edge + f) / 3;
const d = Math.min(Math.abs(u - headU), 1 - Math.abs(u - headU));
const glow = Math.exp(-(d * d) / 0.006);
const corner = m === 0 ? 0.18 : 0;
dot(ctx, ax! + (bx! - ax!) * f, ay! + (by! - ay!) * f, base * (0.9 + 0.7 * glow + corner * 2), 0.32 + corner + 0.68 * glow);
}
}
},
0.8,
);
export type MarkComponent = typeof OrbMark;
/** The mark drawn for each activity. */
export const agentMarks: Record<AgentActivity, MarkComponent> = {
thinking: OrbMark,
searching: ScanMark,
working: ConstellationMark,
planning: SparkMark,
listening: RingMark,
shaping: PrismMark,
};
/** The mark for an activity on its own, e.g. inline after streaming text. */
export function AgentMark({ activity = "thinking", ...props }: MarkProps & { activity?: AgentActivity }) {
const Mark = agentMarks[activity];
return <Mark {...props} />;
}
// ---------------------------------------------------------------------------
// The pill
const sizes: Record<AgentStateSize, { mark: number; pill: string; plain: string }> = {
sm: { mark: 14, pill: "h-6 gap-1.5 pr-2.5 pl-2 text-xs", plain: "gap-1.5 text-xs" },
md: { mark: 18, pill: "h-8 gap-2 pr-3.5 pl-2.5 text-[13px]", plain: "gap-2 text-[13px]" },
lg: { mark: 26, pill: "h-11 gap-2.5 pr-5 pl-3 text-[15px]", plain: "gap-2.5 text-[15px]" },
};
const labelTone: Record<AgentPhase, string> = {
active: "text-zinc-600 dark:text-zinc-400",
idle: "text-zinc-500",
waiting: "text-amber-700 dark:text-amber-400",
done: "text-zinc-600 dark:text-zinc-400",
// The red x carries the failure; the text stays readable rather than shouting.
failed: "text-zinc-600 dark:text-zinc-400",
cancelled: "text-zinc-500",
};
const swap =
"transition-[opacity,scale,filter] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] starting:scale-90 starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none";
export interface AgentStateProps extends Omit<ComponentProps<"span">, "children" | "role"> {
/** What the agent is doing; picks the mark and the default verb. */
activity?: AgentActivity;
/** Replaces the verb, e.g. "Reading the docs". While active an ellipsis follows it. */
label?: ReactNode;
/**
* active animates the mark; waiting holds it still; idle, done, failed, and cancelled
* replace it with a still glyph. Defaults to active.
*/
phase?: AgentPhase;
size?: AgentStateSize;
/** pill draws the rounded hairline container; plain is the mark and verb alone. */
variant?: "pill" | "plain";
/** Makes it a polite live region (role="status") so changes to the label are announced. */
status?: boolean;
}
/** A rounded pill with an animated mark and a verb, for what an agent is doing right now. */
export function AgentState({
activity = "thinking",
label,
phase = "active",
size = "md",
variant = "pill",
status = false,
className,
...props
}: AgentStateProps) {
const config = sizes[size];
const text = label ?? (phase === "active" ? verbs[activity] : phaseLabels[phase]);
const active = phase === "active";
// The ellipsis is generated content, so the element's text stays exactly the label.
const ellipsis = active && !(typeof text === "string" && /(…|\.\.\.)$/.test(text));
return (
<span
role={status ? "status" : undefined}
data-activity={activity}
data-phase={phase}
className={[
"inline-flex max-w-full items-center leading-none whitespace-nowrap select-none",
variant === "pill"
? [
config.pill,
"rounded-full border border-zinc-950/10 bg-zinc-950/[0.015] shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
"dark:border-white/10 dark:bg-white/[0.03] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
].join(" ")
: config.plain,
className,
]
.filter(Boolean)
.join(" ")}
{...props}
>
<span key={`${phase}-${activity}`} aria-hidden="true" className={`inline-flex shrink-0 ${swap}`}>
{active || phase === "waiting" ? (
<AgentMark
activity={activity}
size={config.mark}
paused={!active}
className={active ? "text-zinc-950 dark:text-white" : "text-zinc-950/45 dark:text-white/45"}
/>
) : (
<PhaseGlyph phase={phase} size={config.mark} />
)}
</span>
<span
key={typeof text === "string" ? text : undefined}
className={[
"min-w-0 truncate py-0.5",
labelTone[phase],
ellipsis ? "after:content-['…']" : "",
"transition-[opacity,filter,translate] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] starting:translate-y-[3px] starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none",
].join(" ")}
>
{text}
</span>
</span>
);
}
/** Still glyphs for settled phases, scaled to the mark size so the pill keeps its width. */
function PhaseGlyph({ phase, size }: { phase: Exclude<AgentPhase, "active" | "waiting">; size: number }) {
const tone =
phase === "done" ? "text-emerald-600 dark:text-emerald-400" : phase === "failed" ? "text-red-600 dark:text-red-400" : "text-zinc-400 dark:text-zinc-500";
return (
<svg
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth={size >= 24 ? 1.1 : 1.5}
strokeLinecap="round"
strokeLinejoin="round"
className={`shrink-0 ${tone}`}
style={{ width: size, height: size }}
>
{phase === "done" ? (
<path
d="m4.25 8.4 2.5 2.45 5-5.6"
pathLength={1}
strokeDasharray="1"
className="[stroke-dashoffset:0] transition-[stroke-dashoffset] delay-75 duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] starting:[stroke-dashoffset:1] motion-reduce:transition-none"
/>
) : phase === "failed" ? (
<path d="m5 5 6 6m0-6-6 6" />
) : phase === "cancelled" ? (
<>
<circle cx="8" cy="8" r="5.5" strokeOpacity="0.6" />
<path d="m5.6 10.4 4.8-4.8" />
</>
) : (
<circle cx="8" cy="8" r="5.5" strokeDasharray="1.6 2.2" />
)}
</svg>
);
}Vue
A native Vue 3 implementation ships in the Vue pilot. Run the same command in a Vite + Vue project; the CLI detects Vue and installs these files instead. The live preview above is the React version; the Vue example below is built in a clean Vite + Vue app by CI.
agent-state-example.vue
<script setup lang="ts">
import AgentState from "@/components/shaken/agent/AgentState.vue";
</script>
<template>
<div class="flex flex-wrap items-center justify-center gap-3">
<AgentState activity="thinking" status />
<AgentState activity="searching" label="Searching the docs" />
<AgentState activity="working" phase="done" label="Opened a pull request" />
</div>
</template>src/components/shaken/agent/AgentState.vuevue/agent-state@0.1.0src/components/shaken/agent/AgentMark.vuevue/agent-state@0.1.0src/components/shaken/agent/agent-marks.tsvue/agent-state@0.1.0
agent/AgentState.vueShowHide
agent/AgentState.vue
<script lang="ts">
export type { AgentActivity, AgentPhase } from "./agent-marks";
</script>
<script setup lang="ts">
import { computed } from "vue";
import AgentMark from "./AgentMark.vue";
import type { AgentActivity, AgentPhase } from "./agent-marks";
/** A rounded pill with an animated mark and a verb, for what an agent is doing right now. */
const props = withDefaults(
defineProps<{
/** What the agent is doing; picks the mark and the default verb. */
activity?: AgentActivity;
/** Replaces the verb, e.g. "Reading the docs". While active an ellipsis follows it. */
label?: string;
/**
* active animates the mark; waiting holds it still; idle, done, failed, and cancelled
* replace it with a still glyph.
*/
phase?: AgentPhase;
size?: "sm" | "md" | "lg";
/** pill draws the rounded hairline container; plain is the mark and verb alone. */
variant?: "pill" | "plain";
/** Makes it a polite live region (role="status") so changes to the label are announced. */
status?: boolean;
}>(),
{ activity: "thinking", phase: "active", size: "md", variant: "pill", status: false },
);
const verbs: Record<AgentActivity, string> = {
thinking: "Thinking",
searching: "Searching",
working: "Working",
planning: "Planning",
listening: "Listening",
shaping: "Shaping",
};
const phaseLabels: Record<Exclude<AgentPhase, "active">, string> = {
idle: "Queued",
waiting: "Waiting",
done: "Done",
failed: "Failed",
cancelled: "Cancelled",
};
const sizes = {
sm: { mark: 14, pill: "h-6 gap-1.5 pr-2.5 pl-2 text-xs", plain: "gap-1.5 text-xs" },
md: { mark: 18, pill: "h-8 gap-2 pr-3.5 pl-2.5 text-[13px]", plain: "gap-2 text-[13px]" },
lg: { mark: 26, pill: "h-11 gap-2.5 pr-5 pl-3 text-[15px]", plain: "gap-2.5 text-[15px]" },
} as const;
const labelTone: Record<AgentPhase, string> = {
active: "text-zinc-600 dark:text-zinc-400",
idle: "text-zinc-500",
waiting: "text-amber-700 dark:text-amber-400",
done: "text-zinc-600 dark:text-zinc-400",
// The red x carries the failure; the text stays readable rather than shouting.
failed: "text-zinc-600 dark:text-zinc-400",
cancelled: "text-zinc-500",
};
const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
const swap = `transition-[opacity,scale,filter] duration-300 ${ease} starting:scale-90 starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`;
const config = computed(() => sizes[props.size]);
const text = computed(() => props.label ?? (props.phase === "active" ? verbs[props.activity] : phaseLabels[props.phase]));
const active = computed(() => props.phase === "active");
// The ellipsis is generated content, so the element's text stays exactly the label.
const ellipsis = computed(() => active.value && !/(…|\.\.\.)$/.test(text.value));
const glyphTone = computed(() =>
props.phase === "done"
? "text-emerald-600 dark:text-emerald-400"
: props.phase === "failed"
? "text-red-600 dark:text-red-400"
: "text-zinc-400 dark:text-zinc-500",
);
</script>
<template>
<span
:role="props.status ? 'status' : undefined"
:data-activity="props.activity"
:data-phase="props.phase"
:class="[
'inline-flex max-w-full items-center leading-none whitespace-nowrap select-none',
props.variant === 'pill'
? [
config.pill,
'rounded-full border border-zinc-950/10 bg-zinc-950/[0.015] shadow-[0_1px_2px_rgb(0_0_0/0.04)]',
'dark:border-white/10 dark:bg-white/[0.03] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]',
]
: config.plain,
]"
>
<span :key="`${props.phase}-${props.activity}`" aria-hidden="true" :class="['inline-flex shrink-0', swap]">
<AgentMark
v-if="active || props.phase === 'waiting'"
:activity="props.activity"
:size="config.mark"
:paused="!active"
:class="active ? 'text-zinc-950 dark:text-white' : 'text-zinc-950/45 dark:text-white/45'"
/>
<!-- Still glyphs for settled phases, scaled to the mark size so the pill keeps its width. -->
<svg
v-else
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
:stroke-width="config.mark >= 24 ? 1.1 : 1.5"
stroke-linecap="round"
stroke-linejoin="round"
:class="['shrink-0', glyphTone]"
:style="{ width: `${config.mark}px`, height: `${config.mark}px` }"
>
<path
v-if="props.phase === 'done'"
d="m4.25 8.4 2.5 2.45 5-5.6"
path-length="1"
stroke-dasharray="1"
:class="`[stroke-dashoffset:0] transition-[stroke-dashoffset] delay-75 duration-300 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`"
/>
<path v-else-if="props.phase === 'failed'" d="m5 5 6 6m0-6-6 6" />
<template v-else-if="props.phase === 'cancelled'">
<circle cx="8" cy="8" r="5.5" stroke-opacity="0.6" />
<path d="m5.6 10.4 4.8-4.8" />
</template>
<circle v-else cx="8" cy="8" r="5.5" stroke-dasharray="1.6 2.2" />
</svg>
</span>
<span
:key="text"
:class="[
'min-w-0 truncate py-0.5',
labelTone[props.phase],
ellipsis ? `after:content-['…']` : '',
`transition-[opacity,filter,translate] duration-300 ${ease} starting:translate-y-[3px] starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`,
]"
>{{ text }}</span
>
</span>
</template>agent/AgentMark.vueShowHide
agent/AgentMark.vue
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { type AgentActivity, attachMark } from "./agent-marks";
/** One Agent State mark on its own, e.g. a step that is running or after streaming text. */
const props = withDefaults(
defineProps<{
activity?: AgentActivity;
/** Width and height in CSS pixels. */
size?: number;
/** Holds the current frame instead of animating. */
paused?: boolean;
}>(),
{ activity: "thinking", size: 18, paused: false },
);
const canvas = ref<HTMLCanvasElement | null>(null);
// The last drawn time, so pausing holds the pose instead of jumping to the still frame.
const lastT = { value: null as number | null };
let stop = () => {};
function start() {
stop();
if (canvas.value) stop = attachMark(canvas.value, { activity: props.activity, size: props.size, paused: props.paused }, lastT);
}
onMounted(start);
watch(() => [props.activity, props.size, props.paused], start);
onBeforeUnmount(() => stop());
</script>
<template>
<canvas
ref="canvas"
aria-hidden="true"
:data-mark="props.activity"
class="shrink-0"
:style="{ width: `${props.size}px`, height: `${props.size}px` }"
/>
</template>agent/agent-marks.tsShowHide
agent/agent-marks.ts
// The Agent State marks: a few dozen dots and hairlines drawn on a small canvas in
// `currentColor`, so they follow light and dark themes. Framework independent: AgentMark.vue
// attaches one to a <canvas>. All marks share one requestAnimationFrame loop; a mark only
// draws while it is on screen, the tab is visible, and motion is allowed. Under reduced
// motion each mark renders one still frame.
export type AgentActivity = "thinking" | "searching" | "working" | "planning" | "listening" | "shaping";
export type AgentPhase = "active" | "idle" | "waiting" | "done" | "failed" | "cancelled";
export const agentActivities: AgentActivity[] = ["thinking", "searching", "working", "planning", "listening", "shaping"];
type Paint = (ctx: CanvasRenderingContext2D, t: number, size: number) => void;
/** How a mark draws at time `t` (seconds), and the time used for its still frame. */
export interface MarkSpec {
paint: Paint;
still: number;
}
function mark(paint: Paint, still: number): MarkSpec {
return { paint, still };
}
// ---------------------------------------------------------------------------
// Frame loop
const loops = new Set<(now: number) => void>();
let frame = 0;
function tick(now: number) {
frame = 0;
for (const loop of loops) loop(now);
if (loops.size) frame = requestAnimationFrame(tick);
}
function addLoop(loop: (now: number) => void) {
loops.add(loop);
if (!frame) frame = requestAnimationFrame(tick);
}
function removeLoop(loop: (now: number) => void) {
loops.delete(loop);
if (!loops.size && frame) {
cancelAnimationFrame(frame);
frame = 0;
}
}
export interface MarkOptions {
activity: AgentActivity;
/** Width and height in CSS pixels. */
size: number;
/** Holds the current frame instead of animating. */
paused: boolean;
}
/**
* Draws a mark into a canvas and keeps it animating while it should. Returns a function that
* stops it. Call it again with new options to switch marks; a paused mark keeps its pose.
*/
export function attachMark(canvas: HTMLCanvasElement, { activity, size, paused }: MarkOptions, lastT: { value: number | null }): () => void {
const ctx = canvas.getContext("2d");
if (!ctx) return () => {};
const { paint, still } = agentMarks[activity];
const dpr = Math.min(window.devicePixelRatio || 1, 3);
canvas.width = Math.round(size * dpr);
canvas.height = Math.round(size * dpr);
let color = "";
let colorCheckedAt = -Infinity;
let visible = true;
let running = false;
let watcher: ReturnType<typeof setInterval> | undefined;
const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
const readColor = () => {
const next = getComputedStyle(canvas).color;
const changed = next !== color;
color = next;
return changed;
};
const draw = (t: number) => {
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, size, size);
ctx.fillStyle = color;
ctx.strokeStyle = color;
ctx.globalAlpha = 1;
paint(ctx, t, size);
ctx.globalAlpha = 1;
};
const stillTime = () => (motion.matches ? still : (lastT.value ?? still));
const loop = (now: number) => {
// Theme switches change currentColor; checking twice a second is plenty.
if (now - colorCheckedAt > 500) {
readColor();
colorCheckedAt = now;
}
const t = now / 1000;
lastT.value = t;
draw(t);
};
const update = () => {
const animate = visible && !document.hidden && !motion.matches && !paused;
if (animate && !running) {
running = true;
readColor();
colorCheckedAt = performance.now();
addLoop(loop);
} else if (!animate && running) {
running = false;
removeLoop(loop);
}
clearInterval(watcher);
watcher = undefined;
if (!animate) {
readColor();
draw(stillTime());
// A still mark still follows theme changes while it is on screen.
if (visible && !document.hidden) {
watcher = setInterval(() => {
if (readColor()) draw(stillTime());
}, 600);
}
}
};
readColor();
draw(stillTime());
const observer =
typeof IntersectionObserver === "undefined"
? null
: new IntersectionObserver((entries) => {
visible = entries.some((entry) => entry.isIntersecting);
update();
});
observer?.observe(canvas);
document.addEventListener("visibilitychange", update);
motion.addEventListener("change", update);
update();
return () => {
running = false;
removeLoop(loop);
clearInterval(watcher);
observer?.disconnect();
document.removeEventListener("visibilitychange", update);
motion.removeEventListener("change", update);
};
}
// ---------------------------------------------------------------------------
// Geometry helpers
const TAU = Math.PI * 2;
type Point = [number, number, number];
function dot(ctx: CanvasRenderingContext2D, x: number, y: number, r: number, alpha: number) {
ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
ctx.beginPath();
ctx.arc(x, y, r, 0, TAU);
ctx.fill();
}
/** Rotates around the vertical axis by `yaw`, then tilts toward the viewer by `pitch`. */
function rotate([x, y, z]: Point, yaw: number, pitch: number): Point {
const cy = Math.cos(yaw);
const sy = Math.sin(yaw);
const x1 = x * cy + z * sy;
const z1 = -x * sy + z * cy;
const cp = Math.cos(pitch);
const sp = Math.sin(pitch);
return [x1, y * cp - z1 * sp, y * sp + z1 * cp];
}
const memo = new Map<string, Point[]>();
function cached(key: string, build: () => Point[]): Point[] {
let points = memo.get(key);
if (!points) {
points = build();
memo.set(key, points);
}
return points;
}
/** Evenly spread points on a unit sphere (golden-angle spiral). */
function sphere(count: number): Point[] {
return cached(`sphere:${count}`, () => {
const golden = Math.PI * (3 - Math.sqrt(5));
return Array.from({ length: count }, (_, i) => {
const y = 1 - (i / (count - 1)) * 2;
const r = Math.sqrt(1 - y * y);
return [Math.cos(golden * i) * r, y, Math.sin(golden * i) * r] as Point;
});
});
}
/** Dots laid out on latitude rings, like a wire globe. */
function globe(rows: number): Point[] {
return cached(`globe:${rows}`, () => {
const points: Point[] = [];
for (let i = 1; i <= rows; i++) {
const lat = -Math.PI / 2 + (Math.PI * i) / (rows + 1);
const ring = Math.cos(lat);
const count = Math.max(4, Math.round(ring * rows * 2.3));
for (let j = 0; j < count; j++) {
const lon = (TAU * j) / count + ((i % 2) * Math.PI) / count;
points.push([Math.cos(lon) * ring, Math.sin(lat), Math.sin(lon) * ring]);
}
}
return points;
});
}
/** Dot radius that stays visible at small sizes without turning into blobs at large ones. */
const dotRadius = (size: number) => Math.max(0.6, size * 0.034);
// ---------------------------------------------------------------------------
// Marks
/** A dot sphere turning slowly, nearer dots brighter and larger. A soft ripple drifts over it. */
export const orbMark = mark(
(ctx, t, s) => {
const c = s / 2;
const R = s * 0.42;
const count = Math.round(Math.min(140, Math.max(36, s * s * 0.2)));
const yaw = t * 1.05;
const pitch = 0.38 + Math.sin(t * 0.7) * 0.08;
const base = dotRadius(s);
for (const point of sphere(count)) {
const [x, y, z] = rotate(point, yaw, pitch);
const depth = (z + 1) / 2;
const ripple = 0.78 + 0.22 * Math.sin(point[1] * 3.2 - t * 2.4);
dot(ctx, c + x * R, c + y * R, base * (0.5 + 0.7 * depth), (0.08 + 0.92 * depth * depth) * ripple);
}
},
0.6,
);
/** A globe of latitude rings with a bright band sweeping up and down, like a scan. */
export const scanMark = mark(
(ctx, t, s) => {
const c = s / 2;
const R = s * 0.42;
const rows = s < 22 ? 7 : s < 34 ? 9 : 11;
const band = Math.sin(t * 1.6) * 0.82;
const base = dotRadius(s) * 0.9;
// A hairline chord marks where the scan is.
const half = Math.sqrt(Math.max(0, 1 - band * band)) * R;
ctx.globalAlpha = 0.22;
ctx.fillRect(c - half, c + band * R - 0.25, half * 2, 0.5);
for (const point of globe(rows)) {
const [x, y, z] = rotate(point, t * 0.7, 0.24);
const depth = (z + 1) / 2;
const glow = Math.exp(-((y - band) ** 2) / 0.03);
const alpha = 0.06 + 0.36 * depth + glow * (0.35 + 0.6 * depth);
dot(ctx, c + x * R, c + y * R, base * (0.6 + 0.4 * depth) * (1 + 0.5 * glow), alpha);
}
},
0.35,
);
const constellation = cached("constellation", () =>
sphere(14).map(([x, y, z], i) => {
// Deterministic jitter so the nodes read as scattered, not as a grid.
const j = Math.sin(i * 12.9898) * 43758.5453;
const k = (j - Math.floor(j) - 0.5) * 0.5;
const len = Math.hypot(x + k, y - k * 0.6, z + k * 0.4) || 1;
return [(x + k) / len, (y - k * 0.6) / len, (z + k * 0.4) / len] as Point;
}),
);
const links: [number, number][] = (() => {
const pairs = new Set<string>();
constellation.forEach((a, i) => {
constellation
.map((b, j) => ({ j, d: Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) }))
.filter(({ j }) => j !== i)
.sort((p, q) => p.d - q.d)
.slice(0, 2)
.forEach(({ j }) => pairs.add(i < j ? `${i}-${j}` : `${j}-${i}`));
});
return [...pairs].map((pair) => pair.split("-").map(Number) as [number, number]);
})();
/** Scattered nodes joined by hairlines, turning in space; a signal hops from link to link. */
export const constellationMark = mark(
(ctx, t, s) => {
const c = s / 2;
const R = s * 0.4;
const yaw = t * 0.8;
const pitch = 0.5 + Math.sin(t * 0.5) * 0.15;
const projected = constellation.map((point) => rotate(point, yaw, pitch));
const base = dotRadius(s);
ctx.lineWidth = Math.max(0.5, s * 0.022);
for (const [a, b] of links) {
const p = projected[a]!;
const q = projected[b]!;
ctx.globalAlpha = 0.08 + 0.3 * ((p[2] + q[2] + 2) / 4);
ctx.beginPath();
ctx.moveTo(c + p[0] * R, c + p[1] * R);
ctx.lineTo(c + q[0] * R, c + q[1] * R);
ctx.stroke();
}
for (const [x, y, z] of projected) {
const depth = (z + 1) / 2;
dot(ctx, c + x * R, c + y * R, base * 1.1 * (0.6 + 0.6 * depth), 0.25 + 0.75 * depth);
}
// The signal eases along one link, then moves to the next.
const step = t * 1.2;
const [a, b] = links[Math.floor(step) % links.length]!;
const p = projected[a]!;
const q = projected[b]!;
const f = step - Math.floor(step);
const e = f * f * (3 - 2 * f);
const depth = (p[2] + (q[2] - p[2]) * e + 1) / 2;
dot(ctx, c + (p[0] + (q[0] - p[0]) * e) * R, c + (p[1] + (q[1] - p[1]) * e) * R, base * 1.5, 0.55 + 0.45 * depth);
},
1.1,
);
/** A dotted ring whose dots lift and brighten unevenly, like a voice level. */
export const ringMark = mark(
(ctx, t, s) => {
const c = s / 2;
const count = s < 22 ? 12 : 16;
const R = s * 0.34;
const base = dotRadius(s) * 1.05;
for (let i = 0; i < count; i++) {
const angle = (TAU * i) / count + t * 0.5;
const level = (Math.sin(t * 3.1 + i * 1.3) * Math.sin(t * 1.7 + i * 0.7) + 1) / 2;
const r = R + level * s * 0.07;
dot(ctx, c + Math.cos(angle) * r, c + Math.sin(angle) * r, base * (0.75 + 0.6 * level), 0.22 + 0.78 * level);
}
},
1.2,
);
/** Sparse dots on two radii; a light sweeps around them and leaves a fading trail. */
export const sparkMark = mark(
(ctx, t, s) => {
const c = s / 2;
const count = 10;
const head = t * 2.2;
const base = dotRadius(s) * 1.1;
for (let i = 0; i < count; i++) {
const angle = (TAU * i) / count - Math.PI / 2;
const behind = (((head - angle) % TAU) + TAU) % TAU;
const lit = Math.exp(-behind * 0.8);
const r = (i % 2 ? 0.25 : 0.4) * s * (1 + 0.06 * lit);
dot(ctx, c + Math.cos(angle) * r, c + Math.sin(angle) * r, base * (0.85 + 0.65 * lit), 0.22 + 0.78 * lit);
}
},
0.9,
);
/** A dotted triangle that turns gently while light travels along its edges. */
export const prismMark = mark(
(ctx, t, s) => {
const c = s / 2;
const R = s * 0.42;
const perEdge = s < 22 ? 5 : 7;
const turn = Math.cos(Math.sin(t * 0.9) * 0.55);
// Lower the centroid slightly so the triangle looks centered, not top heavy.
const cy = c + s * 0.05;
const corners = [-Math.PI / 2, Math.PI / 6, (5 * Math.PI) / 6].map((angle) => [c + Math.cos(angle) * R * turn, cy + Math.sin(angle) * R]);
const headU = (t * 0.28) % 1;
const base = dotRadius(s);
for (let edge = 0; edge < 3; edge++) {
const [ax, ay] = corners[edge]!;
const [bx, by] = corners[(edge + 1) % 3]!;
for (let m = 0; m < perEdge; m++) {
const f = m / perEdge;
const u = (edge + f) / 3;
const d = Math.min(Math.abs(u - headU), 1 - Math.abs(u - headU));
const glow = Math.exp(-(d * d) / 0.006);
const corner = m === 0 ? 0.18 : 0;
dot(ctx, ax! + (bx! - ax!) * f, ay! + (by! - ay!) * f, base * (0.9 + 0.7 * glow + corner * 2), 0.32 + corner + 0.68 * glow);
}
}
},
0.8,
);
/** The mark drawn for each activity. */
export const agentMarks: Record<AgentActivity, MarkSpec> = {
thinking: orbMark,
searching: scanMark,
working: constellationMark,
planning: sparkMark,
listening: ringMark,
shaping: prismMark,
};