Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): redesign bot avatars as flat shapes with spring motion (#296)

Leo268ea1a3feb0
diff --git a/.changeset/lively-bot-avatars.md b/.changeset/lively-bot-avatars.md
new file mode 100644
index 000000000..7c17daed5
--- /dev/null
+++ b/.changeset/lively-bot-avatars.md
@@ -0,0 +1,5 @@
+---
+"@t3tools/web": minor
+---
+
+Bot avatars are now flat shapes in a brighter palette, with slanted eyes cut out of the body. Bots on an older preset color move to the matching new one. A working bot sways, glances down at its work, and turns its face around its body now and then. Pointing at a bot widens its eyes and makes them follow the pointer. Resting bots stay still apart from an occasional blink or glance, and all motion respects your reduced-motion setting. Dithered avatars are gone: the picker no longer offers generated identicons or a dither filter, and bots that had one now show a shape.
diff --git a/apps/web/src/components/roster/AvatarColorPicker.tsx b/apps/web/src/components/roster/AvatarColorPicker.tsx
index 71b7eb07c..2e86cc251 100644
--- a/apps/web/src/components/roster/AvatarColorPicker.tsx
+++ b/apps/web/src/components/roster/AvatarColorPicker.tsx
@@ -9,7 +9,7 @@ import {
hsvToHex,
type HsvColor,
} from "./avatarColorPicker.logic";
-import { BLOB_COLORS, DEFAULT_BLOB_COLOR, isBotAvatarColor } from "./roster.logic";
+import { BLOB_COLORS, resolveBlobColor } from "./roster.logic";
function ColorThumb({ color, left, top }: { color: string; left: string; top: string }) {
return (
@@ -175,7 +175,7 @@ export function AvatarColorPicker({
className?: string;
label?: string;
}) {
- const color = isBotAvatarColor(value) ? value.toUpperCase() : DEFAULT_BLOB_COLOR;
+ const color = resolveBlobColor(value);
const presetSelected = BLOB_COLORS.includes(color);
return (
diff --git a/apps/web/src/components/roster/AvatarPickerDialog.tsx b/apps/web/src/components/roster/AvatarPickerDialog.tsx
index 748e404f5..f9c3dd7a2 100644
--- a/apps/web/src/components/roster/AvatarPickerDialog.tsx
+++ b/apps/web/src/components/roster/AvatarPickerDialog.tsx
@@ -10,29 +10,21 @@ import {
DialogPopup,
DialogTitle,
} from "../ui/dialog";
-import { Switch } from "../ui/switch";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { AvatarColorPicker } from "./AvatarColorPicker";
import { BotAvatarView } from "./BotAvatarView";
-import {
- ditherSeedForName,
- orderedDitherRgba,
- rerollDitherSeed,
- resolveUploadAvatar,
- type UploadRendering,
-} from "./dither.logic";
import { BLOB_SHAPES, resolveBlobRendering } from "./roster.logic";
import type { Bot, BotAvatar, BotBlobShape } from "./types";
import { useSaveBotAvatar } from "./useServerRoster";
-type PickerTab = "bot" | "generate" | "upload";
+type PickerTab = "bot" | "upload";
// Uploads become small square data URLs so an oversized photo can neither
// bloat the persisted roster nor blow the localStorage quota.
const AVATAR_UPLOAD_SIZE = 128;
const AVATAR_UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024;
-async function downscaleAvatarImage(file: File): Promise<UploadRendering> {
+async function downscaleAvatarImage(file: File): Promise<string> {
const bitmap = await createImageBitmap(file);
try {
const canvas = document.createElement("canvas");
@@ -52,29 +44,21 @@ async function downscaleAvatarImage(file: File): Promise<UploadRendering> {
AVATAR_UPLOAD_SIZE,
AVATAR_UPLOAD_SIZE,
);
- const plainUrl = canvas.toDataURL("image/jpeg", 0.85);
- // Both renderings up front, so the dither toggle previews instantly. The
- // dithered image is near-1-bit, so PNG stays well under the JPEG's size.
- const imageData = context.getImageData(0, 0, AVATAR_UPLOAD_SIZE, AVATAR_UPLOAD_SIZE);
- orderedDitherRgba(imageData.data, imageData.width, imageData.height);
- context.putImageData(imageData, 0, 0);
- return { plainUrl, ditheredUrl: canvas.toDataURL("image/png") };
+ return canvas.toDataURL("image/jpeg", 0.85);
} finally {
bitmap.close();
}
}
const TAB_LABELS: Record<PickerTab, string> = {
- bot: "Blob",
- generate: "Generate",
+ bot: "Bot",
upload: "Upload",
};
/**
- * Avatar picker for one bot. The Blob tab picks a blob shape and color;
- * Generate seeds a Dither Kit identicon from the bot's name with a reroll;
- * Upload previews a local image, optionally dithered, and applies it as a
- * data URL until server assets exist.
+ * Avatar picker for one bot. The Bot tab picks a body shape and color;
+ * Upload previews a local image and applies it as a data URL until server
+ * assets exist.
*/
export function AvatarPickerDialog({
bot,
@@ -90,21 +74,17 @@ export function AvatarPickerDialog({
const [tab, setTab] = useState<PickerTab>("bot");
const [shape, setShape] = useState<BotBlobShape>(initialBlob.shape);
const [color, setColor] = useState(initialBlob.color);
- const [seed, setSeed] = useState(
- bot.avatar.kind === "dither" ? bot.avatar.seed : ditherSeedForName(bot.name),
- );
- const [upload, setUpload] = useState<UploadRendering | null>(null);
+ const [upload, setUpload] = useState<string | null>(null);
const uploadSequence = useRef(0);
- const [ditherUpload, setDitherUpload] = useState(false);
const [failure, setFailure] = useState<"save" | "upload" | "too-large" | null>(null);
const [saving, setSaving] = useState(false);
const draftAvatar: BotAvatar | null =
tab === "bot"
? { kind: "blob", shape, color }
- : tab === "generate"
- ? { kind: "dither", seed }
- : resolveUploadAvatar(upload, ditherUpload);
+ : upload === null
+ ? null
+ : { kind: "image", assetPath: upload, dithered: false };
const handleUpload = (file: File | undefined) => {
if (!file) return;
@@ -155,13 +135,13 @@ export function AvatarPickerDialog({
value={[tab]}
onValueChange={(next) => {
const value = next[0];
- if (value === "bot" || value === "generate" || value === "upload") {
+ if (value === "bot" || value === "upload") {
setFailure(null);
setTab(value);
}
}}
>
- {(["bot", "generate", "upload"] as const).map((option) => (
+ {(["bot", "upload"] as const).map((option) => (
<Toggle key={option} value={option}>
{TAB_LABELS[option]}
</Toggle>
@@ -200,22 +180,11 @@ export function AvatarPickerDialog({
</div>
<AvatarColorPicker className="mx-auto" value={color} onChange={setColor} />
</>
- ) : tab === "generate" ? (
- <div className="flex h-40 flex-col items-center justify-center gap-3">
- <BotAvatarView
- avatar={{ kind: "dither", seed }}
- name={bot.name}
- className="size-20"
- />
- <Button variant="outline" onClick={() => setSeed(rerollDitherSeed(bot.name))}>
- Reroll
- </Button>
- </div>
) : (
<div className="flex h-40 flex-col items-center justify-center gap-3">
{upload !== null ? (
<img
- src={ditherUpload ? upload.ditheredUrl : upload.plainUrl}
+ src={upload}
alt="Avatar preview"
className="size-20 rounded-full object-cover"
/>
@@ -229,18 +198,6 @@ export function AvatarPickerDialog({
onChange={(event) => handleUpload(event.currentTarget.files?.[0])}
/>
</label>
- {upload !== null ? (
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Switch
- id="dither-avatar-upload"
- checked={ditherUpload}
- onCheckedChange={setDitherUpload}
- />
- <label htmlFor="dither-avatar-upload" className="cursor-pointer">
- Dither image
- </label>
- </div>
- ) : null}
</div>
)}
</DialogPanel>
diff --git a/apps/web/src/components/roster/BotAvatarView.test.tsx b/apps/web/src/components/roster/BotAvatarView.test.tsx
index 576a44c25..8cb9bd9cf 100644
--- a/apps/web/src/components/roster/BotAvatarView.test.tsx
+++ b/apps/web/src/components/roster/BotAvatarView.test.tsx
@@ -4,53 +4,82 @@ import { describe, expect, it } from "vite-plus/test";
import { BotAvatarView } from "./BotAvatarView";
describe("BotAvatarView", () => {
- it("renders ink-bar eyes on a blob instead of an initial", () => {
+ it("draws a blob as a flat svg body with cutout eyes", () => {
const markup = renderToStaticMarkup(
- <BotAvatarView name="Theo" avatar={{ kind: "blob", shape: "circle", color: "#E0645C" }} />,
+ <BotAvatarView name="Theo" avatar={{ kind: "blob", shape: "hex", color: "#FF4A5A" }} />,
);
- expect(markup).toContain('class="bot-eyes"');
- expect(markup).toContain('viewBox="-22 -18 44 36"');
+ expect(markup).toContain('data-avatar-shape="hex"');
expect(markup).toContain('data-bot-state="idle"');
- expect(markup).toContain('fill="#0A0A0A"');
- expect(markup).not.toContain("</text>");
- expect(markup).not.toContain(">T</text>");
+ expect(markup).toContain('fill="#FF4A5A"');
+ expect(markup).toMatch(/<mask id="bot-eyes-[\w-]+"/);
+ expect(markup).toMatch(/mask="url\(#bot-eyes-[\w-]+\)"/);
+ expect(markup).toContain('class="bot-eyes" fill="#000"');
+ expect(markup).not.toContain("<canvas");
});
- it("uses light eyes when the blob color is dark", () => {
+ it("gives every avatar its own mask", () => {
+ const avatar = { kind: "blob", shape: "circle", color: "#2E8EFF" } as const;
const markup = renderToStaticMarkup(
- <BotAvatarView name="Theo" avatar={{ kind: "blob", shape: "pill", color: "#141062" }} />,
+ <>
+ <BotAvatarView name="A" avatar={avatar} />
+ <BotAvatarView name="B" avatar={avatar} />
+ </>,
);
- expect(markup).toContain('fill="#FFFFFF"');
+ const ids = [...markup.matchAll(/<mask id="([^"]+)"/g)].map((match) => match[1]);
+ expect(ids).toHaveLength(2);
+ expect(new Set(ids).size).toBe(2);
});
- it("shortens the eyes while working", () => {
- const idle = renderToStaticMarkup(
- <BotAvatarView
- name="Akeru"
- state="idle"
- avatar={{ kind: "blob", shape: "square", color: "#5B7FD4" }}
- />,
+ it("shows retired muted presets in the current palette", () => {
+ const markup = renderToStaticMarkup(
+ <BotAvatarView name="Old" avatar={{ kind: "blob", shape: "hex", color: "#E0645C" }} />,
);
+
+ expect(markup).toContain('fill="#FF4A5A"');
+ expect(markup).not.toContain("#E0645C");
+ });
+
+ it("renders the same resting face whatever the bot is doing", () => {
+ const avatar = { kind: "blob", shape: "square", color: "#5B7FD4" } as const;
+ const eyes = (markup: string) => [...markup.matchAll(/<rect x="-4.2"[^>]*>/g)].map((m) => m[0]);
+ const idle = renderToStaticMarkup(<BotAvatarView name="Akeru" state="idle" avatar={avatar} />);
const working = renderToStaticMarkup(
- <BotAvatarView
- name="Akeru"
- state="working"
- avatar={{ kind: "blob", shape: "square", color: "#5B7FD4" }}
- />,
+ <BotAvatarView name="Akeru" state="working" avatar={avatar} />,
+ );
+ const waiting = renderToStaticMarkup(
+ <BotAvatarView name="Akeru" state="needs-you" avatar={avatar} />,
);
expect(working).toContain('data-bot-state="working"');
- expect(working).not.toBe(idle);
+ expect(waiting).toContain('data-bot-state="needs-you"');
+ expect(eyes(idle)).toHaveLength(2);
+ expect(eyes(working)).toEqual(eyes(idle));
+ expect(eyes(waiting)).toEqual(eyes(idle));
});
- it("renders a dither identicon without a face", () => {
+ it("paints dark eyes and an outline on light bodies instead of cutting them out", () => {
+ const white = renderToStaticMarkup(
+ <BotAvatarView name="Dew" avatar={{ kind: "blob", shape: "drop", color: "#FFFFFF" }} />,
+ );
+ const blue = renderToStaticMarkup(
+ <BotAvatarView name="Rin" avatar={{ kind: "blob", shape: "drop", color: "#1FBFAE" }} />,
+ );
+
+ expect(white).toContain("rgba(0, 0, 0, 0.14)");
+ expect(white).toContain('class="bot-eyes" fill="#161616"');
+ expect(white).not.toContain("<mask");
+ expect(blue).not.toContain("rgba(0, 0, 0, 0.14)");
+ expect(blue).toContain("<mask");
+ });
+
+ it("draws a legacy dither avatar as a blob", () => {
const markup = renderToStaticMarkup(
<BotAvatarView name="Akeru" avatar={{ kind: "dither", seed: "akeru-seed" }} />,
);
- expect(markup).toContain('data-avatar-dither="akeru-seed"');
- expect(markup).not.toContain("bot-eyes");
+ expect(markup).toContain("data-avatar-shape=");
+ expect(markup).toContain('class="bot-eyes"');
});
});
diff --git a/apps/web/src/components/roster/BotAvatarView.tsx b/apps/web/src/components/roster/BotAvatarView.tsx
index 22dfd623f..a3a060ff2 100644
--- a/apps/web/src/components/roster/BotAvatarView.tsx
+++ b/apps/web/src/components/roster/BotAvatarView.tsx
@@ -1,233 +1,303 @@
-import { useMemo, type CSSProperties } from "react";
+import { useEffect, useId, useRef, type RefObject } from "react";
import { cn } from "~/lib/utils";
-import { generateDitherIdenticon, identiconPathData } from "./dither.logic";
-import { blinkDelayMs, resolveBlobEyeColor, resolveBlobRendering } from "./roster.logic";
+import { IDLE_BEAT_LENGTH_MS, subscribeIdleBeat } from "./botAvatarIdleBeat";
+import { BotMotion, REST_FRAME, wrapOnBelt, type MotionFrame } from "./botAvatarMotion";
+import {
+ botAvatarSeed,
+ resolveBlobEyes,
+ resolveBlobOutline,
+ resolveBlobRendering,
+} from "./roster.logic";
import type { BotAvatar, BotBlobShape } from "./types";
/**
- * Animation states a bot avatar can play. `idle` blinks; `working` loops
- * while a turn runs; `needs-you` calls the user over; `success` runs once on
- * a clean finish. The matching keyframes live in index.css under "Bot
- * avatars".
+ * What a bot is doing. `working` sways, glances down at its work, and spins
+ * now and then for as long as the turn runs; `idle` and `needs-you` rest still
+ * and only move on hover or during the rare idle beat. The presence dot
+ * carries needs-you.
*/
-export type BotAnimationState = "idle" | "working" | "needs-you" | "success";
+export type BotAnimationState = "idle" | "working" | "needs-you";
/**
- * Where the face sits on the 100×100 viewBox. Bottom-heavy shapes (triangle,
- * drop) carry the face lower; small bodies (pill, cloud) shrink it a touch.
+ * Where the face sits on the 100×100 viewBox. It looks up and to the right;
+ * bottom-heavy shapes (triangle, drop) carry it lower and smaller.
*/
-const FACE_LAYOUT: Record<BotBlobShape, { y: number; scale: number }> = {
- circle: { y: 50, scale: 1 },
- squircle: { y: 50, scale: 1 },
- square: { y: 50, scale: 1 },
- pill: { y: 50, scale: 0.88 },
- triangle: { y: 63, scale: 0.85 },
- hex: { y: 51, scale: 0.95 },
- cloud: { y: 57, scale: 0.88 },
- drop: { y: 63, scale: 0.85 },
+const FACE_LAYOUT: Record<BotBlobShape, { x: number; y: number; scale: number }> = {
+ circle: { x: 66, y: 40, scale: 1.1 },
+ squircle: { x: 64, y: 42, scale: 1.1 },
+ square: { x: 66, y: 40, scale: 1.1 },
+ pill: { x: 64, y: 46, scale: 1 },
+ triangle: { x: 50, y: 64, scale: 0.85 },
+ hex: { x: 64, y: 42, scale: 1.1 },
+ cloud: { x: 62, y: 50, scale: 1 },
+ drop: { x: 57, y: 62, scale: 1 },
};
-/**
- * Blob geometry on a 100×100 viewBox. Soft corners come from a round-joined
- * stroke in the fill color, so every shape reads as one solid blob.
- */
-function BlobShape({ shape, color }: { shape: BotBlobShape; color: string }) {
- const soft = { fill: color, stroke: color, strokeWidth: 10, strokeLinejoin: "round" } as const;
- switch (shape) {
- case "circle":
- // Hand-wobbled circle so the body reads organic, not geometric.
- return (
- <path
- d="M96 51 C96 64 92.6 74.4 84.6 82.2 C76.6 90 64 96 51 96 C38 96 26.2 91 18.2 83 C10.2 75 4 63 4 50 C4 37 9.4 25.4 18.4 17.6 C27.4 9.8 39 4 52 4 C65 4 76.4 10 84.4 18 C92.4 26 96 38 96 51 Z"
- fill={color}
- />
- );
- case "squircle":
- return (
- <path
- d="M50 2 C86 2 98 14 98 50 C98 86 86 98 50 98 C14 98 2 86 2 50 C2 14 14 2 50 2 Z"
- fill={color}
- />
- );
- case "square":
- return <rect x="5" y="5" width="90" height="90" rx="16" fill={color} />;
- case "pill":
- return <rect x="2" y="22" width="96" height="56" rx="28" fill={color} />;
- case "triangle":
- return <path d="M50 10 L92 88 L8 88 Z" {...soft} />;
- case "hex":
- return <path d="M50 4 L90 27 L90 73 L50 96 L10 73 L10 27 Z" {...soft} />;
- case "cloud":
- return (
- <path d="M30 82 A17 17 0 0 1 26 49 A22 22 0 0 1 66 35 A19 19 0 0 1 74 82 Z" {...soft} />
- );
- case "drop":
- return (
- <path d="M50 6 C50 6 86 46 86 64 A36 36 0 1 1 14 64 C14 46 50 6 50 6 Z" fill={color} />
- );
+/** Flat body geometry on a 100×100 viewBox. Each shape fills the frame. */
+const BODY: Record<BotBlobShape, string> = {
+ circle: "M4 50A46 46 0 1 1 96 50A46 46 0 1 1 4 50Z",
+ squircle:
+ "M96.8 50C97.5 55.5 97.4 62 95.3 67.3C93.3 72.6 89.2 78.2 84.6 81.9C80 85.5 73.4 87.9 67.6 89.1C61.8 90.4 55.6 89.9 50 89.4C44.4 88.9 39.1 87.7 33.8 86C28.5 84.3 23 82.4 18.3 79.2C13.7 76 8.7 71.7 5.9 66.8C3.1 62 1.3 55.6 1.4 50C1.5 44.4 3.6 38.3 6.3 33.3C9 28.3 13.3 23.8 17.7 20.2C22 16.5 27.3 13.4 32.7 11.4C38.1 9.4 44.2 8.1 50 8.1C55.8 8.2 62 9.5 67.2 11.7C72.4 13.9 77.2 17.5 81.2 21.2C85.2 25 88.6 29.5 91.2 34.3C93.8 39.1 96.1 44.5 96.8 50Z",
+ square: "M30 6H70C88 6 94 12 94 30V70C94 88 88 94 70 94H30C12 94 6 88 6 70V30C6 12 12 6 30 6Z",
+ pill: "M34 19H66A31 31 0 0 1 66 81H34A31 31 0 0 1 34 19Z",
+ triangle: "M35.6 28.3Q50 2 64.4 28.3L89.9 75.1Q98 90 81 90L19 90Q2 90 10.1 75.1Z",
+ hex: "M42.2 5.5Q50 1 57.8 5.5L84.6 21Q92.4 25.5 92.4 34.5L92.4 65.5Q92.4 74.5 84.6 79L57.8 94.5Q50 99 42.2 94.5L15.4 79Q7.6 74.5 7.6 65.5L7.6 34.5Q7.6 25.5 15.4 21Z",
+ cloud:
+ "M31 80.7A20 20 0 1 1 16.7 43.4A22 22 0 0 1 53.4 22.3A19 19 0 0 1 82.3 43A20 20 0 0 1 69 80.7A24 24 0 0 1 31 80.7Z",
+ drop: "M42.6 12.4Q50 3 57.4 12.4L78.2 38.7A36 36 0 1 1 21.8 38.7Z",
+};
+
+/** The two slanted capsule eyes, relative to the face origin. */
+const EYES = [
+ { x: -13, y: 1, rotate: -16 },
+ { x: 13, y: -1, rotate: -20 },
+] as const;
+
+/** Radius the face travels on when it spins around the body. */
+const BELT_RADIUS = 44;
+
+/** Places one eye for a motion frame, or returns null while it is behind the body. */
+function eyeTransform(shape: BotBlobShape, frame: MotionFrame, index: 0 | 1) {
+ const face = FACE_LAYOUT[shape];
+ const eye = EYES[index];
+ const pull = 0.42 * frame.pull;
+ const faceX = face.x + (50 - face.x) * pull;
+ const faceY = face.y + (50 - face.y) * pull;
+ let x = faceX + (eye.x + frame.gazeX) * face.scale;
+ const y = faceY + (eye.y + frame.gazeY) * face.scale;
+ let width = frame.eyeWidth * face.scale;
+ if (frame.spin !== 0) {
+ const wrapped = wrapOnBelt(x, 50, BELT_RADIUS, frame.spin);
+ if (!wrapped) return null;
+ x = wrapped.x;
+ width *= wrapped.width;
}
+ const height = frame.eyeHeight[index] * face.scale;
+ return `translate(${x.toFixed(2)} ${y.toFixed(2)}) rotate(${eye.rotate}) scale(${width.toFixed(3)} ${height.toFixed(3)})`;
}
-/**
- * Two slanted ink-bar eyes, swapped per state. Working shortens the bars into
- * a focused face. Needs-you raises and spreads them. Success closes them into
- * happy arcs.
- */
-function Eyes({ state, color }: { state: BotAnimationState; color: string }) {
- switch (state) {
- case "working":
- return (
- <>
- <rect
- x="-13.5"
- y="0"
- width="9"
- height="10"
- rx="4.5"
- transform="rotate(14 -9 5)"
- fill={color}
- />
- <rect
- x="4.5"
- y="0"
- width="9"
- height="10"
- rx="4.5"
- transform="rotate(14 9 5)"
- fill={color}
- />
- </>
- );
- case "needs-you":
- return (
- <>
- <rect
- x="-15.5"
- y="-14"
- width="9"
- height="26"
- rx="4.5"
- transform="rotate(10 -11 0)"
- fill={color}
- />
- <rect
- x="6.5"
- y="-14"
- width="9"
- height="26"
- rx="4.5"
- transform="rotate(10 11 0)"
- fill={color}
- />
- </>
- );
- case "success":
- return (
- <>
- <path
- d="M-17 1 Q-11 -9 -5 1"
- stroke={color}
- strokeWidth="4"
- strokeLinecap="round"
- fill="none"
- />
- <path
- d="M5 1 Q11 -9 17 1"
- stroke={color}
- strokeWidth="4"
- strokeLinecap="round"
- fill="none"
- />
- </>
- );
- case "idle":
- return (
- <>
- <rect
- x="-14"
- y="-10"
- width="9"
- height="20"
- rx="4.5"
- transform="rotate(14 -9.5 0)"
- fill={color}
- />
- <rect
- x="5"
- y="-10"
- width="9"
- height="20"
- rx="4.5"
- transform="rotate(14 9.5 0)"
- fill={color}
- />
- </>
- );
- }
+function bodyTransform(frame: MotionFrame) {
+ return `translate(${frame.x.toFixed(2)}%, ${frame.y.toFixed(2)}%) rotate(${frame.roll.toFixed(2)}deg) scale(1, ${frame.scaleY.toFixed(4)})`;
+}
+
+/** Two slanted capsule eyes. The motion engine rewrites their transforms. */
+function Eyes({
+ shape,
+ ink,
+ eyeRefs,
+}: {
+ shape: BotBlobShape;
+ ink: string;
+ eyeRefs: RefObject<Array<SVGRectElement | null>>;
+}) {
+ return (
+ <g className="bot-eyes" fill={ink}>
+ {([0, 1] as const).map((index) => (
+ <rect
+ key={index}
+ ref={(node) => {
+ eyeRefs.current[index] = node;
+ }}
+ x="-4.2"
+ y="-8.8"
+ width="8.4"
+ height="17.6"
+ rx="4.2"
+ transform={eyeTransform(shape, REST_FRAME, index) ?? undefined}
+ />
+ ))}
+ </g>
+ );
}
/**
- * The face. A nested svg owns the blink so scaleY uses that svg's viewBox,
- * not a <g> fill-box that collapses as the eyes close and strobes the avatar.
+ * The body and its face. Eyes are cut out of the body so the surface shows
+ * through. Colors too light or dark for that to read paint the eyes on
+ * instead, and light bodies add a faint outline.
*/
-function Face({
+function BlobFigure({
shape,
- state,
color,
+ eyeRefs,
}: {
shape: BotBlobShape;
- state: BotAnimationState;
color: string;
+ eyeRefs: RefObject<Array<SVGRectElement | null>>;
}) {
- const { y, scale } = FACE_LAYOUT[shape];
+ const maskId = `bot-eyes-${useId().replace(/[^\w-]/g, "")}`;
+ const d = BODY[shape];
+ const eyes = resolveBlobEyes(color);
+ const outline = resolveBlobOutline(color);
+ if (eyes.kind === "ink") {
+ return (
+ <>
+ {outline && <path d={d} fill="none" stroke={outline} strokeWidth="3" />}
+ <path d={d} fill={color} />
+ <Eyes shape={shape} ink={eyes.ink} eyeRefs={eyeRefs} />
+ </>
+ );
+ }
return (
- <g transform={`translate(50 ${y}) scale(${scale})`}>
- <svg
- className="bot-eyes"
- x="-22"
- y="-18"
- width="44"
- height="36"
- viewBox="-22 -18 44 36"
- overflow="visible"
- aria-hidden
- >
- <Eyes state={state} color={color} />
- </svg>
- </g>
+ <>
+ <mask id={maskId} maskUnits="userSpaceOnUse" x="-10" y="-10" width="120" height="120">
+ <rect x="-10" y="-10" width="120" height="120" fill="#fff" />
+ <Eyes shape={shape} ink="#000" eyeRefs={eyeRefs} />
+ </mask>
+ <path d={d} fill={color} mask={`url(#${maskId})`} />
+ </>
);
}
/**
- * Dither Kit identicon rendered from the seed alone: no stored bitmap, the
- * generator is deterministic. One background rect and one path keep it a
- * two-element SVG at every size.
+ * A flat blob avatar with a face, moved by a spring engine (see
+ * botAvatarMotion). It animates only while the bot works, while the pointer
+ * is over the avatar or its `[data-bot-hover]` row, and for the rare idle
+ * beat. Hovered eyes follow the pointer. The frame loop stops once the springs
+ * settle and pauses while the avatar is off screen.
*/
-function DitherAvatar({ seed, className }: { seed: string; className?: string | undefined }) {
- const identicon = useMemo(() => generateDitherIdenticon(seed), [seed]);
+function BlobAvatar({
+ shape,
+ color,
+ name,
+ state,
+ className,
+}: {
+ shape: BotBlobShape;
+ color: string;
+ name: string;
+ state: BotAnimationState;
+ className?: string | undefined;
+}) {
+ const wrapperRef = useRef<HTMLSpanElement>(null);
+ const bodyRef = useRef<HTMLSpanElement>(null);
+ const eyeRefs = useRef<Array<SVGRectElement | null>>([null, null]);
+ const working = state === "working";
+ const workingRef = useRef(working);
+ const wakeRef = useRef<() => void>(() => {});
+ const motionRef = useRef<BotMotion | null>(null);
+
+ useEffect(() => {
+ const wrapper = wrapperRef.current;
+ const body = bodyRef.current;
+ if (!wrapper || !body) return;
+ const motion = (motionRef.current = new BotMotion(botAvatarSeed(name)));
+ const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
+ const hoverTarget = wrapper.closest<HTMLElement>("[data-bot-hover]") ?? wrapper;
+ let hovered = false;
+ let pointer: { x: number; y: number } | null = null;
+ let visible = true;
+ let frameId: number | null = null;
+ let last = 0;
+
+ const render = (frame: MotionFrame) => {
+ body.style.transform = bodyTransform(frame);
+ for (const index of [0, 1] as const) {
+ const eye = eyeRefs.current[index];
+ if (!eye) continue;
+ const transform = eyeTransform(shape, frame, index);
+ eye.setAttribute("visibility", transform ? "visible" : "hidden");
+ if (transform) eye.setAttribute("transform", transform);
+ }
+ };
+
+ const tick = (time: number) => {
+ const dt = last === 0 ? 1 / 60 : (time - last) / 1000;
+ last = time;
+ const { frame, active } = motion.tick(dt, {
+ working: workingRef.current,
+ hovered,
+ pointer,
+ reducedMotion: reducedMotion.matches,
+ });
+ render(frame);
+ frameId = active && visible ? requestAnimationFrame(tick) : null;
+ if (frameId === null) last = 0;
+ };
+
+ const wake = () => {
+ if (frameId === null && visible) frameId = requestAnimationFrame(tick);
+ };
+ wakeRef.current = wake;
+
+ const onEnter = (event: PointerEvent) => {
+ hovered = true;
+ onMove(event);
+ wake();
+ };
+ const onMove = (event: PointerEvent) => {
+ const rect = wrapper.getBoundingClientRect();
+ const clamp = (value: number) => Math.max(-0.6, Math.min(0.6, value)) / 0.6;
+ pointer = {
+ x: clamp((event.clientX - (rect.left + rect.width / 2)) / Math.max(rect.width, 1)),
+ y: clamp((event.clientY - (rect.top + rect.height / 2)) / Math.max(rect.height, 1)),
+ };
+ };
+ const onLeave = () => {
+ hovered = false;
+ pointer = null;
+ wake();
+ };
+ reducedMotion.addEventListener("change", wake);
+ hoverTarget.addEventListener("pointerenter", onEnter);
+ hoverTarget.addEventListener("pointermove", onMove);
+ hoverTarget.addEventListener("pointerleave", onLeave);
+
+ const observer = new IntersectionObserver(([entry]) => {
+ visible = entry?.isIntersecting ?? true;
+ if (visible) wake();
+ });
+ observer.observe(wrapper);
+ wake();
+
+ return () => {
+ reducedMotion.removeEventListener("change", wake);
+ hoverTarget.removeEventListener("pointerenter", onEnter);
+ hoverTarget.removeEventListener("pointermove", onMove);
+ hoverTarget.removeEventListener("pointerleave", onLeave);
+ observer.disconnect();
+ if (frameId !== null) cancelAnimationFrame(frameId);
+ wakeRef.current = () => {};
+ motionRef.current = null;
+ };
+ }, [name, shape]);
+
+ useEffect(() => {
+ workingRef.current = working;
+ wakeRef.current();
+ }, [working]);
+
+ useEffect(() => {
+ const wrapper = wrapperRef.current;
+ if (!wrapper || working) return;
+ return subscribeIdleBeat(wrapper, () => {
+ motionRef.current?.beat(IDLE_BEAT_LENGTH_MS);
+ wakeRef.current();
+ });
+ }, [working]);
+
return (
- <svg
- viewBox={`0 0 ${identicon.size} ${identicon.size}`}
+ <span
+ ref={wrapperRef}
aria-hidden
- className={cn("shrink-0 select-none rounded-full", className)}
- data-avatar-dither={seed}
+ className={cn("bot-avatar relative inline-block shrink-0 select-none", className)}
+ data-avatar-shape={shape}
+ data-bot-state={state}
>
- <rect width={identicon.size} height={identicon.size} fill={identicon.background} />
- <path
- d={identiconPathData(identicon)}
- fill={identicon.foreground}
- shapeRendering="crispEdges"
- />
- </svg>
+ <span ref={bodyRef} className="bot-body">
+ <svg viewBox="0 0 100 100" overflow="visible" className="size-full">
+ <BlobFigure shape={shape} color={color} eyeRefs={eyeRefs} />
+ </svg>
+ </span>
+ </span>
);
}
/**
* Renders any bot avatar at a caller-supplied size. Image avatars paint the
- * asset; dither avatars render their seeded identicon; blob avatars get a
- * face. Malformed data falls back to the default blob. `name` seeds the blink
- * phase so bots blink out of sync; `state` picks the animation the CSS plays.
+ * asset; everything else draws as a blob, with legacy dither seeds picking its
+ * shape and color. Malformed data falls back to the default blob. `name`
+ * offsets the motion so a row of working bots does not bob in unison.
*/
export function BotAvatarView({
avatar,
@@ -240,10 +310,6 @@ export function BotAvatarView({
state?: BotAnimationState;
className?: string;
}) {
- if (avatar.kind === "dither") {
- return <DitherAvatar seed={avatar.seed} className={className} />;
- }
-
if (avatar.kind === "image" && avatar.assetPath.length > 0) {
return (
<img
@@ -256,21 +322,5 @@ export function BotAvatarView({
}
const { shape, color } = resolveBlobRendering(avatar);
- const eyeColor = resolveBlobEyeColor(color);
- return (
- <svg
- viewBox="0 0 100 100"
- aria-hidden
- overflow="visible"
- className={cn("bot-avatar shrink-0 select-none", className)}
- data-avatar-shape={shape}
- data-bot-state={state}
- style={{ "--bot-blink-delay": `${blinkDelayMs(name)}ms` } as CSSProperties}
- >
- <g className="bot-body">
- <BlobShape shape={shape} color={color} />
- <Face shape={shape} state={state} color={eyeColor} />
- </g>
- </svg>
- );
+ return <BlobAvatar shape={shape} color={color} name={name} state={state} className={className} />;
}
diff --git a/apps/web/src/components/roster/botAvatarIdleBeat.ts b/apps/web/src/components/roster/botAvatarIdleBeat.ts
new file mode 100644
index 000000000..0d7795091
--- /dev/null
+++ b/apps/web/src/components/roster/botAvatarIdleBeat.ts
@@ -0,0 +1,56 @@
+/**
+ * Paces the rare idle beat. Resting avatars are static SVGs that cost
+ * nothing per frame; every 20–40 seconds one avatar in the viewport wakes for
+ * a moment so the roster still feels alive. At most one idle avatar animates
+ * at a time, and nothing is scheduled while no avatar is mounted.
+ */
+const IDLE_BEAT_MIN_MS = 20_000;
+const IDLE_BEAT_SPREAD_MS = 20_000;
+export const IDLE_BEAT_LENGTH_MS = 1_600;
+
+interface Sleeper {
+ element: HTMLElement;
+ wake: () => void;
+}
+
+const sleepers = new Set<Sleeper>();
+let timer: ReturnType<typeof setTimeout> | null = null;
+
+function isInViewport(element: HTMLElement) {
+ const rect = element.getBoundingClientRect();
+ return (
+ rect.width > 0 &&
+ rect.bottom > 0 &&
+ rect.right > 0 &&
+ rect.top < window.innerHeight &&
+ rect.left < window.innerWidth
+ );
+}
+
+function schedule() {
+ timer = setTimeout(beat, IDLE_BEAT_MIN_MS + Math.random() * IDLE_BEAT_SPREAD_MS);
+}
+
+function beat() {
+ timer = null;
+ if (sleepers.size === 0) return;
+ if (!document.hidden) {
+ const visible = [...sleepers].filter((sleeper) => isInViewport(sleeper.element));
+ visible[Math.floor(Math.random() * visible.length)]?.wake();
+ }
+ schedule();
+}
+
+/** Registers a resting avatar as a candidate for the next idle beat. */
+export function subscribeIdleBeat(element: HTMLElement, wake: () => void) {
+ const sleeper = { element, wake };
+ sleepers.add(sleeper);
+ if (timer === null) schedule();
+ return () => {
+ sleepers.delete(sleeper);
+ if (sleepers.size === 0 && timer !== null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ };
+}
diff --git a/apps/web/src/components/roster/botAvatarMotion.test.ts b/apps/web/src/components/roster/botAvatarMotion.test.ts
new file mode 100644
index 000000000..b9afa3d64
--- /dev/null
+++ b/apps/web/src/components/roster/botAvatarMotion.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { BotMotion, wrapOnBelt, type MotionInput } from "./botAvatarMotion";
+
+const rest: MotionInput = { working: false, hovered: false, pointer: null, reducedMotion: false };
+
+function run(motion: BotMotion, input: MotionInput, seconds: number) {
+ let result = motion.tick(1 / 60, input);
+ for (let elapsed = 1 / 60; elapsed < seconds; elapsed += 1 / 60) {
+ result = motion.tick(1 / 60, input);
+ }
+ return result;
+}
+
+describe("BotMotion", () => {
+ it("stops asking for frames when nothing wants motion", () => {
+ const motion = new BotMotion(0.3);
+ expect(motion.tick(1 / 60, rest).active).toBe(false);
+ });
+
+ it("keeps a working bot moving, then settles it once the turn ends", () => {
+ const motion = new BotMotion(0.3);
+ const working = run(motion, { ...rest, working: true }, 2);
+ expect(working.active).toBe(true);
+ expect(working.frame.roll).not.toBe(0);
+
+ const after = run(motion, rest, 6);
+ expect(after.active).toBe(false);
+ expect(after.frame.roll).toBeCloseTo(0, 1);
+ expect(after.frame.spin).toBe(0);
+ });
+
+ it("turns the eyes toward the pointer and enlarges them on hover", () => {
+ const motion = new BotMotion(0.3);
+ const { frame } = run(motion, { ...rest, hovered: true, pointer: { x: 1, y: 0 } }, 1.5);
+ expect(frame.gazeX).toBeGreaterThan(5);
+ expect(frame.eyeWidth).toBeGreaterThan(1.1);
+ });
+
+ it("plays an idle beat and then rests again", () => {
+ const motion = new BotMotion(0.3);
+ motion.beat(1600);
+ expect(motion.tick(1 / 60, rest).active).toBe(true);
+ expect(run(motion, rest, 5).active).toBe(false);
+ });
+
+ it("holds still under reduced motion", () => {
+ const motion = new BotMotion(0.3);
+ const { frame, active } = motion.tick(1 / 60, {
+ ...rest,
+ working: true,
+ reducedMotion: true,
+ });
+ expect(active).toBe(false);
+ expect(frame.roll).toBe(0);
+ });
+
+ it("drops a pending idle beat when reduced motion is on", () => {
+ const motion = new BotMotion(0.3);
+ motion.beat(1600);
+ const { frame, active } = motion.tick(1 / 60, { ...rest, reducedMotion: true });
+ expect(active).toBe(false);
+ expect(frame.eyeHeight).toEqual([1, 1]);
+ expect(motion.tick(1 / 60, rest).active).toBe(false);
+ });
+});
+
+describe("wrapOnBelt", () => {
+ it("leaves a point in place at rest and hides it behind the body", () => {
+ expect(wrapOnBelt(60, 50, 44, 0)).toEqual({ x: 60, width: 1 });
+ expect(wrapOnBelt(60, 50, 44, Math.PI)).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/roster/botAvatarMotion.ts b/apps/web/src/components/roster/botAvatarMotion.ts
new file mode 100644
index 000000000..1c1d652c1
--- /dev/null
+++ b/apps/web/src/components/roster/botAvatarMotion.ts
@@ -0,0 +1,351 @@
+/**
+ * Spring-driven avatar motion, tuned to feel like Grok Bot's companions.
+ *
+ * Every animated value is a damped spring chasing a target. Poses set the
+ * targets (a slow sway at rest, a rocking bob while working), and one-off
+ * events kick them: blinks with an overshoot, saccades, a one-eye squint, and
+ * a belt spin that wraps the face around the body. The engine only ticks while
+ * something asks for motion and stops itself once every spring has settled,
+ * so a resting roster costs nothing per frame.
+ *
+ * Units are the avatar's 100×100 viewBox. Body offsets are applied as percent
+ * of the element, which is the same thing.
+ */
+
+interface Spring {
+ x: number;
+ v: number;
+ t: number;
+}
+
+const spring = (value: number): Spring => ({ x: value, v: 0, t: value });
+
+function step(s: Spring, freq: number, damping: number, dt: number) {
+ s.v += (-2 * damping * freq * s.v - freq * freq * (s.x - s.t)) * dt;
+ s.x += s.v * dt;
+}
+
+const settled = (s: Spring, eps = 0.002) => Math.abs(s.x - s.t) < eps && Math.abs(s.v) < eps * 10;
+
+const rand = (min: number, max: number) => min + Math.random() * (max - min);
+
+/** Blink keyframes for eye height, [ms, value]. Squeezes shut, then overshoots open. */
+const BLINK: ReadonlyArray<readonly [number, number]> = [
+ [0, 1],
+ [60, 0.08],
+ [110, 0.08],
+ [190, 1.08],
+ [320, 1],
+];
+const DOUBLE_BLINK: ReadonlyArray<readonly [number, number]> = [
+ ...BLINK.slice(0, -1),
+ [360, 1],
+ [420, 0.08],
+ [470, 0.08],
+ [560, 1.06],
+ [680, 1],
+];
+
+function sampleKeyframes(frames: ReadonlyArray<readonly [number, number]>, ms: number) {
+ for (let index = 1; index < frames.length; index++) {
+ const [endMs, endValue] = frames[index]!;
+ if (ms <= endMs) {
+ const [startMs, startValue] = frames[index - 1]!;
+ const t = (ms - startMs) / (endMs - startMs);
+ const eased = t * t * (3 - 2 * t);
+ return startValue + (endValue - startValue) * eased;
+ }
+ }
+ return frames[frames.length - 1]![1];
+}
+
+const SQUINT_MS = 320;
+const SPIN_EVERY_MS: readonly [number, number] = [6000, 9000];
+const WORK_BOB_HZ = 1.6;
+
+export interface MotionFrame {
+ /** Body roll in degrees. */
+ roll: number;
+ /** Body offset in viewBox units. */
+ x: number;
+ y: number;
+ /** Vertical squash of the body. */
+ scaleY: number;
+ /** Gaze offset of the whole face, in face units. */
+ gazeX: number;
+ gazeY: number;
+ /** Pull of the face toward the body center, 0 to 1. */
+ pull: number;
+ /** Eye width and height multipliers. */
+ eyeWidth: number;
+ eyeHeight: [number, number];
+ /** Belt spin angle in radians, or 0 at rest. */
+ spin: number;
+}
+
+export interface MotionInput {
+ working: boolean;
+ hovered: boolean;
+ /** Pointer position relative to the avatar, each clamped to -1..1, or null. */
+ pointer: { x: number; y: number } | null;
+ reducedMotion: boolean;
+}
+
+/**
+ * One avatar's motion state. Call `tick` from requestAnimationFrame; it
+ * returns false once the avatar is at rest and nothing is pending.
+ */
+export class BotMotion {
+ private readonly roll = spring(0);
+ private readonly offsetX = spring(0);
+ private readonly offsetY = spring(0);
+ private readonly squash = spring(1);
+ private readonly lookX = spring(0);
+ private readonly lookY = spring(0);
+ private readonly pull = spring(0);
+ private readonly eyeWidth = spring(1);
+ private readonly eyeHeight = spring(1);
+ private spin: Spring | null = null;
+ private spinDirection = 1;
+
+ private clock = 0;
+ private readonly phase: number;
+ private saccadeAt = 0;
+ private saccade = { x: 0, y: 0 };
+ private blinkAt = 0;
+ private blink: { start: number; frames: ReadonlyArray<readonly [number, number]> } | null = null;
+ private squint: { start: number; eye: 0 | 1 } | null = null;
+ private squintAt = 0;
+ private spinAt = 0;
+ private followX = 0;
+ private followY = 0;
+ private beatUntil = -1;
+ private working = false;
+
+ constructor(seed: number) {
+ this.phase = seed * 40;
+ this.scheduleIdle();
+ }
+
+ /** Plays a short lively moment on a resting avatar. */
+ beat(lengthMs: number) {
+ this.beatUntil = this.clock + lengthMs / 1000;
+ const pick = Math.random();
+ if (pick < 0.4) this.startBlink();
+ else if (pick < 0.7) this.startSquint();
+ else this.saccade = { x: rand(-1, 1) * 5, y: rand(-1, 0.4) * 3 };
+ this.saccadeAt = this.clock + rand(0.9, 1.3);
+ this.blinkAt = Math.max(this.blinkAt, this.beatUntil + 1);
+ this.squintAt = Math.max(this.squintAt, this.beatUntil + 1);
+ }
+
+ tick(dtSeconds: number, input: MotionInput): { frame: MotionFrame; active: boolean } {
+ if (input.reducedMotion) return { frame: this.rest(), active: false };
+ const dt = Math.min(dtSeconds, 1 / 20);
+ this.clock += dt;
+ const now = this.clock;
+ const t = now + this.phase;
+ const beating = now < this.beatUntil;
+ this.working = input.working;
+ const lively = input.working || input.hovered || beating;
+
+ // Pose targets.
+ if (lively && input.working) {
+ const bob = Math.sin(2 * Math.PI * WORK_BOB_HZ * t);
+ this.roll.t = 4 + 2.5 * bob;
+ this.offsetX.t = 1.2;
+ this.offsetY.t = 0.6 + 1.2 * Math.max(0, bob);
+ this.squash.t = 1 - 0.02 * Math.max(0, bob);
+ } else if (lively) {
+ this.roll.t = 1.5 * Math.sin(0.5 * t) + 0.6 * Math.sin(0.17 * t);
+ this.offsetX.t = 0.4 * Math.sin(0.27 * t);
+ this.offsetY.t = 0.5 * Math.sin(0.85 * t);
+ this.squash.t = 1 + 0.007 * Math.sin(0.85 * t);
+ } else {
+ this.roll.t = 0;
+ this.offsetX.t = 0;
+ this.offsetY.t = 0;
+ this.squash.t = 1;
+ }
+
+ // Gaze: saccades, a slow drift, and the pointer while hovered.
+ if (lively && now >= this.saccadeAt) {
+ if (input.working) {
+ this.saccade = {
+ x: (Math.random() < 0.5 ? -1 : 1) * rand(0, 0.4) * 6,
+ y: rand(0.4, 1) * 3.6,
+ };
+ this.saccadeAt = now + rand(1.2, 2.4);
+ } else {
+ this.saccade = { x: 0, y: 0 };
+ this.saccadeAt = now + rand(2.5, 5.5);
+ }
+ }
+ if (!lively) this.saccade = { x: 0, y: 0 };
+ const following = lively && input.hovered && input.pointer !== null;
+ const followTargetX = following ? input.pointer!.x * 9 : 0;
+ const followTargetY = following ? input.pointer!.y * 5.6 : 0;
+ this.followX += (followTargetX - this.followX) * 0.16;
+ this.followY += (followTargetY - this.followY) * 0.16;
+ const saccadeWeight = following ? 0.2 : 1;
+ const drift = lively ? 1 : 0;
+ this.lookX.t =
+ this.saccade.x * saccadeWeight +
+ this.followX +
+ drift * (0.56 * Math.sin(t * 0.42) + 0.2 * Math.sin(t * 1.0 + 2));
+ this.lookY.t =
+ this.saccade.y * saccadeWeight + this.followY + drift * 0.36 * Math.sin(t * 0.58);
+
+ // Hover emphasis: bigger eyes, face drawn toward the middle.
+ const emphasis = lively && input.hovered && !input.working;
+ this.pull.t = emphasis ? 1 : 0;
+ this.eyeWidth.t = emphasis ? 1.18 : 1;
+ this.eyeHeight.t = emphasis ? 1.1 : 1;
+
+ // Blinks and the one-eye squint.
+ if (lively && now >= this.blinkAt && !this.blink) this.startBlink();
+ if (lively && !input.working && now >= this.squintAt && !this.squint) this.startSquint();
+ let blinkHeight = 1;
+ if (this.blink) {
+ const ms = (now - this.blink.start) * 1000;
+ const frames = this.blink.frames;
+ if (ms >= frames[frames.length - 1]![0]) this.blink = null;
+ else blinkHeight = sampleKeyframes(frames, ms);
+ }
+ const eyeHeight: [number, number] = [blinkHeight, blinkHeight];
+ if (this.squint) {
+ const progress = ((now - this.squint.start) * 1000) / SQUINT_MS;
+ if (progress >= 1) this.squint = null;
+ else {
+ const dip = progress < 0.42 ? progress / 0.42 : 1 - (progress - 0.42) / 0.58;
+ eyeHeight[this.squint.eye] *= 1 - 0.55 * dip;
+ }
+ }
+
+ // The working spin, a full turn of the face around the body.
+ if (lively && input.working && !this.spin && now >= this.spinAt) {
+ this.spin = spring(0);
+ this.spin.t = 2 * Math.PI;
+ this.spinDirection = Math.random() < 0.5 ? 1 : -1;
+ }
+
+ const substeps = Math.max(1, Math.ceil(dt * 120));
+ const h = dt / substeps;
+ for (let index = 0; index < substeps; index++) {
+ step(this.roll, 5, 0.9, h);
+ step(this.offsetX, 3.5, 1, h);
+ step(this.offsetY, 4, 1, h);
+ step(this.squash, 10, 0.8, h);
+ step(this.lookX, 13, 1, h);
+ step(this.lookY, 13, 1, h);
+ step(this.pull, 9, 1, h);
+ step(this.eyeWidth, 9, 0.85, h);
+ step(this.eyeHeight, 9, 0.85, h);
+ if (this.spin) step(this.spin, 6.2, 1, h);
+ }
+ let spin = 0;
+ if (this.spin) {
+ spin = this.spin.x * this.spinDirection;
+ if (settled(this.spin, 0.004)) {
+ this.spin = null;
+ spin = 0;
+ this.spinAt = now + rand(...SPIN_EVERY_MS) / 1000;
+ }
+ }
+
+ const frame: MotionFrame = {
+ roll: this.roll.x,
+ x: this.offsetX.x,
+ y: this.offsetY.x,
+ scaleY: this.squash.x,
+ gazeX: this.lookX.x,
+ gazeY: this.lookY.x,
+ pull: this.pull.x,
+ eyeWidth: this.eyeWidth.x,
+ eyeHeight: [eyeHeight[0] * this.eyeHeight.x, eyeHeight[1] * this.eyeHeight.x],
+ spin,
+ };
+
+ const resting =
+ settled(this.roll) &&
+ settled(this.offsetX) &&
+ settled(this.offsetY) &&
+ settled(this.squash) &&
+ settled(this.lookX) &&
+ settled(this.lookY) &&
+ settled(this.pull) &&
+ settled(this.eyeWidth) &&
+ settled(this.eyeHeight) &&
+ Math.abs(this.followX) < 0.01 &&
+ Math.abs(this.followY) < 0.01 &&
+ !this.spin &&
+ !this.blink &&
+ !this.squint;
+ if (!lively && resting) this.scheduleIdle();
+ return { frame, active: lively || !resting };
+ }
+
+ /** Drops every pending motion and snaps to the rest frame. */
+ private rest(): MotionFrame {
+ for (const s of [this.roll, this.offsetX, this.offsetY, this.lookX, this.lookY, this.pull]) {
+ s.x = s.t = s.v = 0;
+ }
+ for (const s of [this.squash, this.eyeWidth, this.eyeHeight]) {
+ s.x = s.t = 1;
+ s.v = 0;
+ }
+ this.followX = this.followY = 0;
+ this.saccade = { x: 0, y: 0 };
+ this.blink = this.squint = this.spin = null;
+ this.beatUntil = -1;
+ return REST_FRAME;
+ }
+
+ private scheduleIdle() {
+ const now = this.clock;
+ this.saccadeAt = now + rand(0.6, 1.5);
+ this.blinkAt = now + rand(1.2, 3);
+ this.squintAt = now + rand(4.5, 10);
+ this.spinAt = now + rand(1.5, 3.5);
+ }
+
+ private startBlink() {
+ this.blink = {
+ start: this.clock,
+ frames: Math.random() < 0.14 ? DOUBLE_BLINK : BLINK,
+ };
+ // Working bots blink often; hovered ones now and then.
+ this.blinkAt = this.clock + (this.working ? rand(1.8, 3.2) : rand(3, 6));
+ }
+
+ private startSquint() {
+ this.squint = { start: this.clock, eye: Math.random() < 0.5 ? 0 : 1 };
+ this.squintAt = this.clock + rand(4.5, 10);
+ }
+}
+
+export const REST_FRAME: MotionFrame = {
+ roll: 0,
+ x: 0,
+ y: 0,
+ scaleY: 1,
+ gazeX: 0,
+ gazeY: 0,
+ pull: 0,
+ eyeWidth: 1,
+ eyeHeight: [1, 1],
+ spin: 0,
+};
+
+/**
+ * Wraps a point on the face around the body like a belt turning by `angle`.
+ * Returns the new x and how wide the point should draw, or null when it has
+ * turned behind the body.
+ */
+export function wrapOnBelt(x: number, center: number, radius: number, angle: number) {
+ const u = Math.max(-0.999, Math.min(0.999, (x - center) / radius));
+ const a = Math.asin(u);
+ const cos = Math.cos(a + angle);
+ if (cos < 0.02) return null;
+ return { x: center + radius * Math.sin(a + angle), width: cos / Math.cos(a) };
+}
diff --git a/apps/web/src/components/roster/dither.logic.test.ts b/apps/web/src/components/roster/dither.logic.test.ts
deleted file mode 100644
index c28327d35..000000000
--- a/apps/web/src/components/roster/dither.logic.test.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import { describe, expect, it } from "vite-plus/test";
-
-import {
- contrastRatio,
- DITHER_GRID_SIZE,
- ditherForegroundColor,
- ditherSeedForName,
- generateDitherIdenticon,
- identiconPathData,
- orderedDitherRgba,
- rerollDitherSeed,
- resolveUploadAvatar,
-} from "./dither.logic";
-import { BLOB_COLORS } from "./roster.logic";
-
-describe("ditherForegroundColor", () => {
- it("meets 4.5:1 contrast against every palette background", () => {
- for (const color of BLOB_COLORS) {
- const foreground = ditherForegroundColor(color);
- expect(contrastRatio(color, foreground), color).toBeGreaterThanOrEqual(4.5);
- }
- });
-
- it("chooses the higher-contrast monochrome color", () => {
- for (const color of BLOB_COLORS) {
- const foreground = ditherForegroundColor(color);
- const other = foreground === "#000000" ? "#ffffff" : "#000000";
- expect(contrastRatio(color, foreground)).toBeGreaterThanOrEqual(contrastRatio(color, other));
- }
- });
-});
-
-describe("generateDitherIdenticon", () => {
- it("is deterministic: same seed, same cells and colors", () => {
- const a = generateDitherIdenticon("Akeru");
- const b = generateDitherIdenticon("Akeru");
- expect(b.cells).toEqual(a.cells);
- expect(b.background).toBe(a.background);
- expect(b.foreground).toBe(a.foreground);
- });
-
- it("differs across seeds", () => {
- const seeds = ["Akeru", "Mori", "Sage", "Akeru#a1b2c3"];
- const patterns = seeds.map((seed) => identiconPathData(generateDitherIdenticon(seed)));
- expect(new Set(patterns).size).toBe(seeds.length);
- });
-
- it("paints a readable pattern: both on and off cells, contrasting colors", () => {
- for (const seed of ["Akeru", "Mori", "Sage", "z", "bot"]) {
- const identicon = generateDitherIdenticon(seed);
- const onCount = identicon.cells.filter(Boolean).length;
- expect(onCount).toBeGreaterThan(0);
- expect(onCount).toBeLessThan(identicon.cells.length);
- expect(identicon.foreground).not.toBe(identicon.background);
- }
- });
-
- it("mirrors horizontally, identicon style", () => {
- const { size, cells } = generateDitherIdenticon("Akeru");
- for (let y = 0; y < size; y++) {
- for (let x = 0; x < size / 2; x++) {
- expect(cells[y * size + x]).toBe(cells[y * size + (size - 1 - x)]);
- }
- }
- });
-
- it("survives an empty seed", () => {
- const identicon = generateDitherIdenticon("");
- expect(identicon.cells).toHaveLength(DITHER_GRID_SIZE * DITHER_GRID_SIZE);
- });
-});
-
-describe("orderedDitherRgba", () => {
- const gradient = (width: number, height: number): Uint8ClampedArray => {
- const data = new Uint8ClampedArray(width * height * 4);
- for (let index = 0; index < width * height; index++) {
- const value = Math.round((index / (width * height - 1)) * 255);
- data.set([value, value, value, 255], index * 4);
- }
- return data;
- };
-
- it("changes pixels and leaves only pure black or white", () => {
- const width = 16;
- const height = 16;
- const data = gradient(width, height);
- const before = Uint8ClampedArray.from(data);
- orderedDitherRgba(data, width, height);
- expect(data).not.toEqual(before);
- for (let index = 0; index < data.length; index += 4) {
- expect([0, 255]).toContain(data[index]);
- expect(data[index + 1]).toBe(data[index]);
- expect(data[index + 2]).toBe(data[index]);
- expect(data[index + 3]).toBe(255);
- }
- });
-
- it("is deterministic for the same input", () => {
- const a = gradient(8, 8);
- const b = gradient(8, 8);
- orderedDitherRgba(a, 8, 8);
- orderedDitherRgba(b, 8, 8);
- expect(a).toEqual(b);
- });
-});
-
-describe("seeds", () => {
- it("derives the initial seed from the name, with a fallback", () => {
- expect(ditherSeedForName(" Akeru ")).toBe("Akeru");
- expect(ditherSeedForName(" ")).toBe("bot");
- });
-
- it("rerolls keep the name prefix and vary with the random source", () => {
- const first = rerollDitherSeed("Akeru", () => 0.25);
- const second = rerollDitherSeed("Akeru", () => 0.75);
- expect(first.startsWith("Akeru#")).toBe(true);
- expect(second).not.toBe(first);
- expect(rerollDitherSeed("Akeru", () => 0.25)).toBe(first);
- });
-});
-
-describe("resolveUploadAvatar", () => {
- const upload = { plainUrl: "data:plain", ditheredUrl: "data:dithered" };
-
- it("is null until an image is chosen", () => {
- expect(resolveUploadAvatar(null, false)).toBeNull();
- expect(resolveUploadAvatar(null, true)).toBeNull();
- });
-
- it("saves the plain rendering with dithered: false when the toggle is off", () => {
- expect(resolveUploadAvatar(upload, false)).toEqual({
- kind: "image",
- assetPath: "data:plain",
- dithered: false,
- });
- });
-
- it("saves the dithered rendering with dithered: true when the toggle is on", () => {
- expect(resolveUploadAvatar(upload, true)).toEqual({
- kind: "image",
- assetPath: "data:dithered",
- dithered: true,
- });
- });
-});
diff --git a/apps/web/src/components/roster/dither.logic.ts b/apps/web/src/components/roster/dither.logic.ts
deleted file mode 100644
index b5269e19a..000000000
--- a/apps/web/src/components/roster/dither.logic.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import { BLOB_COLORS } from "./roster.logic";
-import type { BotAvatar } from "./types";
-
-/**
- * Dither Kit style identicons: a seeded intensity field pushed through a
- * Bayer ordered-dither threshold. Everything here is deterministic — the same
- * seed always yields the same pixels — so avatars render from the seed alone
- * and nothing needs to be stored.
- */
-
-export const DITHER_GRID_SIZE = 16;
-
-// Classic 4×4 Bayer matrix; thresholds are (value + 0.5) / 16.
-const BAYER_4 = [
- [0, 8, 2, 10],
- [12, 4, 14, 6],
- [3, 11, 1, 9],
- [15, 7, 13, 5],
-] as const;
-
-// 8×8 Bayer matrix for photo dithering; thresholds are (value + 0.5) / 64.
-const BAYER_8 = [
- [0, 32, 8, 40, 2, 34, 10, 42],
- [48, 16, 56, 24, 50, 18, 58, 26],
- [12, 44, 4, 36, 14, 46, 6, 38],
- [60, 28, 52, 20, 62, 30, 54, 22],
- [3, 35, 11, 43, 1, 33, 9, 41],
- [51, 19, 59, 27, 49, 17, 57, 25],
- [15, 47, 7, 39, 13, 45, 5, 37],
- [63, 31, 55, 23, 61, 29, 53, 21],
-] as const;
-
-/** FNV-1a, 32-bit. Stable across sessions, unlike anything Math-random. */
-function hashSeed(seed: string): number {
- let hash = 0x811c9dc5;
- for (let index = 0; index < seed.length; index++) {
- hash ^= seed.charCodeAt(index);
- hash = Math.imul(hash, 0x01000193);
- }
- return hash >>> 0;
-}
-
-/** mulberry32: tiny seeded PRNG, consumed in a fixed order for determinism. */
-function mulberry32(state: number): () => number {
- let a = state >>> 0;
- return () => {
- a = (a + 0x6d2b79f5) >>> 0;
- let t = a;
- t = Math.imul(t ^ (t >>> 15), t | 1);
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-}
-
-/** The seed a bot's name implies; empty names still get a stable image. */
-export function ditherSeedForName(name: string): string {
- const trimmed = name.trim();
- return trimmed.length === 0 ? "bot" : trimmed;
-}
-
-/**
- * Rerolled seed: the name plus a random suffix, so the identicon stays
- * name-flavored while every roll lands on a different image. The random
- * source is injectable for tests.
- */
-export function rerollDitherSeed(name: string, random: () => number = Math.random): string {
- const suffix = Math.floor(random() * 36 ** 6)
- .toString(36)
- .padStart(6, "0");
- return `${ditherSeedForName(name)}#${suffix}`;
-}
-
-function relativeLuminance(hex: string): number {
- const match = /^#([0-9a-f]{6})$/i.exec(hex);
- if (match === null) return 0;
- const value = Number.parseInt(match[1]!, 16);
- const channel = (shift: number) => {
- const srgb = ((value >> shift) & 0xff) / 255;
- return srgb <= 0.04045 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;
- };
- return 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0);
-}
-
-/** WCAG contrast ratio for two six-digit hex colors. */
-export function contrastRatio(first: string, second: string): number {
- const firstLuminance = relativeLuminance(first);
- const secondLuminance = relativeLuminance(second);
- const lighter = Math.max(firstLuminance, secondLuminance);
- const darker = Math.min(firstLuminance, secondLuminance);
- return (lighter + 0.05) / (darker + 0.05);
-}
-
-/** Pick the higher-contrast monochrome foreground for dither pixels. */
-export function ditherForegroundColor(background: string): "#000000" | "#ffffff" {
- return contrastRatio(background, "#000000") >= contrastRatio(background, "#ffffff")
- ? "#000000"
- : "#ffffff";
-}
-
-export interface DitherIdenticon {
- /** Grid side length; cells is row-major size × size. */
- size: number;
- /** True cells paint the foreground color. */
- cells: boolean[];
- background: string;
- foreground: string;
-}
-
-/**
- * Seed → identicon. A jittered radial intensity field plus per-cell noise is
- * thresholded by the Bayer 4×4 matrix, then mirrored horizontally for the
- * classic identicon symmetry. Background comes from the blob palette and the
- * foreground picks whichever of black or white has the higher measured
- * contrast, so the image stays readable in both color schemes.
- */
-export function generateDitherIdenticon(seed: string): DitherIdenticon {
- const random = mulberry32(hashSeed(seed.length === 0 ? "bot" : seed));
- const background = BLOB_COLORS[Math.floor(random() * BLOB_COLORS.length)]!;
- const size = DITHER_GRID_SIZE;
- const half = size / 2;
- const centerX = half - 0.5 + (random() - 0.5) * 3;
- const centerY = half - 0.5 + (random() - 0.5) * 3;
- const falloff = 1.2 + random() * 1.4;
- const noiseWeight = 0.25 + random() * 0.3;
-
- const cells = Array.from({ length: size * size }, () => false);
- for (let y = 0; y < size; y++) {
- for (let x = 0; x < half; x++) {
- const dx = (x - centerX) / half;
- const dy = (y - centerY) / half;
- const base = Math.max(0, 1 - Math.sqrt(dx * dx + dy * dy) ** falloff);
- const intensity = base * (1 - noiseWeight) + random() * noiseWeight;
- const on = intensity > (BAYER_4[y % 4]![x % 4]! + 0.5) / 16;
- cells[y * size + x] = on;
- cells[y * size + (size - 1 - x)] = on;
- }
- }
- return { size, cells, background, foreground: ditherForegroundColor(background) };
-}
-
-/** One SVG path of unit squares for the on cells; a single element per avatar. */
-export function identiconPathData(identicon: DitherIdenticon): string {
- const parts: string[] = [];
- for (let y = 0; y < identicon.size; y++) {
- for (let x = 0; x < identicon.size; x++) {
- if (identicon.cells[y * identicon.size + x]) parts.push(`M${x} ${y}h1v1h-1z`);
- }
- }
- return parts.join("");
-}
-
-/**
- * In-place ordered dither over RGBA pixels: per-pixel luminance against the
- * tiled Bayer 8×8 threshold, output pure black or white, alpha untouched.
- * Operates on the raw array so tests run without a DOM ImageData.
- */
-export function orderedDitherRgba(data: Uint8ClampedArray, width: number, height: number): void {
- for (let y = 0; y < height; y++) {
- for (let x = 0; x < width; x++) {
- const index = (y * width + x) * 4;
- const luminance =
- (0.299 * data[index]! + 0.587 * data[index + 1]! + 0.114 * data[index + 2]!) / 255;
- const value = luminance > (BAYER_8[y % 8]![x % 8]! + 0.5) / 64 ? 255 : 0;
- data[index] = value;
- data[index + 1] = value;
- data[index + 2] = value;
- }
- }
-}
-
-/** Both renderings of one upload, computed together at upload time. */
-export interface UploadRendering {
- plainUrl: string;
- ditheredUrl: string;
-}
-
-/**
- * The avatar record an upload saves: the dithered rendering with
- * dithered: true when the toggle is on, the plain one with dithered: false
- * otherwise. Null until an image is chosen.
- */
-export function resolveUploadAvatar(
- upload: UploadRendering | null,
- ditherEnabled: boolean,
-): BotAvatar | null {
- if (upload === null) return null;
- return ditherEnabled
- ? { kind: "image", assetPath: upload.ditheredUrl, dithered: true }
- : { kind: "image", assetPath: upload.plainUrl, dithered: false };
-}
diff --git a/apps/web/src/components/roster/roster.logic.test.ts b/apps/web/src/components/roster/roster.logic.test.ts
index 60f2d4aa9..bbfc1961b 100644
--- a/apps/web/src/components/roster/roster.logic.test.ts
+++ b/apps/web/src/components/roster/roster.logic.test.ts
@@ -2,7 +2,7 @@ import { BotId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
- blinkDelayMs,
+ botAvatarSeed,
buildGroupedRosterSections,
buildRosterSections,
buildRosterStrip,
@@ -17,7 +17,9 @@ import {
parseChatPath,
randomBotAvatar,
resolveBlobRendering,
- resolveBlobEyeColor,
+ resolveBlobColor,
+ resolveBlobEyes,
+ resolveBlobOutline,
resolveBotPresence,
resolveLatestRosterMessage,
resolveRosterBotId,
@@ -62,12 +64,40 @@ function bot(input: Partial<Bot> & Pick<Bot, "id" | "name">): Bot {
};
}
-describe("resolveBlobEyeColor", () => {
- it("chooses the eye color with the stronger contrast", () => {
- expect(resolveBlobEyeColor("#141062")).toBe("#FFFFFF");
- expect(resolveBlobEyeColor("#E0645C")).toBe("#0A0A0A");
- expect(resolveBlobEyeColor("#FFFFFF")).toBe("#0A0A0A");
- expect(resolveBlobEyeColor("#000000")).toBe("#FFFFFF");
+describe("resolveBlobEyes", () => {
+ it("cuts eyes out of every preset", () => {
+ for (const color of BLOB_COLORS) {
+ expect(resolveBlobEyes(color)).toEqual({ kind: "cutout" });
+ }
+ });
+
+ it("paints eyes on bodies too light or too dark for a cutout to read", () => {
+ expect(resolveBlobEyes("#FFFFFF")).toEqual({ kind: "ink", ink: "#161616" });
+ expect(resolveBlobEyes("#FFF4B0")).toEqual({ kind: "ink", ink: "#161616" });
+ expect(resolveBlobEyes("#000000")).toEqual({ kind: "ink", ink: "#FFFFFF" });
+ });
+});
+
+describe("resolveBlobColor", () => {
+ it("moves retired muted presets onto the vivid palette", () => {
+ expect(resolveBlobColor("#E0645C")).toBe("#FF4A5A");
+ expect(resolveBlobColor("#7a8699")).toBe("#8E8E93");
+ });
+
+ it("keeps custom colors and falls back for invalid ones", () => {
+ expect(resolveBlobColor("#123abc")).toBe("#123ABC");
+ expect(resolveBlobColor("#FFFFFF")).toBe("#FFFFFF");
+ expect(resolveBlobColor("")).toBe(DEFAULT_BLOB_COLOR);
+ expect(resolveBlobColor("red")).toBe(DEFAULT_BLOB_COLOR);
+ });
+});
+
+describe("resolveBlobOutline", () => {
+ it("outlines only bodies light enough to fade into a light surface", () => {
+ expect(resolveBlobOutline("#FFFFFF")).not.toBeNull();
+ for (const color of [...BLOB_COLORS, "#000000", "nope"]) {
+ expect(resolveBlobOutline(color)).toBeNull();
+ }
});
});
@@ -348,14 +378,13 @@ describe("roster drag ids", () => {
});
describe("randomBotAvatar", () => {
- it("returns a valid blob and never picks white", () => {
+ it("returns a valid blob from the presets", () => {
for (let i = 0; i < 20; i++) {
const avatar = randomBotAvatar(() => i / 20);
expect(avatar.kind).toBe("blob");
if (avatar.kind !== "blob") continue;
expect(BLOB_SHAPES).toContain(avatar.shape);
expect(BLOB_COLORS).toContain(avatar.color);
- expect(avatar.color).not.toBe("#FFFFFF");
}
});
@@ -458,17 +487,26 @@ describe("resolveLatestRosterMessage", () => {
describe("resolveBlobRendering", () => {
it("passes a valid blob avatar through", () => {
- expect(resolveBlobRendering({ kind: "blob", shape: "hex", color: "#5BA97B" })).toEqual({
+ expect(resolveBlobRendering({ kind: "blob", shape: "hex", color: "#16C47A" })).toEqual({
shape: "hex",
- color: "#5BA97B",
+ color: "#16C47A",
});
});
- it("falls back to the default blob for non-blob kinds", () => {
- expect(resolveBlobRendering({ kind: "dither", seed: "abc" })).toEqual({
- shape: DEFAULT_BLOB_SHAPE,
- color: DEFAULT_BLOB_COLOR,
- });
+ it("draws legacy dither avatars as a stable blob picked from the seed", () => {
+ const first = resolveBlobRendering({ kind: "dither", seed: "bot-a" });
+ expect(resolveBlobRendering({ kind: "dither", seed: "bot-a" })).toEqual(first);
+ expect(BLOB_SHAPES).toContain(first.shape);
+ expect(BLOB_COLORS).toContain(first.color);
+ const looks = new Set(
+ ["bot-a", "bot-b", "bot-c", "bot-d", "bot-e"].map((seed) =>
+ JSON.stringify(resolveBlobRendering({ kind: "dither", seed })),
+ ),
+ );
+ expect(looks.size).toBeGreaterThan(1);
+ });
+
+ it("falls back to the default blob for images and missing avatars", () => {
expect(resolveBlobRendering({ kind: "image", assetPath: "/a.png", dithered: false })).toEqual({
shape: DEFAULT_BLOB_SHAPE,
color: DEFAULT_BLOB_COLOR,
@@ -496,15 +534,15 @@ describe("resolveBlobRendering", () => {
});
});
-describe("blinkDelayMs", () => {
- it("is a stable phase offset within one blink cycle", () => {
- expect(blinkDelayMs("Akeru")).toBe(blinkDelayMs("Akeru"));
- expect(blinkDelayMs("Akeru")).toBeLessThanOrEqual(0);
- expect(blinkDelayMs("Akeru")).toBeGreaterThan(-6400);
+describe("botAvatarSeed", () => {
+ it("is a stable seed between 0 and 1", () => {
+ expect(botAvatarSeed("Akeru")).toBe(botAvatarSeed("Akeru"));
+ expect(botAvatarSeed("Akeru")).toBeGreaterThanOrEqual(0);
+ expect(botAvatarSeed("Akeru")).toBeLessThan(1);
});
it("staggers different bots", () => {
- expect(blinkDelayMs("Akeru")).not.toBe(blinkDelayMs("Mori"));
+ expect(botAvatarSeed("Akeru")).not.toBe(botAvatarSeed("Mori"));
});
});
diff --git a/apps/web/src/components/roster/roster.logic.ts b/apps/web/src/components/roster/roster.logic.ts
index 1fd56eb59..d69094443 100644
--- a/apps/web/src/components/roster/roster.logic.ts
+++ b/apps/web/src/components/roster/roster.logic.ts
@@ -21,23 +21,43 @@ export const BLOB_SHAPES: readonly BotBlobShape[] = [
];
export const BLOB_COLORS: readonly string[] = [
- "#FFFFFF",
- "#E0645C",
- "#E8883A",
- "#D9A833",
- "#5BA97B",
- "#4E9BB8",
- "#5B7FD4",
- "#8B6FC9",
- "#C96FA8",
- "#7A8699",
+ "#FF4A5A",
+ "#FF7A1F",
+ "#FFA826",
+ "#16C47A",
+ "#1FBFAE",
+ "#2E8EFF",
+ "#9A68FF",
+ "#FF4FA8",
+ "#A0764F",
+ "#8E8E93",
];
export const DEFAULT_BLOB_SHAPE: BotBlobShape = "circle";
-export const DEFAULT_BLOB_COLOR = "#7A8699";
-const DARK_EYES = "#0A0A0A";
+export const DEFAULT_BLOB_COLOR = "#8E8E93";
+const DARK_EYES = "#161616";
const LIGHT_EYES = "#FFFFFF";
+/** The muted presets bots were saved with before the palette went vivid. */
+const LEGACY_BLOB_COLORS: Record<string, string> = {
+ "#E0645C": "#FF4A5A",
+ "#E8883A": "#FF7A1F",
+ "#D9A833": "#FFA826",
+ "#5BA97B": "#16C47A",
+ "#4E9BB8": "#1FBFAE",
+ "#5B7FD4": "#2E8EFF",
+ "#8B6FC9": "#9A68FF",
+ "#C96FA8": "#FF4FA8",
+ "#7A8699": "#8E8E93",
+};
+
+/** Normalizes a stored body color, moving retired presets onto the current palette. */
+export function resolveBlobColor(value: unknown) {
+ if (!isBotAvatarColor(value)) return DEFAULT_BLOB_COLOR;
+ const color = value.toUpperCase();
+ return LEGACY_BLOB_COLORS[color] ?? color;
+}
+
function relativeLuminance(hexColor: string) {
const channels = hexColor
.slice(1)
@@ -52,23 +72,23 @@ function relativeLuminance(hexColor: string) {
return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
}
-function contrastRatio(first: number, second: number) {
- const lighter = Math.max(first, second);
- const darker = Math.min(first, second);
- return (lighter + 0.05) / (darker + 0.05);
+/**
+ * How the eyes are drawn. Most bodies cut their eyes out so the surface shows
+ * through. Near-white and near-black bodies would lose cutout eyes against a
+ * matching surface, so they paint them in a contrasting ink instead.
+ */
+export function resolveBlobEyes(color: string): { kind: "cutout" } | { kind: "ink"; ink: string } {
+ const luminance = isBotAvatarColor(color) ? relativeLuminance(color) : null;
+ if (luminance === null) return { kind: "cutout" };
+ if (luminance > 0.6) return { kind: "ink", ink: DARK_EYES };
+ if (luminance < 0.02) return { kind: "ink", ink: LIGHT_EYES };
+ return { kind: "cutout" };
}
-/** Picks whichever eye color has the stronger contrast against the blob. */
-export function resolveBlobEyeColor(color: string) {
- if (!isBotAvatarColor(color)) return DARK_EYES;
-
- const bodyLuminance = relativeLuminance(color);
- const darkLuminance = relativeLuminance(DARK_EYES);
- if (bodyLuminance === null || darkLuminance === null) return DARK_EYES;
-
- const darkContrast = contrastRatio(bodyLuminance, darkLuminance);
- const lightContrast = contrastRatio(bodyLuminance, 1);
- return lightContrast > darkContrast ? LIGHT_EYES : DARK_EYES;
+/** A faint edge for light bodies that would otherwise fade into a light surface. */
+export function resolveBlobOutline(color: string) {
+ const luminance = isBotAvatarColor(color) ? relativeLuminance(color) : null;
+ return luminance !== null && luminance > 0.7 ? "rgba(0, 0, 0, 0.14)" : null;
}
export function isBotAvatarColor(value: unknown): value is string {
@@ -81,14 +101,24 @@ export function isBotBlobShape(value: string): value is BotBlobShape {
/**
* Every avatar kind resolves to a paintable blob so the roster never renders
- * an empty slot: dither and image avatars (and any unknown blob shape coming
- * from persisted or server data) fall back to the default circle blob until
- * their real renderer applies.
+ * an empty slot. Legacy dither avatars, which delegated bots and imports still
+ * carry, become a blob picked from their seed so each bot keeps a stable,
+ * distinct look. Image avatars and unknown blob shapes from persisted or
+ * server data fall back to the default circle.
*/
export function resolveBlobRendering(avatar: BotAvatar | null | undefined): {
shape: BotBlobShape;
color: string;
} {
+ if (avatar?.kind === "dither") {
+ const hash = Math.abs(hashSeed(avatar.seed));
+ return {
+ shape: BLOB_SHAPES[hash % BLOB_SHAPES.length] ?? DEFAULT_BLOB_SHAPE,
+ color:
+ BLOB_COLORS[Math.floor(hash / BLOB_SHAPES.length) % BLOB_COLORS.length] ??
+ DEFAULT_BLOB_COLOR,
+ };
+ }
if (avatar?.kind !== "blob") {
return { shape: DEFAULT_BLOB_SHAPE, color: DEFAULT_BLOB_COLOR };
}
@@ -96,21 +126,16 @@ export function resolveBlobRendering(avatar: BotAvatar | null | undefined): {
// default circle rather than an empty slot.
return {
shape: isBotBlobShape(avatar.shape) ? avatar.shape : DEFAULT_BLOB_SHAPE,
- color: avatar.color || DEFAULT_BLOB_COLOR,
+ color: resolveBlobColor(avatar.color),
};
}
-/**
- * Random blob avatar for a freshly created bot. White is excluded so an
- * auto-assigned body never washes out on the light sidebar; it stays
- * pickable in the avatar picker. `random` is injectable for tests.
- */
+/** Random blob avatar for a freshly created bot. `random` is injectable for tests. */
export function randomBotAvatar(
random: () => number = Math.random,
): Extract<BotAvatar, { kind: "blob" }> {
- const colors = BLOB_COLORS.filter((color) => color !== "#FFFFFF");
const shape = BLOB_SHAPES[Math.floor(random() * BLOB_SHAPES.length)] ?? DEFAULT_BLOB_SHAPE;
- const color = colors[Math.floor(random() * colors.length)] ?? DEFAULT_BLOB_COLOR;
+ const color = BLOB_COLORS[Math.floor(random() * BLOB_COLORS.length)] ?? DEFAULT_BLOB_COLOR;
return { kind: "blob", shape, color };
}
@@ -145,14 +170,17 @@ export function resolveBotPresence(shell: PresenceShell | null): RosterPresence
}
/**
- * Phase offset for the idle blink, so a roster full of bots never blinks in
- * sync. Negative so the animation starts mid-cycle. The modulo must match the
- * `bot-blink` duration in index.css.
+ * Stable 0–1 motion seed per bot, so a roster full of avatars never blinks or
+ * glances in sync.
*/
-export function blinkDelayMs(seed: string): number {
+export function botAvatarSeed(seed: string): number {
+ return (Math.abs(hashSeed(seed)) % 1000) / 1000;
+}
+
+function hashSeed(seed: string) {
let hash = 0;
for (let i = 0; i < seed.length; i++) hash = (hash * 31 + seed.charCodeAt(i)) | 0;
- return -(Math.abs(hash) % 6400);
+ return hash;
}
export function resolveRosterBotId(
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index e790ca1db..298f33aec 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -2549,52 +2549,23 @@ code {
}
}
-/* Bot avatars. State-driven and transform-only. Working uses weighted
- squash-and-stretch. Needs-you calls twice, then holds. Success hops once.
- Never use fill-box: a blinking <g> shrinks its origin every frame and the
- avatar strobes. Body motion is the 100×100 viewBox; eyes use their own. */
-.bot-avatar {
+/* Bot avatars. Flat SVG blobs moved by the spring engine in
+ botAvatarMotion.ts, which writes the body transform here and the eye
+ transforms on the SVG. The body transform stays on an HTML wrapper so it
+ composites; cutout eyes live in an SVG mask, which repaints only while
+ they move. */
+.bot-avatar .bot-body,
+.bot-avatar svg {
+ display: block;
+ width: 100%;
+ height: 100%;
overflow: visible;
}
.bot-avatar .bot-body {
- transform-box: view-box;
- transform-origin: 50px 100px;
-}
-
-.bot-avatar .bot-eyes {
- display: inline;
- overflow: visible;
- transform-box: view-box;
transform-origin: 50% 50%;
}
-.bot-avatar[data-bot-state="idle"] .bot-eyes {
- animation: bot-blink 6.4s linear infinite;
- animation-delay: var(--bot-blink-delay, 0ms);
-}
-
-.bot-avatar[data-bot-state="idle"]:hover .bot-body,
-[data-bot-hover]:hover .bot-avatar[data-bot-state="idle"] .bot-body {
- animation: bot-hover 240ms cubic-bezier(0.2, 0, 0, 1);
-}
-
-.bot-avatar[data-bot-state="working"] .bot-body {
- animation: bot-work 960ms cubic-bezier(0.45, 0, 0.55, 1) infinite;
-}
-
-.bot-avatar[data-bot-state="needs-you"] .bot-body {
- animation: bot-call 2.4s linear infinite;
-}
-
-.bot-avatar[data-bot-state="success"] .bot-body {
- animation: bot-success 680ms linear both;
-}
-
-.bot-avatar[data-bot-state="success"] .bot-eyes {
- animation: bot-success-eyes 680ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
-}
-
.bot-status-shimmer {
color: transparent;
background-image: linear-gradient(
@@ -2615,154 +2586,9 @@ code {
}
}
-@keyframes bot-work {
- 0%,
- 100% {
- transform: translateY(0) rotate(0deg) scale(1, 1);
- }
-
- 12% {
- transform: translateY(1%) rotate(-2deg) scale(1.03, 0.97);
- }
-
- 28% {
- transform: translateY(-2%) rotate(-5deg) scale(0.97, 1.04);
- }
-
- 50% {
- transform: translateY(0) rotate(0deg) scale(1.02, 0.98);
- }
-
- 62% {
- transform: translateY(1%) rotate(2deg) scale(1.03, 0.97);
- }
-
- 78% {
- transform: translateY(-2%) rotate(5deg) scale(0.97, 1.04);
- }
-}
-
-@keyframes bot-call {
- 0%,
- 70%,
- 100% {
- transform: translateY(0) rotate(0deg) scale(1, 1);
- }
-
- 6% {
- transform: translateY(1%) rotate(0deg) scale(1.06, 0.92);
- animation-timing-function: cubic-bezier(0.4, 0, 1, 1);
- }
-
- 14% {
- transform: translateY(-7%) rotate(-3deg) scale(0.95, 1.08);
- animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
- }
-
- 24% {
- transform: translateY(0) rotate(2deg) scale(1.04, 0.95);
- }
-
- 32% {
- transform: translateY(0) rotate(0deg) scale(1, 1);
- }
-
- 44% {
- transform: translateY(1%) rotate(0deg) scale(1.04, 0.95);
- }
-
- 52% {
- transform: translateY(-4%) rotate(3deg) scale(0.98, 1.05);
- }
-
- 62% {
- transform: translateY(0) rotate(-1deg) scale(1.02, 0.98);
- }
-}
-
-@keyframes bot-success {
- 0% {
- transform: translateY(0) rotate(0deg) scale(1, 1);
- }
-
- 12% {
- transform: translateY(1%) rotate(0deg) scale(1.1, 0.88);
- animation-timing-function: cubic-bezier(0.4, 0, 1, 1);
- }
-
- 32% {
- transform: translateY(-12%) rotate(-4deg) scale(0.94, 1.08);
- animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
- }
-
- 48% {
- transform: translateY(-10%) rotate(4deg) scale(0.96, 1.06);
- }
-
- 65% {
- transform: translateY(0) rotate(0deg) scale(1.08, 0.9);
- }
-
- 80% {
- transform: translateY(-3%) rotate(0deg) scale(0.98, 1.03);
- }
-
- 100% {
- transform: translateY(0) rotate(0deg) scale(1, 1);
- }
-}
-
-@keyframes bot-success-eyes {
- 0%,
- 10% {
- transform: translateY(4%) scaleY(0.2);
- }
-
- 30% {
- transform: translateY(-2%) scaleY(1);
- }
-
- 46% {
- transform: translateY(0) scaleY(1.08);
- }
-
- 100% {
- transform: translateY(0) scaleY(1);
- }
-}
-
-@keyframes bot-blink {
- 0%,
- 93%,
- 95.25%,
- 100% {
- transform: scaleY(1);
- }
-
- 94% {
- transform: scaleY(0.08);
- }
-}
-
-@keyframes bot-hover {
- 0%,
- 100% {
- transform: translateY(0) scale(1, 1);
- }
-
- 50% {
- transform: translateY(-2px) scale(1.03, 0.98);
- }
-}
-
@media (prefers-reduced-motion: reduce) {
- .bot-avatar .bot-eyes,
- .bot-avatar .bot-body,
.bot-status-shimmer {
animation: none;
- }
-
- .bot-status-shimmer {
color: var(--foreground);
background: none;
}
diff --git a/docs/user/bots.md b/docs/user/bots.md
index 68bd5d05f..10e74d4dc 100644
--- a/docs/user/bots.md
+++ b/docs/user/bots.md
@@ -15,6 +15,14 @@ You can connect a subscription in Settings and use **Create** to add a bot later
You can change the bot's avatar, name, label, description, model, voice access, and enabled tools.
Select **Save** to apply the changes.
+Shaped avatars are a flat colored body with a face. The eyes are cut out of the body, so they take
+the color of whatever sits behind the avatar. Very light and very dark custom colors draw their eyes
+on instead. Bots saved with an older preset color show the matching color from the current palette.
+
+Avatars rest on a still frame. A working bot sways, glances down at its work, and now and then turns
+its face around its body. Point at a bot and its eyes widen and follow the pointer. Now and then one
+resting bot on screen blinks or glances around. With reduced motion turned on, avatars stay still.
+
Set **Token hard stop** to interrupt the current step when it reaches the selected limit. A settled
reply shows its engine, step tokens, and estimated USD cost when the provider reports enough usage
data.