Open-source Grok Bot alternative with a virtual machine that bots can use
Mascot Shape Catalog Implementation Plan
Naming note (2026-09-01): the code vocabulary for this feature is
body, notshape—mascotBody,MASCOT_BODIES,MascotBodyId,shared/mascot-bodies.ts,scripts/mascot-bodies/,MausBodies.swift. The repo enforcesanti-slop/no-shape-in-symbol-namesas an error, andbodyis the word this document already uses in prose. Identifiers written asmascotShapeetc. below are the original design text and are stale; the ids themselves (cursor,blob, …) are unchanged.
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Give every bot a choice of ten body shapes — plus a mode where its own uploaded image becomes the body with the live face still on top — rendered identically on desktop and iOS.
Architecture: A Node generator solves each shape's face placement once (signed distance field + the existing fit solver) and emits two checked-in catalogs, one TypeScript and one Swift. Both renderers already accept a pluggable silhouette and an anchored face, so they become lookups over that catalog rather than hardcoded single shapes. The image body reuses the clipPath the renderer already builds for the face.
Tech Stack: TypeScript, React, Node 22 (--experimental-strip-types), Vitest, Zod 4, SwiftUI (Canvas), pnpm.
Spec: docs/superpowers/specs/2026-08-31-mascot-shape-catalog-design.md
Global Constraints
- Branch:
feat/mascot-shape-catalog. Do not push; do not open a PR. - Repo root:
/Users/omkar/Desktop/openmaus/OpenGrokBot. Desktop and iOS are the same repo (ios/is a subdirectory). - No new dependencies. The generator is plain Node plus what already ships.
- Face box is
228.541units. Face centre is[120, 122.5]. These are existing constants — never redefine them, import them. - Generated paths use absolute
M,C,Zonly. The iOS parser inMausSilhouette.parse()understands nothing else. - Generated files carry a
// Generated by scripts/gen-mascot-shapes.ts — do not hand-edit.header, matching the existing convention inios/App/MausFaceData.swift. - Shape ids are persisted values and must never change:
cursor,blob,circle,squircle,capsule,drop,shield,hexagon,diamond,star. cursoris the default everywhere. Any absent or unrecognised shape id resolves tocursor.- Tests run under Vitest with
environment: "node"— there is no jsdom and no @testing-library. React components are tested withrenderToStaticMarkupfromreact-dom/server, followingsrc/components/RenameTitle.test.ts. - Vitest only collects these globs:
server/**/*.test.ts,electron/**/*.test.mjs,src/**/*.test.ts,companion/**/*.test.ts,scripts/**/*.test.mjs. A test file outside them will silently never run. - Run a single test file with
pnpm exec vitest run <path>. - Typecheck with
pnpm typecheck. Lint withpnpm lint. - Commit after every task.
File Structure
Created:
| File | Responsibility |
|---|---|
src/components/cursor-face-data.ts |
The face tables (expressions, gaze, mouths, constants), extracted so plain Node can import them without parsing JSX |
scripts/mascot-shapes/builders.ts |
The ten outlines, as absolute-cubic path data |
scripts/mascot-shapes/geometry.ts |
Cubic flattening, bounds, the fit transform |
scripts/mascot-shapes/raster.ts |
Polyline → binary mask (replaces the studio's canvas rasteriser) |
scripts/mascot-shapes/sdf.ts |
Distance field + inscribed circle (copied verbatim from Blob Studio) |
scripts/mascot-shapes/solve.ts |
Expression point clouds + solveFit (copied verbatim from Blob Studio) |
scripts/gen-mascot-shapes.ts |
Entry point: solve, clamp, assert, emit both catalogs |
shared/mascot-shapes.ts |
Generated. TS catalog, id union, Zod schema, botMascotShape() |
ios/App/MausShapes.swift |
Generated. Swift catalog keyed by the same ids |
Modified:
| File | Change |
|---|---|
src/components/CursorAvatar.tsx |
Re-export face data from the new module; add bodyImage to CursorSilhouette and render it |
src/components/Avatar.tsx |
Shape lookup replaces the inline GRADIENT_SILHOUETTE; new shape and bodyImage props |
src/components/BotProfileAvatarCard.tsx |
Shape picker row; face crop; upload defaults to face |
shared/bot-avatar.ts |
Add face to BOT_AVATAR_CROPS |
server/store.ts, server/bot-profile.ts, server/team-manifest.ts, server/bot-package.ts, server/package-export.ts, server/index.ts |
Carry mascotShape alongside color / mascotExpression |
ios/Sources/CompanionCore/Models.swift |
Bot.mascotShape, BotProfilePatch.mascotShape |
ios/App/MausAvatar.swift |
Per-shape silhouette lookup; shape and image-body parameters |
ios/App/BotAvatarView.swift |
Three-way branch: flat image / image body / gradient body |
package.json |
gen:shapes script |
Task 1: Extract the face data tables
The generator needs EXPRESSIONS, GAZE, MOUTHS and the face constants. They currently live in src/components/CursorAvatar.tsx, which is JSX — node --experimental-strip-types cannot load it. Moving the pure data into a .ts module makes it importable from a plain Node script, and mirrors how iOS already separates MausFaceData.swift from MausAvatar.swift.
This is a pure move. No behaviour changes.
Files:
- Create:
src/components/cursor-face-data.ts - Modify:
src/components/CursorAvatar.tsx - Test:
src/components/cursor-face-data.test.ts
Interfaces:
Consumes: nothing.
Produces:
export type Ring = [number, number][] export const FACE_BOX = 228.541 export const FACE_CENTRE: [number, number] // [120, 122.5] export const GAZE_TRAVEL: { x: number; y: number } // { x: 13.2, y: 8.4 } export const MOUTH_STROKE = 7.5 export const GAZE: [number, number][] export const EXPRESSIONS: Ring[][] export const EXPRESSION_COUNT: number export const MOUTHS: number[][] export function mouthFrame(rings: Ring[], spec: number[]): { x: number; y: number; angle: number }Step 1: Write the failing test
Create src/components/cursor-face-data.test.ts:
import { describe, expect, it } from "vitest";
import {
EXPRESSIONS,
EXPRESSION_COUNT,
FACE_BOX,
FACE_CENTRE,
GAZE,
GAZE_TRAVEL,
MOUTHS,
MOUTH_STROKE,
mouthFrame,
} from "./cursor-face-data";
describe("cursor face data", () => {
it("carries one entry per expression in every table", () => {
expect(EXPRESSION_COUNT).toBe(25);
expect(EXPRESSIONS).toHaveLength(25);
expect(GAZE).toHaveLength(25);
expect(MOUTHS).toHaveLength(25);
});
it("gives every expression two eye rings of 48 points", () => {
for (const expression of EXPRESSIONS) {
expect(expression).toHaveLength(2);
for (const ring of expression) expect(ring).toHaveLength(48);
}
});
it("keeps the face-space constants the renderer and the phone agree on", () => {
expect(FACE_BOX).toBe(228.541);
expect(FACE_CENTRE).toEqual([120, 122.5]);
expect(GAZE_TRAVEL).toEqual({ x: 13.2, y: 8.4 });
expect(MOUTH_STROKE).toBe(7.5);
});
it("hangs the mouth below the eye pair", () => {
const frame = mouthFrame(EXPRESSIONS[0], MOUTHS[0]);
expect(Number.isFinite(frame.x)).toBe(true);
expect(Number.isFinite(frame.y)).toBe(true);
expect(Number.isFinite(frame.angle)).toBe(true);
});
});
- Step 2: Run it and watch it fail
pnpm exec vitest run src/components/cursor-face-data.test.ts
Expected: FAIL — cannot resolve ./cursor-face-data.
- Step 3: Move the data
Create src/components/cursor-face-data.ts. Move these out of CursorAvatar.tsx verbatim, changing nothing but their location:
export type Ringconst ENCODED: string[](the 25-line expression table)const RAW: Ring[][]const ringCentreexport const GAZEexport const EXPRESSIONSexport const EXPRESSION_COUNTexport const MOUTHSexport const MOUTH_STROKEexport const FACE_BOXexport const FACE_CENTREexport function mouthFrame
ringCentre is used by mouthFrame, so it moves too and stays module-private.
Add one new export, replacing the two loose constants at CursorAvatar.tsx:54-55:
/** How far pointer gaze may pull the eyes, in face-space units. */
export const GAZE_TRAVEL = { x: 13.2, y: 8.4 }
Give the file this header:
/**
* The mascot's face tables — 25 expressions x 2 eye rings x 48 points, a mouth
* per expression, and the face-space constants every coordinate is expressed in.
*
* Split out of CursorAvatar.tsx so `scripts/gen-mascot-shapes.ts` can import it
* from plain Node: the renderer is JSX and `--experimental-strip-types` cannot
* load it, but the generator needs exactly these numbers to solve where a face
* fits inside a new silhouette. The phone already draws this line in the same
* place (MausFaceData.swift vs MausAvatar.swift).
*/
- Step 4: Re-wire
CursorAvatar.tsx
Replace the removed block with an import, and re-export so every existing consumer keeps working unchanged (src/lib/mascot.ts and src/mascot-preview.tsx both import from ./CursorAvatar):
import {
EXPRESSIONS,
EXPRESSION_COUNT,
FACE_BOX,
FACE_CENTRE,
GAZE,
GAZE_TRAVEL,
MOUTHS,
MOUTH_STROKE,
mouthFrame,
type Ring,
} from "./cursor-face-data"
export {
EXPRESSIONS,
EXPRESSION_COUNT,
FACE_BOX,
FACE_CENTRE,
GAZE,
GAZE_TRAVEL,
MOUTHS,
MOUTH_STROKE,
mouthFrame,
}
export type { Ring }
Then replace the two uses of the old loose constants:
const gx = clamp(p.gaze?.x ?? 0, -1, 1) * GAZE_TRAVEL.x
const gy = clamp(p.gaze?.y ?? 0, -1, 1) * GAZE_TRAVEL.y
SPHERE_C, SPHERE_R, mouthPath and anchorTransform stay in CursorAvatar.tsx — they are rendering concerns, not data.
- Step 5: Verify nothing moved
pnpm exec vitest run src/components/cursor-face-data.test.ts
pnpm typecheck
pnpm lint
Expected: PASS, clean typecheck, clean lint. If pnpm typecheck reports an unused import in CursorAvatar.tsx, delete it — do not suppress it.
- Step 6: Commit
git add src/components/cursor-face-data.ts src/components/cursor-face-data.test.ts src/components/CursorAvatar.tsx
git commit -m "refactor: split the mascot face tables out of the renderer
The generator needs these numbers and cannot load JSX. Same split the
phone already makes between MausFaceData and MausAvatar."
Task 2: The ten outlines
Files:
- Create:
scripts/mascot-shapes/builders.ts - Test:
scripts/mascot-shapes/builders.test.mjs
Interfaces:
- Consumes: nothing.
- Produces:
export interface ShapeDef { id: string; name: string; d: string; viewBox: [number, number, number, number] } export const SHAPE_DEFS: ShapeDef[] // ten entries, `cursor` first export const SHAPE_IDS: string[]dis absolute-cubic path data.viewBoxis[minX, minY, width, height]of the coordinate spacedis drawn in.
Builders are adapted from Blob Studio's studio/src/shapes/builtin.ts, with every Q, A, L, H and V command converted to C. Read that file for the parameter values; the conversion is this task's actual work.
- Step 1: Write the failing test
Create scripts/mascot-shapes/builders.test.mjs:
import { describe, expect, it } from "vitest";
import { SHAPE_DEFS, SHAPE_IDS } from "./builders.ts";
const EXPECTED_IDS = [
"cursor", "blob", "circle", "squircle", "capsule",
"drop", "shield", "hexagon", "diamond", "star",
];
describe("shape builders", () => {
it("produces the catalog in its persisted order, cursor first", () => {
expect(SHAPE_IDS).toEqual(EXPECTED_IDS);
});
it("emits only absolute M, C and Z, which is all the iOS parser understands", () => {
for (const shape of SHAPE_DEFS) {
const commands = shape.d.match(/[A-Za-z]/g) ?? [];
const unique = [...new Set(commands)].sort();
expect(unique, `${shape.id} uses unsupported commands`).toEqual(["C", "M", "Z"]);
}
});
it("starts every outline with a move and closes it", () => {
for (const shape of SHAPE_DEFS) {
expect(shape.d.trimStart().startsWith("M"), shape.id).toBe(true);
expect(shape.d.trimEnd().endsWith("Z"), shape.id).toBe(true);
}
});
it("gives every curve six numbers", () => {
for (const shape of SHAPE_DEFS) {
for (const segment of shape.d.split("C").slice(1)) {
const numbers = segment.match(/-?\d+(?:\.\d+)?(?:e-?\d+)?/g) ?? [];
expect(numbers.length % 6, `${shape.id} has a ragged curve`).toBe(0);
}
}
});
it("keeps the cursor outline byte-identical to the shipped artwork", () => {
const cursor = SHAPE_DEFS.find(s => s.id === "cursor");
expect(cursor.d.startsWith("M0 0 C1.12815992 0.94880479")).toBe(true);
expect(cursor.d.trimEnd().endsWith("-21.34867451 -18.24899383 0 0 Z")).toBe(true);
});
});
- Step 2: Run it and watch it fail
pnpm exec vitest run scripts/mascot-shapes/builders.test.mjs
Expected: FAIL — cannot resolve ./builders.ts.
- Step 3: Write the builders
Create scripts/mascot-shapes/builders.ts. Structure:
/**
* The ten catalog outlines, as absolute cubic path data.
*
* Adapted from Blob Studio's studio/src/shapes/builtin.ts at fixed parameters.
* Cubics only, because the phone's twenty-line path parser understands `M`, `C`
* and `Z` and nothing else — emitting anything richer here would mean growing a
* parser on the platform least able to afford it.
*/
/** Quadratic control point to its exact cubic pair. */
function quadToCubic(
x0: number, y0: number, cx: number, cy: number, x1: number, y1: number
): [number, number, number, number, number, number] {
return [
x0 + (2 / 3) * (cx - x0), y0 + (2 / 3) * (cy - y0),
x1 + (2 / 3) * (cx - x1), y1 + (2 / 3) * (cy - y1),
x1, y1,
]
}
/** A straight run as a degenerate cubic, so the emitted path stays cubics-only. */
function lineToCubic(
x0: number, y0: number, x1: number, y1: number
): [number, number, number, number, number, number] {
return [x0 + (x1 - x0) / 3, y0 + (y1 - y0) / 3, x0 + (2 * (x1 - x0)) / 3, y0 + (2 * (y1 - y0)) / 3, x1, y1]
}
/** Circular-arc magic number: four cubics approximate a circle to ~0.02%. */
const KAPPA = 0.5522847498307936
Then a small path builder that accumulates M/C/Z and rounds coordinates to 5 decimals, and the ten definitions:
cursor— the literal artwork string. Copy it out ofDEFAULT_SILHOUETTE.bodyinsrc/components/CursorAvatar.tsx(thedattribute only, without thetransform), and setviewBoxto[0, 0, 512, 512]with a note that the artwork is drawn pre-translate. Do not regenerate it — the test asserts it byte-for-byte.circle— fourKAPPAarcs, 200x200.capsule— 150x200, ends fully round: two straight sides aslineToCubic, two semicircular caps as twoKAPPAarcs each.squircle— 200x200, corner radiusmin(w,h)/2 * 0.5: four straight edges plus fourKAPPA-scaled corner arcs.blob— the studio's wobble builder atwobble: 0.35, 200x200. It already emits quadratics through midpoints; run each throughquadToCubic.drop— the studio's builder atbelly: 0.62, 156x194. ItsCsegments carry over unchanged; its oneA(a semicircle of radiushw) becomes twoKAPPAarcs.shield— the studio'sconeattip: 0.45, base: 0.9, 190x200. Quadratics viaquadToCubic, lines vialineToCubic.hexagon— the studio's polygon atsides: 6, round: 0.12, 196x196.diamond— the same polygon builder atsides: 4, round: 0.12, 196x196.star— the studio's star atpoints: 5, inner: 0.42, 196x196. It emits only lines, so every edge becomes alineToCubic.
Export SHAPE_DEFS in the order listed in the test, and SHAPE_IDS derived from it.
- Step 4: Run the tests
pnpm exec vitest run scripts/mascot-shapes/builders.test.mjs
Expected: PASS, all five cases.
- Step 5: Commit
git add scripts/mascot-shapes/builders.ts scripts/mascot-shapes/builders.test.mjs
git commit -m "feat: the ten mascot outlines as absolute cubics"
Task 3: Flattening, bounds and the fit transform
Files:
- Create:
scripts/mascot-shapes/geometry.ts - Test:
scripts/mascot-shapes/geometry.test.mjs
Interfaces:
- Consumes: nothing.
- Produces:
export interface Bounds { minX: number; minY: number; maxX: number; maxY: number } export function flatten(d: string, tolerance?: number): [number, number][][] export function boundsOf(polylines: [number, number][][]): Bounds export function fitTransform(bounds: Bounds): { transform: string; scale: number; tx: number; ty: number } export function applyFit(polylines: [number, number][][], fit: { scale: number; tx: number; ty: number }): [number, number][][]
fitTransform reproduces the mapping in Blob Studio's measureFit: scale the drawn bounds to fill the face box on its tighter axis, then centre it. The emitted string is translate(<tx> <ty>) scale(<scale>), matching the shipped DEFAULT_SILHOUETTE.fit format so the renderer needs no change.
- Step 1: Write the failing test
Create scripts/mascot-shapes/geometry.test.mjs:
import { describe, expect, it } from "vitest";
import { applyFit, boundsOf, fitTransform, flatten } from "./geometry.ts";
const FACE_BOX = 228.541;
/** A 100x100 box at the origin, as four degenerate cubics. */
const BOX =
"M0 0 C33.33 0 66.67 0 100 0 C100 33.33 100 66.67 100 100 " +
"C66.67 100 33.33 100 0 100 C0 66.67 0 33.33 0 0 Z";
describe("flatten", () => {
it("walks a closed path into one polyline", () => {
const polylines = flatten(BOX);
expect(polylines).toHaveLength(1);
expect(polylines[0].length).toBeGreaterThan(4);
});
it("keeps every sampled point on the box it came from", () => {
for (const [x, y] of flatten(BOX)[0]) {
const onEdge =
Math.abs(x) < 0.01 || Math.abs(x - 100) < 0.01 ||
Math.abs(y) < 0.01 || Math.abs(y - 100) < 0.01;
expect(onEdge, `(${x}, ${y}) left the box`).toBe(true);
}
});
});
describe("boundsOf", () => {
it("measures the drawn extent", () => {
expect(boundsOf(flatten(BOX))).toEqual({
minX: expect.closeTo(0, 2),
minY: expect.closeTo(0, 2),
maxX: expect.closeTo(100, 2),
maxY: expect.closeTo(100, 2),
});
});
});
describe("fitTransform", () => {
it("scales a square to fill the face box", () => {
const fit = fitTransform({ minX: 0, minY: 0, maxX: 100, maxY: 100 });
expect(fit.scale).toBeCloseTo(FACE_BOX / 100, 5);
});
it("centres the narrow axis of a tall shape", () => {
const fit = fitTransform({ minX: 0, minY: 0, maxX: 50, maxY: 100 });
expect(fit.scale).toBeCloseTo(FACE_BOX / 100, 5);
// 50 wide at that scale leaves half the box spare, split evenly.
expect(fit.tx).toBeCloseTo(FACE_BOX / 4, 3);
expect(fit.ty).toBeCloseTo(0, 3);
});
it("emits the transform in the format the renderer already parses", () => {
const fit = fitTransform({ minX: 0, minY: 0, maxX: 100, maxY: 100 });
expect(fit.transform).toMatch(/^translate\(-?[\d.]+ -?[\d.]+\) scale\([\d.]+\)$/);
});
});
describe("applyFit", () => {
it("lands the shape inside the face box", () => {
const fit = fitTransform({ minX: 0, minY: 0, maxX: 100, maxY: 100 });
const bounds = boundsOf(applyFit(flatten(BOX), fit));
expect(bounds.minX).toBeGreaterThanOrEqual(-0.01);
expect(bounds.minY).toBeGreaterThanOrEqual(-0.01);
expect(bounds.maxX).toBeLessThanOrEqual(FACE_BOX + 0.01);
expect(bounds.maxY).toBeLessThanOrEqual(FACE_BOX + 0.01);
});
});
- Step 2: Run it and watch it fail
pnpm exec vitest run scripts/mascot-shapes/geometry.test.mjs
Expected: FAIL — cannot resolve ./geometry.ts.
- Step 3: Implement
Create scripts/mascot-shapes/geometry.ts:
flatten— tokenise the path (a number scanner handling-andeexactly like the iOS parser does), walkM/C/Z, and subdivide each cubic adaptively until the chord deviates from the curve by less thantolerance(default0.05artwork units). Return one polyline per subpath.boundsOf— min/max over all points.fitTransform—scale = FACE_BOX / max(width, height), thentx = -minX * scale + (FACE_BOX - width * scale) / 2and the same forty. Roundscaleto 6 decimals and the translations to 4, then build the string. Return the rounded numbers soapplyFituses exactly what gets emitted.applyFit—[x * scale + tx, y * scale + ty].
Import FACE_BOX from ../../src/components/cursor-face-data.ts rather than redefining it.
- Step 4: Run the tests
pnpm exec vitest run scripts/mascot-shapes/geometry.test.mjs
Expected: PASS.
- Step 5: Commit
git add scripts/mascot-shapes/geometry.ts scripts/mascot-shapes/geometry.test.mjs
git commit -m "feat: flatten cubics and fit an outline into the face box"
Task 4: Rasterise a polyline into a mask
This replaces Blob Studio's rasterise, which draws through an <img> and a canvas. We know the outline analytically, so a scanline fill is both sufficient and dependency-free.
Files:
- Create:
scripts/mascot-shapes/raster.ts - Test:
scripts/mascot-shapes/raster.test.mjs
Interfaces:
- Consumes:
flatten,boundsOf,fitTransform,applyFitfrom Task 3. - Produces:
Returnsexport function maskFromPolylines(polylines: [number, number][][], size?: number): Uint8Arraysize * sizebytes,1inside. Coordinates are face-space;sizedefaults to256.
Use the non-zero winding rule, matching how SVG fills by default.
- Step 1: Write the failing test
Create scripts/mascot-shapes/raster.test.mjs:
import { describe, expect, it } from "vitest";
import { maskFromPolylines } from "./raster.ts";
const FACE_BOX = 228.541;
const SIZE = 256;
/** A circle of radius r centred in the face box, as a dense polygon. */
const circle = (r, steps = 512) => {
const c = FACE_BOX / 2;
const points = [];
for (let i = 0; i < steps; i++) {
const a = (i / steps) * Math.PI * 2;
points.push([c + Math.cos(a) * r, c + Math.sin(a) * r]);
}
return [points];
};
const at = (mask, x, y) => {
const px = Math.floor((x / FACE_BOX) * SIZE);
const py = Math.floor((y / FACE_BOX) * SIZE);
return mask[py * SIZE + px];
};
describe("maskFromPolylines", () => {
it("fills the inside and leaves the outside clear", () => {
const mask = maskFromPolylines(circle(80));
expect(at(mask, FACE_BOX / 2, FACE_BOX / 2)).toBe(1);
expect(at(mask, 4, 4)).toBe(0);
});
it("covers the area the circle actually has", () => {
const r = 80;
const mask = maskFromPolylines(circle(r));
let filled = 0;
for (const value of mask) filled += value;
const perPixel = (FACE_BOX / SIZE) ** 2;
expect(filled * perPixel).toBeCloseTo(Math.PI * r * r, -2);
});
it("puts the edge where the radius says it is", () => {
const mask = maskFromPolylines(circle(60));
const c = FACE_BOX / 2;
expect(at(mask, c + 55, c)).toBe(1);
expect(at(mask, c + 65, c)).toBe(0);
});
it("clips shapes that run past the face box instead of wrapping them", () => {
const mask = maskFromPolylines([[[-50, -50], [50, -50], [50, 50], [-50, 50]]]);
expect(at(mask, 4, 4)).toBe(1);
expect(at(mask, FACE_BOX - 4, FACE_BOX - 4)).toBe(0);
});
});
- Step 2: Run it and watch it fail
pnpm exec vitest run scripts/mascot-shapes/raster.test.mjs
Expected: FAIL — cannot resolve ./raster.ts.
- Step 3: Implement
Create scripts/mascot-shapes/raster.ts. For each scanline y, sample at the pixel centre (py + 0.5) * unitsPerPixel; collect every edge crossing with its winding direction (+1 downward, -1 upward); sort by x; walk left to right accumulating winding, and fill spans where the running total is non-zero. Clamp span ends to [0, size) so out-of-box geometry clips rather than wraps.
- Step 4: Run the tests
pnpm exec vitest run scripts/mascot-shapes/raster.test.mjs
Expected: PASS, all four cases.
- Step 5: Commit
git add scripts/mascot-shapes/raster.ts scripts/mascot-shapes/raster.test.mjs
git commit -m "feat: scanline rasteriser, so the solver needs no canvas"
Task 5: Port the distance field and the fit solver
Both are copied from Blob Studio essentially verbatim — they are pure math and already carry their own tests there. The only edits are import paths and dropping the DOM-dependent buildSdf.
Files:
- Create:
scripts/mascot-shapes/sdf.ts - Create:
scripts/mascot-shapes/solve.ts - Test:
scripts/mascot-shapes/solve.test.mjs
Interfaces:
- Consumes:
maskFromPolylines(Task 4); the face tables (Task 1). - Produces:
// sdf.ts export interface Sdf { size: number; data: Float32Array; unitsPerPixel: number } export function fieldFromMask(mask: Uint8Array, size: number): Sdf export function sampleSdf(sdf: Sdf, x: number, y: number): number export function largestInscribedCircle(sdf: Sdf): { x: number; y: number; radius: number } // solve.ts export interface FitResult { anchor: { x: number; y: number; scale: number }; clipping: number[]; clearance: number } export function buildClouds(lookAround: number, mouthStroke?: number, aim?: { x: number; y: number }): Cloud[] export function solveFit(sdf: Sdf, lookAround: number, mouthStroke?: number, aim?: { x: number; y: number }): FitResult export function report(clouds: Cloud[], sdf: Sdf, anchor: { x: number; y: number; scale: number }): { clipping: number[]; clearance: number } export function maxScaleAt(clouds: Cloud[], sdf: Sdf, ax: number, ay: number, cap: number): number
Copy sdf.ts from studio/src/fit/sdf.ts, keeping fieldFromMask, edt, edt1d, sampleSdf and largestInscribedCircle. Drop buildSdf, rasterise, loadImage and RasterError — those are the canvas path Task 4 replaced.
Copy solve.ts from studio/src/fit/solve.ts, keeping buildClouds, clearanceOf, worstAcross, maxScaleAt, solveFit and report. Two changes:
- Import from
../../src/components/cursor-face-data.tsinstead of the studio's engine. - Drop the
lifeparameter and theSACCADE_RADIUSpadding. The studio's engine jitters the eyes with micro-saccades; this app'sCursorAvatardoes not (there is nosaccadeanywhere in it). Charging every face for clearance nothing uses would shrink all ten shapes for no reason. ReplaceGAZE_TRAVELusage with the export from Task 1.
- Step 1: Write the failing test
Create scripts/mascot-shapes/solve.test.mjs:
import { describe, expect, it } from "vitest";
import { maskFromPolylines } from "./raster.ts";
import { fieldFromMask, largestInscribedCircle, sampleSdf } from "./sdf.ts";
import { buildClouds, report, solveFit } from "./solve.ts";
const FACE_BOX = 228.541;
const SIZE = 256;
const circle = (r, steps = 512) => {
const c = FACE_BOX / 2;
const points = [];
for (let i = 0; i < steps; i++) {
const a = (i / steps) * Math.PI * 2;
points.push([c + Math.cos(a) * r, c + Math.sin(a) * r]);
}
return [points];
};
const fieldFor = (r) => fieldFromMask(maskFromPolylines(circle(r), SIZE), SIZE);
describe("sdf", () => {
it("is positive inside, negative outside, and zero on the edge", () => {
const sdf = fieldFor(80);
const c = FACE_BOX / 2;
expect(sampleSdf(sdf, c, c)).toBeGreaterThan(70);
expect(sampleSdf(sdf, c + 100, c)).toBeLessThan(0);
expect(Math.abs(sampleSdf(sdf, c + 80, c))).toBeLessThan(3);
});
it("finds the centre of a circle as its largest inscribed circle", () => {
const found = largestInscribedCircle(fieldFor(80));
expect(found.x).toBeCloseTo(FACE_BOX / 2, 0);
expect(found.y).toBeCloseTo(FACE_BOX / 2, 0);
expect(found.radius).toBeCloseTo(80, 0);
});
});
describe("solveFit", () => {
it("fits a full-size face in a roomy circle", () => {
const fit = solveFit(fieldFor(100), 0);
expect(fit.clipping).toEqual([]);
expect(fit.anchor.scale).toBeGreaterThan(0.8);
});
it("shrinks the face rather than clipping it in a tight circle", () => {
const roomy = solveFit(fieldFor(100), 0);
const tight = solveFit(fieldFor(55), 0);
expect(tight.clipping).toEqual([]);
expect(tight.anchor.scale).toBeLessThan(roomy.anchor.scale);
});
it("never exceeds the scale the expressions were drawn for", () => {
expect(solveFit(fieldFor(110), 0).anchor.scale).toBeLessThanOrEqual(1);
});
it("agrees with report at the anchor it returned", () => {
const sdf = fieldFor(90);
const fit = solveFit(sdf, 0);
expect(report(buildClouds(0), sdf, fit.anchor).clipping).toEqual([]);
});
it("reports clipping when a face is forced too large", () => {
const sdf = fieldFor(55);
const forced = { ...solveFit(sdf, 0).anchor, scale: 1 };
expect(report(buildClouds(0), sdf, forced).clipping.length).toBeGreaterThan(0);
});
});
- Step 2: Run it and watch it fail
pnpm exec vitest run scripts/mascot-shapes/solve.test.mjs
Expected: FAIL — cannot resolve ./sdf.ts.
- Step 3: Port both files
As described above. Keep the original comments — they explain why the search sweeps outward from the inscribed circle and why the scale is rounded down before re-checking.
- Step 4: Run the tests
pnpm exec vitest run scripts/mascot-shapes/solve.test.mjs
Expected: PASS, all seven cases.
- Step 5: Commit
git add scripts/mascot-shapes/sdf.ts scripts/mascot-shapes/solve.ts scripts/mascot-shapes/solve.test.mjs
git commit -m "feat: port the distance field and fit solver, minus the canvas"
Task 6: Generate the TypeScript catalog
Files:
- Create:
scripts/gen-mascot-shapes.ts - Create (generated):
shared/mascot-shapes.ts - Modify:
package.json - Test:
scripts/mascot-shapes/catalog.test.mjs
Interfaces:
- Consumes: everything from Tasks 2–5.
- Produces, in
shared/mascot-shapes.ts:export const MASCOT_SHAPE_IDS: readonly ["cursor", "blob", ...] export type MascotShapeId = (typeof MASCOT_SHAPE_IDS)[number] export const mascotShapeSchema: z.ZodEnum<...> export interface MascotShape { id: MascotShapeId; name: string; fit: string; body: string; clip: string; anchor: { x: number; y: number; scale: number } } export const MASCOT_SHAPES: Record<MascotShapeId, MascotShape> export const DEFAULT_MASCOT_SHAPE: MascotShapeId // "cursor" export function botMascotShape(value: unknown): MascotShapeIdbodyis<path fill="{{GRADIENT}}" d="..."/>;clipis the same path without the fill. This matchesCursorSilhouetteexactly, so the renderer needs no adapter.
Solve parameters. Avatar.tsx defaults to forward: true, which cancels each expression's authored gaze and gives the pointer its full range (POINTER_GAZE.forward = 1). So solve with lookAround: 0, and because a pointer can be in any direction, solve at each of the four extreme aims (±1, ±1) and keep the worst scale. A single centred solve would produce a face that clips when someone moves the mouse.
The clamp. After solving all ten, take the minimum scale across the catalog, then re-solve each shape's anchor position at that fixed scale (sweep anchors, keep the one with the best clearance). Fail if the shared scale is below cursor's own solved scale.
The assertion. Fail the generator if report() finds any clipping expression for any shape at its final anchor.
- Step 1: Write the failing test
Create scripts/mascot-shapes/catalog.test.mjs:
import { describe, expect, it } from "vitest";
import {
DEFAULT_MASCOT_SHAPE,
MASCOT_SHAPES,
MASCOT_SHAPE_IDS,
botMascotShape,
mascotShapeSchema,
} from "../../shared/mascot-shapes.ts";
describe("the generated catalog", () => {
it("carries all ten shapes", () => {
expect(MASCOT_SHAPE_IDS).toHaveLength(10);
for (const id of MASCOT_SHAPE_IDS) expect(MASCOT_SHAPES[id].id).toBe(id);
});
it("defaults to the cursor", () => {
expect(DEFAULT_MASCOT_SHAPE).toBe("cursor");
});
it("gives every shape the markup the renderer expects", () => {
for (const id of MASCOT_SHAPE_IDS) {
const shape = MASCOT_SHAPES[id];
expect(shape.body, id).toContain('fill="{{GRADIENT}}"');
expect(shape.clip, id).not.toContain("fill=");
expect(shape.fit, id).toMatch(/^translate\(/);
expect(shape.name.length, id).toBeGreaterThan(0);
}
});
it("places every face inside its body", () => {
for (const id of MASCOT_SHAPE_IDS) {
const { anchor } = MASCOT_SHAPES[id];
expect(anchor.scale, id).toBeGreaterThan(0);
expect(anchor.scale, id).toBeLessThanOrEqual(1);
expect(anchor.x, id).toBeGreaterThan(0);
expect(anchor.y, id).toBeGreaterThan(0);
}
});
it("clamps every face to one shared size", () => {
const scales = new Set(MASCOT_SHAPE_IDS.map(id => MASCOT_SHAPES[id].anchor.scale));
expect([...scales]).toHaveLength(1);
});
});
describe("botMascotShape", () => {
it("accepts a known id", () => {
expect(botMascotShape("blob")).toBe("blob");
});
it("falls back to the cursor for anything else", () => {
expect(botMascotShape("hexagram")).toBe("cursor");
expect(botMascotShape(undefined)).toBe("cursor");
expect(botMascotShape(null)).toBe("cursor");
expect(botMascotShape(42)).toBe("cursor");
});
it("exposes a schema that rejects an unknown id", () => {
expect(mascotShapeSchema.safeParse("star").success).toBe(true);
expect(mascotShapeSchema.safeParse("nope").success).toBe(false);
});
});
- Step 2: Run it and watch it fail
pnpm exec vitest run scripts/mascot-shapes/catalog.test.mjs
Expected: FAIL — cannot resolve ../../shared/mascot-shapes.ts.
- Step 3: Write the generator
Create scripts/gen-mascot-shapes.ts. Pipeline per shape: flatten → boundsOf → fitTransform → applyFit → maskFromPolylines → fieldFromMask → solve at the four extreme aims, keep the worst. Then clamp, re-solve anchors at the shared scale, assert no clipping, and write shared/mascot-shapes.ts.
Emit the file with a generated header, import { z } from "zod", and the exports listed above. botMascotShape mirrors botAvatarProfile in shared/bot-avatar.ts:
export function botMascotShape(value: unknown): MascotShapeId {
return mascotShapeSchema.safeParse(value).data ?? DEFAULT_MASCOT_SHAPE
}
Print a summary table (id, scale, clearance) to stdout so a human running it can see what changed.
- Step 4: Add the script and run it
Add to package.json scripts, next to the other build: entries:
"gen:shapes": "node --experimental-strip-types scripts/gen-mascot-shapes.ts"
Then:
pnpm gen:shapes
Expected: writes shared/mascot-shapes.ts and prints ten rows, every clearance >= 0. If it fails the clipping assertion, the outline from Task 2 is wrong — fix the builder, do not relax the assertion.
- Step 5: Run the tests
pnpm exec vitest run scripts/mascot-shapes/catalog.test.mjs
pnpm typecheck
Expected: PASS.
- Step 6: Commit
git add scripts/gen-mascot-shapes.ts scripts/mascot-shapes/catalog.test.mjs shared/mascot-shapes.ts package.json
git commit -m "feat: generate the mascot shape catalog
Every face placement is solved against the real expression geometry and
clamped to one shared size, so the ten shapes read as one character."
Task 7: Generate the Swift catalog
Files:
- Modify:
scripts/gen-mascot-shapes.ts - Create (generated):
ios/App/MausShapes.swift - Test:
scripts/mascot-shapes/swift-catalog.test.mjs
Interfaces:
- Consumes: the solved catalog from Task 6.
- Produces, in
ios/App/MausShapes.swift:enum MausShapes { struct Shape { let id: String; let name: String; let path: String let fit: (scale: CGFloat, tx: CGFloat, ty: CGFloat) let anchor: (x: CGFloat, y: CGFloat, scale: CGFloat) } static let all: [String: Shape] static let order: [String] static let defaultID = "cursor" static func shape(_ id: String?) -> Shape // falls back to cursor }
iOS gets the fit as numbers, not a transform string — MausSilhouette builds a CGAffineTransform and has no SVG transform parser. This is why fitTransform returns its components alongside the string.
- Step 1: Write the failing test
Create scripts/mascot-shapes/swift-catalog.test.mjs. Since Swift cannot be imported, assert on the emitted text:
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { MASCOT_SHAPES, MASCOT_SHAPE_IDS } from "../../shared/mascot-shapes.ts";
const swift = readFileSync(new URL("../../ios/App/MausShapes.swift", import.meta.url), "utf8");
describe("the generated Swift catalog", () => {
it("warns against hand-editing, like MausFaceData does", () => {
expect(swift).toContain("do not hand-edit");
});
it("declares every shape the TypeScript catalog has", () => {
for (const id of MASCOT_SHAPE_IDS) {
expect(swift, `${id} missing from Swift`).toContain(`"${id}"`);
}
});
it("defaults to the cursor", () => {
expect(swift).toContain('static let defaultID = "cursor"');
});
it("carries the same anchors as the TypeScript catalog", () => {
for (const id of MASCOT_SHAPE_IDS) {
const { anchor } = MASCOT_SHAPES[id];
expect(swift, `${id} anchor.x`).toContain(`x: ${anchor.x}`);
expect(swift, `${id} anchor.y`).toContain(`y: ${anchor.y}`);
}
});
it("emits only the path commands the iOS parser understands", () => {
for (const match of swift.matchAll(/path:\s*"""\n([\s\S]*?)\n\s*"""/g)) {
const unique = [...new Set(match[1].match(/[A-Za-z]/g) ?? [])].sort();
expect(unique.filter(c => !"e".includes(c))).toEqual(["C", "M", "Z"]);
}
});
});
- Step 2: Run it and watch it fail
pnpm exec vitest run scripts/mascot-shapes/swift-catalog.test.mjs
Expected: FAIL — ios/App/MausShapes.swift does not exist.
- Step 3: Emit the Swift file
Extend scripts/gen-mascot-shapes.ts with a second writer. Long paths go in """ multi-line literals, wrapped at ~100 columns on whitespace — exactly how MausSilhouette.path is already formatted, and the parser already treats newlines as separators.
- Step 4: Regenerate and test
pnpm gen:shapes
pnpm exec vitest run scripts/mascot-shapes/swift-catalog.test.mjs
Expected: PASS.
- Step 5: Commit
git add scripts/gen-mascot-shapes.ts ios/App/MausShapes.swift scripts/mascot-shapes/swift-catalog.test.mjs
git commit -m "feat: emit the Swift shape catalog from the same solve
One solve, two platforms — which is what stops the face placement
drifting apart the way 0.74 and 0.84 already did."
Task 8: Guard the generated files against drift
The catalogs are checked in, so nothing stops someone hand-editing them into an invalid state. This test is the guard.
Files:
- Test:
scripts/mascot-shapes/generated.test.mjs
Interfaces:
Consumes: the generator and both catalogs.
Step 1: Write the test
Create scripts/mascot-shapes/generated.test.mjs:
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { SHAPE_DEFS } from "./builders.ts";
import { maskFromPolylines } from "./raster.ts";
import { applyFit, boundsOf, fitTransform, flatten } from "./geometry.ts";
import { fieldFromMask } from "./sdf.ts";
import { buildClouds, report } from "./solve.ts";
import { MASCOT_SHAPES, MASCOT_SHAPE_IDS } from "../../shared/mascot-shapes.ts";
const root = new URL("../../", import.meta.url).pathname;
const read = (p) => readFileSync(new URL(p, import.meta.url), "utf8");
describe("generated catalogs", () => {
it("match a fresh run of the generator", () => {
const before = {
ts: read("../../shared/mascot-shapes.ts"),
swift: read("../../ios/App/MausShapes.swift"),
};
execFileSync("node", ["--experimental-strip-types", "scripts/gen-mascot-shapes.ts"], {
cwd: root,
stdio: "pipe",
});
expect(read("../../shared/mascot-shapes.ts")).toBe(before.ts);
expect(read("../../ios/App/MausShapes.swift")).toBe(before.swift);
}, 120_000);
});
describe("every baked anchor", () => {
/** The four extreme pointer aims the generator solves against. */
const AIMS = [
{ x: -1, y: -1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: 1, y: 1 },
];
it("clears the silhouette across every expression and every gaze", () => {
for (const id of MASCOT_SHAPE_IDS) {
const def = SHAPE_DEFS.find(s => s.id === id);
const polylines = flatten(def.d);
const fit = fitTransform(boundsOf(polylines));
const sdf = fieldFromMask(maskFromPolylines(applyFit(polylines, fit), 256), 256);
for (const aim of AIMS) {
const result = report(buildClouds(0, undefined, aim), sdf, MASCOT_SHAPES[id].anchor);
expect(result.clipping, `${id} clips looking (${aim.x}, ${aim.y})`).toEqual([]);
}
}
}, 120_000);
});
- Step 2: Run it
pnpm exec vitest run scripts/mascot-shapes/generated.test.mjs
Expected: PASS. A failure here means either a catalog was hand-edited or the generator is non-deterministic — fix the cause, never the assertion.
- Step 3: Commit
git add scripts/mascot-shapes/generated.test.mjs
git commit -m "test: fail if a generated catalog drifts from its generator"
Task 9: Persist and sync the shape
Files:
- Modify:
server/store.ts,server/bot-profile.ts,server/team-manifest.ts,server/bot-package.ts,server/package-export.ts,server/index.ts - Test:
server/bot-profile.test.ts(extend)
Interfaces:
- Consumes:
mascotShapeSchema,MascotShapeId,botMascotShapefromshared/mascot-shapes.ts. - Produces:
BotRecord.mascotShape?: MascotShapeId | null, accepted byparseBotProfilePatchand carried inappearance.
Follow mascotExpression and avatarCrop exactly — every place one appears, the other belongs.
- Step 1: Write the failing tests
Append to server/bot-profile.test.ts:
describe("mascotShape", () => {
it("accepts a known shape", () => {
expect(parseBotProfilePatch({ mascotShape: "blob" } as never, true)).toEqual({
ok: true,
patch: { mascotShape: "blob" },
});
});
it("maps an unknown shape to a readable message", () => {
expect(parseBotProfilePatch({ mascotShape: "hexagram" } as never, true)).toEqual({
ok: false,
error:
"mascotShape must be cursor, blob, circle, squircle, capsule, drop, shield, hexagon, diamond, or star",
});
});
});
- Step 2: Run and watch them fail
pnpm exec vitest run server/bot-profile.test.ts
Expected: FAIL — the patch strips the unknown key, so the first case returns { ok: true, patch: {} }.
- Step 3: Thread the field through
server/store.ts— besidemascotExpression?: MausExpression | null(~line 288):
and addmascotShape?: MascotShapeId | null;"mascotShape"to the profile pick at ~line 855 and the spread at ~line 873.server/bot-profile.ts— add"mascotShape"to the allow-list (line 14),line 39),mascotShape: mascotShapeSchema.optional()to the schema ("mascotShape"to thePick<>(line 52), and an issue branch beside theline 77) producing the message the test expects.avatarCropone (server/team-manifest.ts—mascotShape: optionalText(40)besidemascotExpression(line 49); the optional field on both appearance interfaces (lines 91, 203); and the three carry-through sites (~lines 162, 256, 285).server/bot-package.ts—mascotShape: optionalText(40)(line 72) and the appearance spread (line 265).server/package-export.ts— beside line 111:if (bot.mascotShape) appearance.mascotShape = bot.mascotShape;server/index.ts— add"mascotShape"to the broadcast key list at ~line 4048.
- Step 4: Run the server suite
pnpm exec vitest run server/bot-profile.test.ts server/team-manifest.test.ts server/index.test.ts
pnpm typecheck
Expected: PASS.
- Step 5: Commit
git add server shared
git commit -m "feat: persist and sync a bot's mascot shape"
Task 10: Render the chosen shape on desktop
Files:
- Modify:
src/components/Avatar.tsx - Test:
src/components/Avatar.test.ts
Interfaces:
Consumes:
MASCOT_SHAPES,botMascotShape(Task 6).Produces:
MausAvatarProps.shape?: MascotShapeId.Step 1: Write the failing test
Create src/components/Avatar.test.ts, following the renderToStaticMarkup pattern from RenameTitle.test.ts:
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { MausAvatar } from "./Avatar";
import { MASCOT_SHAPES } from "../../shared/mascot-shapes";
const render = (props: Record<string, unknown>) =>
renderToStaticMarkup(createElement(MausAvatar, { color: "green", animated: false, ...props } as never));
describe("MausAvatar shape", () => {
it("wears the cursor when no shape is given", () => {
expect(render({})).toContain(MASCOT_SHAPES.cursor.anchor.scale.toString());
});
it("wears the shape it is given", () => {
const markup = render({ shape: "star" });
expect(markup).toContain(MASCOT_SHAPES.star.fit);
});
it("falls back to the cursor for an unknown shape", () => {
expect(render({ shape: "hexagram" })).toContain(MASCOT_SHAPES.cursor.fit);
});
it("paints the body with the per-bot gradient, never a flat black fill", () => {
const markup = render({ shape: "circle" });
expect(markup).not.toContain('fill="#000000"');
expect(markup).not.toContain("{{GRADIENT}}");
expect(markup).toContain("url(#");
});
});
- Step 2: Run and watch it fail
pnpm exec vitest run src/components/Avatar.test.ts
Expected: FAIL — shape is not a prop, so the star and circle cases render the cursor.
- Step 3: Implement
In src/components/Avatar.tsx:
- Delete the
GRADIENT_SILHOUETTEconstant and its comment (lines ~24-33). The generator emits{{GRADIENT}}directly, so the workaround has nothing left to fix. - Add to
MausAvatarProps:/** Which body the bot wears. Unknown values fall back to the cursor. */ shape?: MascotShapeId; - Destructure
shapeand resolve it:const silhouette = MASCOT_SHAPES[botMascotShape(shape)]; - Pass
silhouette={silhouette}to<CursorAvatar>.
- Step 4: Run the tests
pnpm exec vitest run src/components/Avatar.test.ts
pnpm typecheck
Expected: PASS.
- Step 5: Thread it at the bot call sites
Find them:
grep -rn "MausAvatar" src --include='*.tsx' | grep -v "components/Avatar.tsx"
At each site that renders a specific bot — recognisable because it already passes color={bot.color} — add shape={bot.mascotShape}. Sites rendering a generic mascot (onboarding art, the preview harness) take the default and must not change. BotAvatar in Avatar.tsx is the main wrapper; threading it there covers most of them.
- Step 6: Verify and commit
pnpm typecheck && pnpm lint
git add src/components/Avatar.tsx src/components/Avatar.test.ts src
git commit -m "feat: render a bot's chosen shape
Drops the GRADIENT_SILHOUETTE regex patch: the generator emits the
placeholder the renderer always wanted."
Task 11: The shape picker
Files:
Modify:
src/components/BotProfileAvatarCard.tsxStep 1: Add the picker
Below the existing colour swatch row (after the crop === "mascot" block that renders expressions and colours, ~line 205 onward), add a shape row, shown only when crop === "mascot" || crop === "face" — those are the two modes that draw a body.
Follow the existing section idiom exactly: a text-[12px] font-medium uppercase tracking-[0.08em] text-ink-secondary label reading Body, then a grid grid-cols-5 gap-1.5 of buttons, one per MASCOT_SHAPE_IDS.
Each button renders a live 34px preview in the bot's current colour, so the choice is shown rather than named:
<button
key={id}
type="button"
aria-pressed={(bot.mascotShape ?? "cursor") === id}
aria-label={`Use the ${MASCOT_SHAPES[id].name} body`}
onClick={() => onPatch({ mascotShape: id })}
className={cn(
"flex items-center justify-center rounded-lg py-1.5",
(bot.mascotShape ?? "cursor") === id
? "bg-control text-ink"
: "text-ink-secondary hover:bg-control/60",
)}
>
<MausAvatar color={bot.color} shape={id} size={34} animated={false} trackPointer={false} />
</button>
animated={false} matters: ten animating avatars in a settings panel is ten 30fps canvases for a control the user looks at once.
Add mascotShape to the AvatarPatch type at the top of the file, and to the Pick<Bot, ...> in SettingsPanel.tsx (~line 336) so the patch reaches the server.
Extend the Reset mascot handler to clear it:
onClick={() => onPatch({ avatarCrop: "mascot", color: "green", mascotExpression: null, mascotShape: "cursor" })}
- Step 2: Verify
pnpm typecheck && pnpm lint
- Step 3: Commit
git add src/components/BotProfileAvatarCard.tsx src/components/SettingsPanel.tsx
git commit -m "feat: pick a bot's body from the ten shapes"
Task 12: An image can be the body
Files:
- Modify:
src/components/CursorAvatar.tsx,shared/bot-avatar.ts - Test:
src/components/CursorAvatar.test.ts,server/bot-avatar.test.ts(extend)
Interfaces:
Produces:
CursorSilhouette.bodyImage?: string;BOT_AVATAR_CROPSgains"face".Step 1: Write the failing tests
Create src/components/CursorAvatar.test.ts:
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { CursorAvatar, DEFAULT_SILHOUETTE } from "./CursorAvatar";
const render = (silhouette: unknown) =>
renderToStaticMarkup(
createElement(CursorAvatar, { silhouette, animated: false } as never),
);
describe("CursorAvatar body", () => {
it("paints a gradient when there is no image", () => {
const markup = render(DEFAULT_SILHOUETTE);
expect(markup).not.toContain("<image");
expect(markup).toContain("linearGradient");
});
it("paints the image, clipped to the silhouette, when there is one", () => {
const markup = render({
...DEFAULT_SILHOUETTE,
bodyImage: "/api/attachments/cat.webp",
});
expect(markup).toContain("<image");
expect(markup).toContain("/api/attachments/cat.webp");
expect(markup).toContain('preserveAspectRatio="xMidYMid slice"');
});
it("scrims the image so a white face stays readable on a pale picture", () => {
const markup = render({ ...DEFAULT_SILHOUETTE, bodyImage: "/api/attachments/cat.webp" });
expect(markup).toContain("radialGradient");
});
it("escapes the image URL instead of interpolating it as markup", () => {
const markup = render({
...DEFAULT_SILHOUETTE,
bodyImage: '/api/attachments/x.webp"/><script>alert(1)</script>',
});
expect(markup).not.toContain("<script>");
expect(markup).toContain("<script>");
});
});
Append to server/bot-avatar.test.ts:
it("accepts the living-image crop", () => {
expect(botAvatarProfile({ avatarUrl: "/api/attachments/a.webp", avatarCrop: "face" }))
.toEqual({ avatarUrl: "/api/attachments/a.webp", avatarCrop: "face" });
});
- Step 2: Run and watch them fail
pnpm exec vitest run src/components/CursorAvatar.test.ts server/bot-avatar.test.ts
Expected: FAIL — no <image> rendered; "face" is not a valid crop.
- Step 3: Implement
In shared/bot-avatar.ts, add "face" to BOT_AVATAR_CROPS, placed second so it reads ["mascot", "face", "circle", "rounded", "square"]. Update the doc comment: the first two draw the mascot body, the rest crop a flat image.
In src/components/CursorAvatar.tsx:
- Add to
CursorSilhouette:/** * When set, the body is this image clipped to the silhouette rather than a * gradient fill. A typed prop, not a token in `body` — `body` and `clip` are * injected as raw markup, and interpolating a URL into raw markup is an * injection path. */ bodyImage?: string - In
defs, alongside the existing linear gradient, add the scrim — a radial gradient centred on the anchor, rendered only whenbodyImageis set:{silhouette.bodyImage && ( <radialGradient id={`${uid}-scrim`} gradientUnits="userSpaceOnUse" cx={silhouette.anchor.x} cy={silhouette.anchor.y} r={FACE_BOX * 0.55} > <stop offset="0%" stopColor="#000000" stopOpacity="0.42" /> <stop offset="65%" stopColor="#000000" stopOpacity="0.14" /> <stop offset="100%" stopColor="#000000" stopOpacity="0" /> </radialGradient> )} - Replace the single body group with a branch. Keep the existing gradient path untouched for the no-image case:
The image is not wrapped in{silhouette.bodyImage ? ( <> <image href={silhouette.bodyImage} x={0} y={0} width={FACE_BOX} height={FACE_BOX} preserveAspectRatio="xMidYMid slice" clipPath={`url(#${uid}-clip)`} /> <rect x={0} y={0} width={FACE_BOX} height={FACE_BOX} fill={`url(#${uid}-scrim)`} clipPath={`url(#${uid}-clip)`} /> </> ) : ( <g transform={silhouette.fit || undefined} dangerouslySetInnerHTML={{ __html: body }} /> )}silhouette.fit: it is drawn in face-box space and clipped by#{uid}-clip, which already has the fit baked onto theclipPathelement.
- Step 4: Run the tests
pnpm exec vitest run src/components/CursorAvatar.test.ts server/bot-avatar.test.ts src/components/Avatar.test.ts
pnpm typecheck
Expected: PASS. Existing Avatar.test.ts cases must still pass — the gradient path is unchanged.
- Step 5: Commit
git add src/components/CursorAvatar.tsx src/components/CursorAvatar.test.ts shared/bot-avatar.ts server/bot-avatar.test.ts
git commit -m "feat: let an image be the mascot's body
Clipped to the silhouette with a radial scrim, so a white face stays
readable over a pale picture."
Task 13: Wire the living image on desktop
Files:
Modify:
src/components/Avatar.tsx,src/components/BotProfileAvatarCard.tsxTest:
src/components/Avatar.test.ts(extend)Step 1: Write the failing tests
Append to src/components/Avatar.test.ts:
describe("MausAvatar living image", () => {
it("wears the image when the bot is in face mode", () => {
const markup = render({ shape: "circle", bodyImage: "/api/attachments/cat.webp" });
expect(markup).toContain("<image");
expect(markup).toContain("/api/attachments/cat.webp");
});
it("keeps the gradient body when there is no image", () => {
expect(render({ shape: "circle" })).not.toContain("<image");
});
});
- Step 2: Run and watch them fail
pnpm exec vitest run src/components/Avatar.test.ts
Expected: FAIL — bodyImage is not a prop.
- Step 3: Implement
- In
Avatar.tsx, addbodyImage?: stringtoMausAvatarPropsand fold it into the resolved silhouette:const base = MASCOT_SHAPES[botMascotShape(shape)]; const silhouette = bodyImage ? { ...base, bodyImage } : base; - In
BotAvatar(the bot-aware wrapper in the same file), pass the image when the crop isface:
The existing flat-crop branch is untouched:const profile = botAvatarProfile(bot); const bodyImage = profile.avatarCrop === "face" ? profile.avatarUrl : undefined;circle,roundedandsquarestill render the image without a mascot. - In
BotProfileAvatarCard.tsx, change the upload default so a new image keeps its face:
Do the same in theonPatch({ avatarUrl, avatarCrop: latestCrop === "mascot" ? "face" : latestCrop });generatehandler's fallback (result.bot.avatarCrop ?? "face"). - Add
faceto the crop selector's labels. The grid isgrid-cols-4for four crops — change it togrid-cols-5and label the new oneLiving.
- Step 4: Run and commit
pnpm exec vitest run src/components/Avatar.test.ts && pnpm typecheck && pnpm lint
git add src/components/Avatar.tsx src/components/Avatar.test.ts src/components/BotProfileAvatarCard.tsx
git commit -m "feat: uploading an image keeps the bot's face"
Task 14: Carry the shape to the phone
Files:
Modify:
ios/Sources/CompanionCore/Models.swiftStep 1: Add the fields
- On
Bot(~line 228, besidemascotExpression):public var mascotShape: String? - On
BotProfilePatch(line 566, besideline 599), and theavatarCrop): the property, the initialiser parameter and assignment, theCodingKeyscase (encodeIfPresent(~line 614) — matchingavatarCropline for line. - Add
case facetoAvatarCrop, with raw value"face".
An unknown crop must keep decoding to mascot rather than throwing; confirm AvatarCrop decoding already tolerates unknown values, and if it does not, make it do so — an older phone must survive a newer desktop.
- Step 2: Build
cd ios && swift build 2>&1 | tail -20
Expected: builds clean.
- Step 3: Commit
git add ios/Sources/CompanionCore/Models.swift
git commit -m "feat: carry mascotShape and the living crop to the phone"
Task 15: Render the chosen shape on iOS
Files:
Modify:
ios/App/MausAvatar.swift,ios/App/BotAvatarView.swiftTest:
ios/Tests/MausShapesTests.swiftStep 1: Write the failing test
Create ios/Tests/MausShapesTests.swift:
import XCTest
@testable import CompanionCore
final class MausShapesTests: XCTestCase {
func testEveryShapeParsesToAClosedPath() {
for id in MausShapes.order {
let path = MausSilhouette.inFaceBox(id)
XCTAssertFalse(path.isEmpty, "\(id) parsed to nothing")
let bounds = path.boundingRect
XCTAssertGreaterThan(bounds.width, 0, "\(id) has no width")
XCTAssertGreaterThan(bounds.height, 0, "\(id) has no height")
XCTAssertLessThanOrEqual(bounds.maxX, MausFaceData.faceBox + 1, "\(id) overflows the face box")
XCTAssertLessThanOrEqual(bounds.maxY, MausFaceData.faceBox + 1, "\(id) overflows the face box")
}
}
func testUnknownShapeFallsBackToTheCursor() {
XCTAssertEqual(MausShapes.shape("hexagram").id, "cursor")
XCTAssertEqual(MausShapes.shape(nil).id, "cursor")
}
func testAnchorsMatchTheGeneratedCatalog() {
for id in MausShapes.order {
let anchor = MausShapes.shape(id).anchor
XCTAssertGreaterThan(anchor.scale, 0, "\(id) has no face")
XCTAssertLessThanOrEqual(anchor.scale, 1, "\(id) inflates the face")
}
}
}
- Step 2: Run and watch it fail
cd ios && swift test --filter MausShapesTests 2>&1 | tail -20
Expected: FAIL — MausSilhouette.inFaceBox(_:) does not exist.
- Step 3: Generalise
MausSilhouette
In ios/App/MausAvatar.swift, replace the single-shape statics with per-shape lookups. Keep the parse-once caching — the existing comment explains it exists because a chat list redraws hundreds of avatars per frame, and per-shape caching is what preserves that:
private static var cache: [String: Path] = [:]
private static let lock = NSLock()
/// The silhouette in the desktop's face box, parsed once per shape.
static func inFaceBox(_ id: String) -> Path {
let shape = MausShapes.shape(id)
lock.lock(); defer { lock.unlock() }
if let cached = cache[shape.id] { return cached }
let path = parse(shape.path).applying(
CGAffineTransform(scaleX: shape.fit.scale, y: shape.fit.scale)
.concatenating(CGAffineTransform(translationX: shape.fit.tx, y: shape.fit.ty))
)
cache[shape.id] = path
return path
}
Make parse take the path string as a parameter rather than reading the old static. Delete MausSilhouette.path, parsed, parsedBounds, inFaceBox and faceBoxBounds as stored statics — they become per-shape functions. fit(_ rect:) and margin stay as they are; they are about the viewport, not the shape.
Then give MausAvatar a var shape: String = "cursor" parameter and replace every MausSilhouette.inFaceBox / MausFaceData.anchor reference in its drawing code (around lines 497-531) with the per-shape lookup. BotAvatarView and ChatAvatarView pass bot.mascotShape.
- Step 4: Run and commit
cd ios && swift test --filter MausShapesTests 2>&1 | tail -20
Expected: PASS.
git add ios/App/MausAvatar.swift ios/App/BotAvatarView.swift ios/Tests/MausShapesTests.swift
git commit -m "feat: render the chosen shape on iOS"
Task 16: The living image on iOS
Files:
Modify:
ios/App/MausAvatar.swift,ios/App/BotAvatarView.swiftStep 1: Draw an image body
Give MausAvatar an optional image:
/// When set, the body is this image clipped to the silhouette instead of the
/// colour gradient — the phone's half of the desktop's `bodyImage`.
var bodyImage: UIImage?
In the body-drawing block (~line 520), branch. Where the gradient fill happens today, instead clip and draw:
if let bodyImage {
context.drawLayer { layer in
layer.clip(to: silhouette)
layer.draw(Image(uiImage: bodyImage), in: bounds)
// The face is white; a pale image would swallow it. Same radial scrim
// the desktop paints, same anchor, same falloff.
layer.fill(
Path(bounds),
with: .radialGradient(
Gradient(stops: [
.init(color: .black.opacity(0.42), location: 0),
.init(color: .black.opacity(0.14), location: 0.65),
.init(color: .black.opacity(0), location: 1),
]),
center: CGPoint(x: anchor.x, y: anchor.y),
startRadius: 0,
endRadius: MausFaceData.faceBox * 0.55
)
)
}
} else {
// existing gradient fill, unchanged
}
layer.draw(Image:in:) uses .scaledToFill semantics against the given rect; pass the silhouette's bounding rect so the picture covers the body the way xMidYMid slice does on the web.
- Step 2: Branch three ways in
BotAvatarView
Replace the current two-way usesImage branch:
private var crop: AvatarCrop { bot.avatarCrop ?? .mascot }
/// Flat crops replace the mascot; `.face` feeds the image into it.
private var usesFlatImage: Bool { crop != .mascot && crop != .face && bot.avatarUrl != nil && !failed }
private var usesImageBody: Bool { crop == .face && bot.avatarUrl != nil && !failed }
Render: flat image as today; usesImageBody passes the decoded image to MausAvatar(bodyImage:); everything else is the gradient mascot. The existing failed handling already covers all three — a missing or undecodable attachment falls through to the gradient mascot, so identity is never an empty placeholder.
Widen the .task(id:) guard so face also fetches: change guard crop != .mascot to guard crop != .mascot, bot.avatarUrl != nil.
- Step 3: Build, test, commit
cd ios && swift build 2>&1 | tail -20 && swift test 2>&1 | tail -20
git add ios/App/MausAvatar.swift ios/App/BotAvatarView.swift
git commit -m "feat: the living image body on iOS"
Task 17: Full verification
- Step 1: Run everything
pnpm typecheck && pnpm lint && pnpm exec vitest run
cd ios && swift build && swift test
Expected: all green.
- Step 2: Look at it
Use the run skill to launch the desktop app. Then:
- Open a bot's profile. Confirm ten body previews, each in the bot's colour.
- Switch between several. Confirm the face stays the same size and stays inside the body.
- Upload an image. Confirm it lands on Living, fills the body, and the face blinks and tracks the pointer over it.
- Try a very pale image and a very dark one. Confirm the face is readable on both — this is what the scrim is for.
- Switch to
Circlecrop. Confirm it reverts to today's flat behaviour. - Put the desktop and the phone side by side on the same bot. Confirm the face sits identically on both — that is the drift fix, and it is the one thing no automated test can prove.
- Step 3: Report
Summarise what shipped, and flag that the cursor anchor moved from 0.74 (desktop) and 0.84 (iOS) to whichever single value the solver produced, so a reviewer expecting pixel-identical desktop output knows why it changed.
Do not push or open a PR. Leave the branch for Omkar.
Self-Review
Spec coverage:
| Spec section | Task |
|---|---|
| The catalog (ten shapes, stable ids) | 2, 6 |
| Face scale is clamped | 6 (clamp + assertion), 6 test |
| The generator (pipeline, no deps, cubics-only) | 2, 3, 4, 5, 6, 7 |
| Generator fails on clipping | 6, 8 |
Desktop (Avatar.tsx, workaround removal, call sites) |
10 |
| Desktop picker | 11 |
| iOS (per-shape lookup, cache, fallback) | 15 |
| Schema and sync | 9, 14 |
Custom images: the face mode |
12, 13, 16 |
| Custom images: rendering + typed prop | 12 |
| Custom images: face contrast scrim | 12, 16 |
| Custom images: iOS three-way branch | 16 |
| Testing (all listed cases) | 1–8, 10, 12, 13, 15, 17 |
No gaps.
Type consistency: MascotShapeId is defined in Task 6 and used in 9, 10, 12, 13. botMascotShape is defined in 6 and used in 10, 13. bodyImage is string on the web (Task 12) and UIImage? on iOS (Task 16) — deliberately different, since the web takes a URL and Swift takes decoded bytes that Session.avatarData(for:) already fetches. MausShapes.shape(_:) is defined in Task 7's emitted Swift and used in 15 and 16. fitTransform returns both the string (web, Task 3) and the components (Swift, Task 7) — both consumers are covered.
Placeholder scan: No TBDs. Every code step carries real code. Task 2's builders are the one place describing a conversion rather than printing all ten paths in full — the conversion helpers are given in full and the source parameters are cited file-by-file, because ten literal cubic paths would be several thousand digits of generated output that the generator produces anyway and Task 2's test verifies.