Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): richer generated avatars with legible palettes

Gus411585053260
diff --git a/src/web/src/components/avatar/boring-avatar.test.ts b/src/web/src/components/avatar/boring-avatar.test.ts
index c06d26f26..305bb30f7 100644
--- a/src/web/src/components/avatar/boring-avatar.test.ts
+++ b/src/web/src/components/avatar/boring-avatar.test.ts
@@ -4,27 +4,39 @@ import { BoringAvatar } from "./boring-avatar"
// BoringAvatar returns a wrapper <span> (co-locating the caller's radius
// className with overflow-hidden so a square SVG gets cropped to the container
-// shape) whose single child is the boring-avatars <Avatar>.
+// shape). Its child depends on variant:
+// - beam (default): our own face renderer, injected as SVG via a span.
+// - marble: the boring-avatars <Avatar> (gradient background).
type SpanEl = {
type: "span"
- props: { className: string; style: { width: number | string; height: number | string }; children: AvatarEl }
+ props: {
+ className: string
+ style: { width: number | string; height: number | string }
+ children: unknown
+ }
}
type AvatarEl = { type: typeof Avatar; props: { square: boolean; size: number | string; className: string; variant: string; preserveAspectRatio?: string } }
-function inner(el: unknown): AvatarEl["props"] {
- return (el as SpanEl).props.children.props
+function child(el: unknown): unknown {
+ return (el as SpanEl).props.children
}
describe("BoringAvatar", () => {
- it("defaults to a SQUARE svg so the container radius crops it", () => {
+ it("renders our generated face SVG for the default (beam) variant", () => {
const el = BoringAvatar({ seed: "s1" }) as unknown as SpanEl
expect(el.type).toBe("span")
- expect(inner(el).square).toBe(true)
+ const inner = child(el) as { props: { dangerouslySetInnerHTML: { __html: string } } }
+ // beam is our face renderer, not the lib — injected as an SVG string.
+ expect(inner.props.dangerouslySetInnerHTML.__html).toContain("<svg")
+ expect(inner.props.dangerouslySetInnerHTML.__html).toContain('viewBox="0 0 36 36"')
})
- it("still honors an explicit square={false}", () => {
- const el = BoringAvatar({ seed: "s1", square: false }) as unknown as SpanEl
- expect(inner(el).square).toBe(false)
+ it("is deterministic — same seed renders the same beam face", () => {
+ const a = BoringAvatar({ seed: "s1" }) as unknown as SpanEl
+ const b = BoringAvatar({ seed: "s1" }) as unknown as SpanEl
+ const ha = (child(a) as { props: { dangerouslySetInnerHTML: { __html: string } } }).props.dangerouslySetInnerHTML.__html
+ const hb = (child(b) as { props: { dangerouslySetInnerHTML: { __html: string } } }).props.dangerouslySetInnerHTML.__html
+ expect(ha).toBe(hb)
})
it("co-locates the caller's radius className with overflow-hidden on the wrapper", () => {
@@ -33,17 +45,19 @@ describe("BoringAvatar", () => {
expect(el.props.className).toContain("overflow-hidden")
})
- it("gives the wrapper an explicit box from size, and fills it with the inner avatar", () => {
+ it("gives the wrapper an explicit box from size", () => {
const el = BoringAvatar({ seed: "s1", size: 40 }) as unknown as SpanEl
expect(el.props.style).toEqual({ width: 40, height: 40 })
- expect(inner(el).size).toBe("100%")
- expect(inner(el).className).toContain("size-full")
})
- it("forwards variant and preserveAspectRatio to the inner avatar (marble background)", () => {
- const el = BoringAvatar({ seed: "s1", variant: "marble", size: "100%", preserveAspectRatio: "none" }) as unknown as SpanEl
- expect(inner(el).variant).toBe("marble")
- expect(inner(el).preserveAspectRatio).toBe("none")
+ it("forwards variant/square/preserveAspectRatio to the lib for marble (background)", () => {
+ const el = BoringAvatar({ seed: "s1", variant: "marble", size: "100%", preserveAspectRatio: "none", square: false }) as unknown as SpanEl
+ const inner = child(el) as AvatarEl
+ expect(inner.type).toBe(Avatar)
+ expect(inner.props.variant).toBe("marble")
+ expect(inner.props.preserveAspectRatio).toBe("none")
+ expect(inner.props.square).toBe(false)
+ expect(inner.props.size).toBe("100%")
expect(el.props.style).toEqual({ width: "100%", height: "100%" })
})
})
diff --git a/src/web/src/components/avatar/boring-avatar.tsx b/src/web/src/components/avatar/boring-avatar.tsx
index 1cfd948f2..1d2efa516 100644
--- a/src/web/src/components/avatar/boring-avatar.tsx
+++ b/src/web/src/components/avatar/boring-avatar.tsx
@@ -2,6 +2,7 @@
import Avatar from "boring-avatars";
import { paletteFromSeed } from "@/lib/avatar/boring-palettes";
+import { renderFaceSvg } from "@/lib/avatar/face";
import { cn } from "@/lib/utils";
/**
@@ -10,8 +11,11 @@ import { cn } from "@/lib/utils";
* component. `seed` maps to boring-avatars' `name` prop (deterministic), and
* the palette is chosen deterministically from the same seed.
*
- * `beam` (default) is the face fallback; `marble` is the gradient background
- * used for server/channel icons and the profile banner.
+ * `beam` (default) is the face fallback — rendered by our own `renderFaceSvg`
+ * (richer shape/eye/mouth vocabulary than the lib's fixed beam), same 36-unit
+ * canvas + seed-derived palette so it drops into the same crop. `marble` is the
+ * gradient background (server/channel icons, profile banner) and stays on the
+ * lib.
*
* `square` defaults to true so the underlying SVG is a full square that the
* container's radius crops — matching how photo `object-cover` avatars behave.
@@ -40,15 +44,21 @@ export function BoringAvatar({
}) {
return (
<span className={cn("inline-flex overflow-hidden align-middle", className)} style={{ width: size, height: size }}>
- <Avatar
- size="100%"
- name={seed}
- variant={variant}
- colors={paletteFromSeed(seed)}
- square={square}
- className="size-full"
- preserveAspectRatio={preserveAspectRatio}
- />
+ {variant === "beam" ? (
+ // Our generated face — self-contained SVG (viewBox 0 0 36 36, 100% w/h),
+ // fills the crop span exactly like the lib's `size="100%"` did.
+ <span className="size-full [&>svg]:block [&>svg]:size-full" dangerouslySetInnerHTML={{ __html: renderFaceSvg(seed, paletteFromSeed(seed)) }} />
+ ) : (
+ <Avatar
+ size="100%"
+ name={seed}
+ variant={variant}
+ colors={paletteFromSeed(seed)}
+ square={square}
+ className="size-full"
+ preserveAspectRatio={preserveAspectRatio}
+ />
+ )}
</span>
);
}
diff --git a/src/web/src/lib/avatar/boring-palettes.ts b/src/web/src/lib/avatar/boring-palettes.ts
index c088a1ae2..b71702f8f 100644
--- a/src/web/src/lib/avatar/boring-palettes.ts
+++ b/src/web/src/lib/avatar/boring-palettes.ts
@@ -3,9 +3,10 @@
*
* Set 0 is the official boringavatars.com sample palette; the rest are the
* opening entries of Matt DesLauriers' Nice Color Palettes (the same source
- * boringavatars.com's own playground samples from). Colors are used as-is for
- * this vibe-check phase — DESIGN.md's desaturation rule is a deliberate
- * follow-up, not applied here.
+ * boringavatars.com's own playground samples from). Three template entries
+ * (idx 3, 6, 7) were replaced with lively, curated sets — the originals were
+ * muddy/dark or had clashing hues (the template-residue bug DESIGN.md calls
+ * out). No global desaturation: it dropped contrast, so the vibrant hues stand.
*
* Selection reuses the same hash + mulberry32 PRNG as `gradient-from-seed.ts`
* so the "looks random, never flickers" behavior matches the rest of the app.
@@ -15,11 +16,11 @@ export const PALETTES: readonly (readonly string[])[] = [
["#00686c", "#32c2b9", "#edecb3", "#fad928", "#ff9915"],
["#69d2e7", "#a7dbd8", "#e0e4cc", "#f38630", "#fa6900"],
["#fe4365", "#fc9d9a", "#f9cdad", "#c8c8a9", "#83af9b"],
- ["#ecd078", "#d95b43", "#c02942", "#542437", "#53777a"],
+ ["#ffd166", "#f4845f", "#ef476f", "#c86b98", "#6a8caf"],
["#556270", "#4ecdc4", "#c7f464", "#ff6b6b", "#c44d58"],
["#774f38", "#e08e79", "#f1d4af", "#ece5ce", "#c5e0dc"],
- ["#e8ddcb", "#cdb380", "#036564", "#033649", "#031634"],
- ["#490a3d", "#bd1550", "#e97f02", "#f8ca00", "#8a9b0f"],
+ ["#0b525b", "#06d6a0", "#8ac6d1", "#ffd166", "#ff9f68"],
+ ["#3a2e4d", "#8a5a9e", "#e0729a", "#ffb26b", "#ffe08a"],
["#594f4f", "#547980", "#45ada8", "#9de0ad", "#e5fcc2"],
["#00a0b0", "#6a4a3c", "#cc333f", "#eb6841", "#edc951"],
["#e94e77", "#d68189", "#c6a49a", "#c6e5d9", "#f4ead5"],
diff --git a/src/web/src/lib/avatar/face.test.ts b/src/web/src/lib/avatar/face.test.ts
new file mode 100644
index 000000000..831489781
--- /dev/null
+++ b/src/web/src/lib/avatar/face.test.ts
@@ -0,0 +1,143 @@
+import { describe, it, expect } from "vitest"
+import { renderFaceSvg, ink } from "./face"
+
+const PALETTE = ["#00686c", "#32c2b9", "#edecb3", "#fad928", "#ff9915"]
+
+describe("ink", () => {
+ it("returns black ink on a light wrapper", () => {
+ expect(ink("#edecb3")).toBe("#000000")
+ })
+ it("returns white ink on a dark wrapper", () => {
+ expect(ink("#00686c")).toBe("#ffffff")
+ })
+})
+
+describe("renderFaceSvg", () => {
+ it("is deterministic — same seed + palette → identical SVG", () => {
+ const a = renderFaceSvg("Shelly#3863", PALETTE)
+ const b = renderFaceSvg("Shelly#3863", PALETTE)
+ expect(a).toBe(b)
+ })
+
+ it("emits a well-formed 36-unit SVG", () => {
+ const svg = renderFaceSvg("Alice", PALETTE)
+ expect(svg.startsWith("<svg")).toBe(true)
+ expect(svg).toContain('viewBox="0 0 36 36"')
+ expect(svg.trim().endsWith("</svg>")).toBe(true)
+ })
+
+ it("uses no <mask> id (would collide across many faces on one page)", () => {
+ const svg = renderFaceSvg("Alice", PALETTE)
+ expect(svg).not.toContain("<mask")
+ expect(svg).not.toContain("url(#")
+ })
+
+ it("draws two eyes and a mouth inside the face group", () => {
+ // Every face renders a left+right eye and one mouth; the wrapper is a rect
+ // or path. Assert the face has drawable children beyond the bg rect.
+ const svg = renderFaceSvg("Diego", PALETTE)
+ const inner = svg.slice(svg.indexOf('rotate'))
+ expect(inner.length).toBeGreaterThan(0)
+ // at least one stroke/fill primitive from the eye/mouth libraries
+ expect(/<(circle|path|g)\b/.test(svg)).toBe(true)
+ })
+
+ it("varies across seeds — different ids generally produce different faces", () => {
+ const seeds = ["a", "b", "c", "d", "e", "f", "g", "h"]
+ const svgs = new Set(seeds.map((s) => renderFaceSvg(s, PALETTE)))
+ // Not all identical — the richer vocabulary means low collision.
+ expect(svgs.size).toBeGreaterThan(1)
+ })
+
+ it("only references colors from the given palette (plus contrast ink + white)", () => {
+ const svg = renderFaceSvg("Melisa#1043", PALETTE)
+ const hexes = svg.match(/#[0-9a-fA-F]{6}/g) ?? []
+ const allowed = new Set([...PALETTE, "#000000", "#ffffff"])
+ for (const h of hexes) expect(allowed.has(h)).toBe(true)
+ })
+
+ it("draws the face inside the shape's group so features sit on the wrapper (never vanish on bg)", () => {
+ // The "no eyes" bug: features were in a separate group that could land on
+ // the bg; ink (derived from wrapper) then matched the max-contrast bg and
+ // white eyes vanished on a light bg. Fix: face is nested in the shape group
+ // and shares its transform. Assert the SVG has exactly ONE transform group
+ // and the eye/mouth nodes are inside it (after the wrapper fill).
+ for (let n = 0; n < 60; n++) {
+ const svg = renderFaceSvg(`e-${n}`, PALETTE)
+ const groups = svg.match(/<g transform=/g) ?? []
+ expect(groups.length).toBe(1) // single shared shape+face group
+ // eyes/mouth (circle/path with the ink color) come AFTER the wrapper fill
+ const groupStart = svg.indexOf("<g transform")
+ const wrapperEnd = svg.indexOf("/>", groupStart) // first fill (wrapper)
+ const facePart = svg.slice(wrapperEnd)
+ expect(/(circle|path)/.test(facePart)).toBe(true)
+ }
+ })
+
+ it("keeps the tilt gentle (upright, human) — never a full spin", () => {
+ // Faces ride the shape rotation; a big spin flips them upside-down ("not a
+ // face anymore"). Rotation must stay within ±~12°.
+ for (let n = 0; n < 80; n++) {
+ const svg = renderFaceSvg(`r-${n}`, PALETTE)
+ const rot = parseFloat((svg.match(/rotate\((-?\d+(?:\.\d+)?)/) ?? ["", "0"])[1])
+ expect(Math.abs(rot)).toBeLessThanOrEqual(12)
+ }
+ })
+
+ it("keeps the shape translate small so the wrapper always covers the face", () => {
+ // Root cause of "shape doesn't cover the face / features clipped": the lib
+ // beam translated the shape up to ±9, moving its center off the canvas
+ // center so the wrapper stopped covering where features sit. Clamp: |tx|,
+ // |ty| ≤ ~2.6 → coverage radius (shape half-extent 12.2 − offset) > feature
+ // extent 9.5, so the face is always inside the wrapper.
+ for (let n = 0; n < 80; n++) {
+ const svg = renderFaceSvg(`t-${n}`, PALETTE)
+ const m = svg.match(/translate\((-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?)\)/)!
+ expect(Math.abs(parseFloat(m[1]))).toBeLessThanOrEqual(2.6)
+ expect(Math.abs(parseFloat(m[2]))).toBeLessThanOrEqual(2.6)
+ }
+ })
+
+ it("keeps eyes and mouth centered so they never leave the shape", () => {
+ // The x4-8 clipping Gus hit: the face had an independent offset that pushed
+ // features off the narrower blob shapes. Face now shares the shape's
+ // translate+scale (no independent offset), so features stay within ~9.5px of
+ // center — inside the narrowest shape (half-extent ≈12.2px). Assert every
+ // eye/mouth coordinate authored into the face group is within that radius of
+ // center (18,14 eye row / 18,~20 mouth), pre-transform (the shared transform
+ // preserves relative position).
+ for (let n = 0; n < 60; n++) {
+ const svg = renderFaceSvg(`s-${n}`, PALETTE)
+ // the face group is the LAST <g transform=...>; pull the coords inside it
+ const faceGroup = svg.slice(svg.lastIndexOf("<g transform"))
+ const coords = [...faceGroup.matchAll(/(?:cx|x)="?(-?\d+(?:\.\d+)?)"?\s+(?:cy|y)="?(-?\d+(?:\.\d+)?)"?/g)]
+ // fall back to any numeric pairs if attribute names differ across shapes
+ for (const m of coords) {
+ const x = parseFloat(m[1])
+ const y = parseFloat(m[2])
+ const d = Math.hypot(x - 18, y - 18)
+ expect(d).toBeLessThan(11)
+ }
+ }
+ })
+
+ it("keeps face wrapper and background readably apart on every palette (no low-contrast melt)", () => {
+ // The bug Gus hit: an all-light palette (idx 6) could pair a light wrapper
+ // with a near-light background, melting the face into the bg. bg is now the
+ // max-luminance-distance color, so the wrapper↔bg gap stays meaningful for
+ // every palette + seed. Guard the worst case across many seeds per palette.
+ const lum = (hex: string) => {
+ const h = hex.replace("#", "")
+ return (parseInt(h.slice(0, 2), 16) * 299 + parseInt(h.slice(2, 4), 16) * 587 + parseInt(h.slice(4, 6), 16) * 114) / 1000
+ }
+ const seeds = Array.from({ length: 40 }, (_, n) => `seed-${n}`)
+ // A single-hue palette genuinely can't separate — use the real 5-color set.
+ for (const seed of seeds) {
+ const svg = renderFaceSvg(seed, PALETTE)
+ // first two rects are bg then wrapper; pull their fills in document order
+ const fills = [...svg.matchAll(/fill="(#[0-9a-fA-F]{6})"/g)].map((m) => m[1])
+ const [bg, wrapper] = fills
+ expect(Math.abs(lum(bg) - lum(wrapper))).toBeGreaterThan(15)
+ }
+ })
+})
diff --git a/src/web/src/lib/avatar/face.ts b/src/web/src/lib/avatar/face.ts
new file mode 100644
index 000000000..0c6cc526e
--- /dev/null
+++ b/src/web/src/lib/avatar/face.ts
@@ -0,0 +1,193 @@
+// Generated "beam" face renderer — the richer replacement for boring-avatars'
+// fixed beam geometry. Ported from the approved design prototype
+// (Alli, avatar-features.mjs). Same 36-unit canvas, same wrapper transform +
+// PRNG, same auto-contrast ink as the lib's beam, so it reads as "more of the
+// same face", not a new style. Only the feature vocabulary grew:
+// 6 shapes (silhouette-distinct, not corner-radius) · 6 eyes · 6 mouths.
+// Each seed picks its shape/eye/mouth deterministically, so a given id always
+// renders the same face and never flickers across renames.
+//
+// `beam` only. Marble (server/channel icons, banner) stays on the lib.
+
+const C = 36
+const CX = 18
+const CY = 18
+const R = 17
+const TAU = Math.PI * 2
+const N = 72
+
+// boring-avatars PRNG helpers (verbatim from the lib bundle, so the wrapper
+// transform matches the lib's beam exactly).
+function hashSeed(name: string): number {
+ let r = 0
+ for (let i = 0; i < name.length; i++) {
+ r = (r << 5) - r + name.charCodeAt(i)
+ r = r & r
+ }
+ return Math.abs(r)
+}
+const digit = (n: number, p: number): number => Math.floor((n / Math.pow(10, p)) % 10)
+const unit = (n: number, m: number, p?: number): number => {
+ const a = n % m
+ return p && digit(n, p) % 2 === 0 ? -a : a
+}
+const pick = (n: number, arr: readonly string[], off = 0): string => arr[(n + off) % arr.length]
+
+// Perceived luminance (0–255), the same weighting the lib uses for faceColor.
+function luminance(hex: string): number {
+ const h = hex.replace("#", "")
+ const r = parseInt(h.substr(0, 2), 16)
+ const g = parseInt(h.substr(2, 2), 16)
+ const b = parseInt(h.substr(4, 2), 16)
+ return (r * 299 + g * 587 + b * 114) / 1000
+}
+
+// Contrasting ink color — same luminance rule the lib uses for faceColor.
+export function ink(hex: string): string {
+ return luminance(hex) >= 128 ? "#000000" : "#ffffff"
+}
+
+// Pick the palette color with the greatest luminance distance from `wrapper`,
+// for use as the background. The lib's beam uses a fixed offset (bg =
+// palette[(i+13)%len]) which can land wrapper + bg on two near-luminance
+// colors — a face that melts into its background (the low-contrast bug Gus
+// hit on the all-light idx-6 palette). Max-distance guarantees the face reads
+// against the bg for every seed/palette. Deterministic: pure function of
+// wrapper + palette, so faces stay stable and never flicker.
+function farthestByLuminance(wrapper: string, palette: readonly string[]): string {
+ const wl = luminance(wrapper)
+ let best = palette[0]
+ let bestDist = -1
+ for (const c of palette) {
+ const d = Math.abs(luminance(c) - wl)
+ if (d > bestDist) {
+ bestDist = d
+ best = c
+ }
+ }
+ return best
+}
+
+function polyPath(fn: (t: number) => [number, number]): string {
+ let d = ""
+ for (let i = 0; i <= N; i++) {
+ const t = (i / N) * TAU
+ const [x, y] = fn(t)
+ d += (i === 0 ? "M" : "L") + x.toFixed(2) + " " + y.toFixed(2) + " "
+ }
+ return d + "Z"
+}
+// Radial modulation r(t) = R * mod(t) — used for the lopsided/teardrop blobs.
+function radial(t: number, mod: (a: number) => number): [number, number] {
+ const r = R * mod(t)
+ return [CX + r * Math.cos(t), CY + r * Math.sin(t)]
+}
+
+// Wrapper shapes: soft, chunky, distinct by SILHOUETTE (proportion + gentle
+// asymmetry), not corner-radius — corner differences vanish at 32px under the
+// circular crop. No scallop/flower/zigzag (too busy, off the soft-simple
+// logic). `round`/`rounded` emit a plain rect (perf); the rest emit a <path>.
+type Shape = { rect: number } | { path: string }
+const SHAPES: Record<string, Shape> = {
+ round: { rect: C },
+ rounded: { rect: C / 3 },
+ wide: { path: polyPath((t) => [CX + R * 1.02 * Math.cos(t), CY + R * 0.72 * Math.sin(t)]) },
+ egg: { path: polyPath((t) => [CX + R * 0.86 * Math.cos(t), CY + R * Math.sin(t) - 2.4 * Math.sin(t) * Math.sin(t)]) },
+ potato: { path: polyPath((t) => radial(t, (a) => 0.95 * (1 + 0.11 * Math.sin(a + 0.5) + 0.06 * Math.cos(2 * a - 0.8)))) },
+ drop: { path: polyPath((t) => radial(t, (a) => 0.94 * (1 + 0.14 * Math.cos(a - Math.PI / 2)))) },
+}
+const SHAPE_KEYS = Object.keys(SHAPES)
+
+// Eyes — big, chunky, bold strokes (ESW). Baseline is beam's dot, enlarged.
+const ESW = 1.6
+type EyeFn = (x: number, y: number, c: string, right?: boolean) => string
+const EYES: Record<string, EyeFn> = {
+ dot: (x, y, c) => `<circle cx="${x}" cy="${y}" r="1.6" fill="${c}"/>`,
+ round: (x, y, c) => `<circle cx="${x}" cy="${y}" r="1.9" fill="${c}"/>`,
+ wide: (x, y, c) => `<g><circle cx="${x}" cy="${y}" r="2.1" fill="#fff"/><circle cx="${x}" cy="${y + 0.3}" r="1.15" fill="${c}"/></g>`,
+ sleepy: (x, y, c) => `<path d="M${x - 1.8} ${y} q1.8 1.7 3.6 0" stroke="${c}" stroke-width="${ESW}" fill="none" stroke-linecap="round"/>`,
+ wink: (x, y, c, right) => right
+ ? `<path d="M${x - 1.8} ${y} q1.8 1.7 3.6 0" stroke="${c}" stroke-width="${ESW}" fill="none" stroke-linecap="round"/>`
+ : `<circle cx="${x}" cy="${y}" r="1.9" fill="${c}"/>`,
+ happy: (x, y, c) => `<path d="M${x - 1.8} ${y + 0.7} q1.8 -2 3.6 0" stroke="${c}" stroke-width="${ESW}" fill="none" stroke-linecap="round"/>`,
+}
+const EYE_KEYS = Object.keys(EYES)
+
+// Mouths — simple, thick-lined, chunky (MSW), matched to the fat eyes.
+const MSW = 1.5
+type MouthFn = (spread: number, c: string) => string
+const MOUTHS: Record<string, MouthFn> = {
+ smile: (s, c) => `<path d="M14.5 ${19 + s}q3.5 2.6 7 0" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
+ arc: (s, c) => `<path d="M13.5 ${19 + s} a1,0.85 0 0,0 9,0" fill="${c}"/>`,
+ flat: (s, c) => `<path d="M15 ${19.5 + s}h6" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
+ open: (s, c) => `<circle cx="18" cy="${20 + s}" r="2.3" fill="${c}"/>`,
+ grin: (s, c) => `<path d="M13.5 ${18.6 + s}q4.5 3.4 9 0" stroke="${c}" stroke-width="1.8" fill="none" stroke-linecap="round"/>`,
+ cat: (s, c) => `<path d="M14 ${19 + s}q2 1.8 4 0 q2 1.8 4 0" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
+}
+const MOUTH_KEYS = Object.keys(MOUTHS)
+
+// Render a generated beam face to an SVG string for the given seed + palette.
+// The wrapper transform mirrors the lib's beam so faces sit identically inside
+// the container crop; feature choice is deterministic on the seed hash.
+export function renderFaceSvg(seed: string, palette: readonly string[]): string {
+ const i = hashSeed(seed)
+ const wrapper = pick(i, palette)
+ const bg = farthestByLuminance(wrapper, palette)
+ const c = ink(wrapper)
+
+ // Small translate only (±2.6px). The lib beam translated up to ±9, which
+ // moved the shape's center so far off the canvas center that the wrapper
+ // (radius ≈17) stopped covering where the features sit (≈9.5px from center) —
+ // features fell outside the shape / got clipped by the circular crop (Gus's
+ // "shape doesn't cover the face" / z51). Guarantee coverage: narrowest shape
+ // half-extent ≈12.2 (×scale ≥1) minus feature extent 9.5 ≈ 2.7 of slack, so a
+ // ≤2.6 offset keeps the whole face inside the wrapper for every shape.
+ const tx = ((i % 27) / 26 - 0.5) * 5.2
+ const ty = (((digit(i, 2) + digit(i, 5)) % 11) / 10 - 0.5) * 5.2
+ // Gentle tilt only (±~12°), not the lib beam's full 0–359° spin. The face
+ // rides this rotation (shared transform, below), so a big spin would flip the
+ // whole face upside-down — "not even a face anymore". A small tilt keeps every
+ // avatar upright and human while still varying per seed.
+ const rot = (i % 25) - 12
+ const scale = 1 + unit(i, Math.round(C / 12)) / 10
+
+ // Eye spread 0–2 (eyes land at x 12/24 .. 14/22, i.e. ≤6px from center) and
+ // the eye row nudged to y=15 (nearer the shape's widest band at center 18).
+ // The old 0–4 spread pushed eyes to x 10/24 (±8) — out where the narrower/
+ // taller shapes (egg, wide oval, potato) have already tapered, so an eye
+ // poked past the edge (z51). Keeping the eye row narrow + centered keeps both
+ // eyes on the wrapper for every shape.
+ const eyeSpread = i % 3
+ const mouthSpread = i % 2
+
+ const shape = SHAPES[SHAPE_KEYS[i % SHAPE_KEYS.length]]
+ const eyeFn = EYES[EYE_KEYS[digit(i, 4) % EYE_KEYS.length]]
+ const mouthFn = MOUTHS[MOUTH_KEYS[digit(i, 5) % MOUTH_KEYS.length]]
+
+ const wrapperEl = "path" in shape
+ ? `<path d="${shape.path}" fill="${wrapper}"/>`
+ : `<rect width="${C}" height="${C}" rx="${shape.rect}" fill="${wrapper}"/>`
+
+ const leftEye = eyeFn(14 - eyeSpread, 15, c, false)
+ const rightEye = eyeFn(20 + eyeSpread, 15, c, true)
+ const mouth = mouthFn(mouthSpread, c)
+
+ // The face is nested inside the shape's transform group and shares its EXACT
+ // transform, so features always sit on the wrapper fill, centered on it —
+ // never drifting onto the background or off toward an edge. This fixes two
+ // bugs at once: (a) "no eyes" — ink is derived from `wrapper`, so a feature
+ // that landed on `bg` (now the max-contrast-vs-wrapper color) could match the
+ // bg and vanish; keeping features on the wrapper guarantees ink contrast; and
+ // (b) "features too far off-center" — the old independent face offset (fx/fy,
+ // a lib-beam relic whose wrapper filled the whole 36×36 square) let eyes/mouth
+ // wander. Shape and face both rotate about center (18,18) and share the same
+ // translate, so the face center coincides with the shape center at any rot.
+ // The face rides the shape's rotation (a small tilt, like the lib's own beam).
+ const faceXf = `translate(${tx} ${ty}) rotate(${rot} 18 18) scale(${scale})`
+
+ // No <mask> — a full-canvas white mask is a no-op clip, and a shared mask id
+ // would collide across the many faces on one page (member lists, message
+ // streams). The 36×36 viewBox + the caller's `overflow-hidden` crop already
+ // bound the drawing; anything outside the box is clipped by the container.
+ return `<svg viewBox="0 0 ${C} ${C}" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"><rect width="${C}" height="${C}" fill="${bg}"/><g transform="${faceXf}">${wrapperEl}${leftEye}${rightEye}${mouth}</g></svg>`
+}