name: minimoji-web
description: Add Minimoji 3D avatar heads to a React or Next.js web app with @minimoji/react — use when asked to "add Minimoji" to a web page, show a Mini avatar head or a character (D.A.S.H., an alien, an animal, the penguin, the ghost), make a head talk with lip-sync and emotes from audio or a recorded line, cue a mood or gesture, show the head's loader, or get a Minimoji key for a web app.
@minimoji/react: Minimoji heads in a web app
@minimoji/react draws live Minimoji heads in the browser: one
<MinimojiStage> per page (a WebGL canvas), and <MinimojiHead>s placed
over ordinary DOM elements (their anchors). A head is built on the page
from its avatar JSON or a character id: drawing one fetches nothing and needs
no key. The head already blinks, breathes, glances, emotes on a mood change,
lip-syncs what you feed it and talks naturally while it does; build on that,
never redraw it.
This file is the rules and the smallest snippets. Every tsx snippet here is
typechecked against the package's src/index.d.ts by a test in the Minimoji
repo, so it compiles against the version you have. The full API is
src/index.d.ts and README.md in the package. The minimoji.com homepage is
the reference integration: its hello row and cast conversation are built
exactly as section 4 shows.
1. Install
@minimoji/react is on npm, with its peers:
npm install @minimoji/react react@19 react-dom@19 three@0.160 @react-three/fiber@9
In the Minimoji monorepo it is "@minimoji/react": "workspace:*".
- It is plain ESM with types, no build step. In Next.js it renders on the
client only: put
'use client' on the file that mounts the stage.
- WebGL: a stage needs a browser. Server-render the anchors and the poster
(section 4), never the stage.
- What it fetches by default: the engine is inside the package, so a head
draws with no network beyond what you point it at, but for two things from
https://www.minimoji.com (allow
them in a strict CSP): a sculpted haircut or hat's mesh from /sdk/parts/
(connect-src; if it fails the head draws a hand-made fallback) and the
mood stickers' PNGs from /emote-bursts/ (img-src, or serve your own,
section 5).
2. One head
'use client';
import { useRef } from 'react';
import { MinimojiStage, MinimojiHead, type AvatarInput } from '@minimoji/react';
// the same JSON the avatar service and the Swift Kit take; the same document is always the same head
const me: AvatarInput = { seed: 4821, head: 'round', skin: 'brown', hair: { style: 'afro', color: 'ink' } };
export function Me() {
const anchor = useRef<HTMLDivElement>(null);
return (
<>
<div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }} />
<MinimojiStage>
<MinimojiHead avatar={me} anchor={anchor} expression="happy" look="mouse" />
</MinimojiStage>
</>
);
}
- The anchor is a DOM element outside the stage. The stage's children
render inside its WebGL canvas: only
MinimojiHead and MinimojiShadow
go there, never a <div>. The head is placed in its anchor's rect every
frame, so the anchor can live anywhere on the page, scroll, move or resize.
anchor is required in the default mode="overlay"; without it the head
is built and never placed.
- A saved avatar is stored by its avatar key; keep the document (or
fetch it by key from the service) to draw it live.
avatarKey(avatar) is
the normalized JSON, for React keys and caches.
look: 'mouse' (follows the pointer anywhere), 'near' (within
reach px), 'idle' (glances about on its own), { x, y } in −1…1,
null (the camera), 'manual' (you call head.life.lookAt).
A character: D.A.S.H., an alien, an animal
'use client';
import { useRef } from 'react';
import { MinimojiStage, MinimojiHead } from '@minimoji/react';
export function Dash() {
const anchor = useRef<HTMLDivElement>(null);
return (
<>
<div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }} />
<MinimojiStage>
{/* `avatar` is still required: a character draws instead of it */}
<MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor} expression="joy" />
</MinimojiStage>
</>
);
}
- Ids:
agent (D.A.S.H.), its themes (dashGold, dashNeon, …), the
aliens (alien, alienMint, …), cat, kitty, rabbit, monkey,
dog, penguin, ghost. The service's GET /capabilities lists them
(characters), and CHARACTERS in @minimoji/react/characters.
- A dealt one (
dashDealt, alienDealt) takes a seed: the same seed is
the same face. { id, pick } fixes parts of a kit.
- Play a character exactly like a person: expressions, cues, talking,
listening. No per-species code; D.A.S.H. draws its mouth on its screen.
The stage
- One
<MinimojiStage> per page, high in the tree, holding every head.
It is fixed over the page and transparent (mode="overlay", the default).
mode="wall" is the opaque viewer wall: the head sits in the stage's
own box (give it a size with style), no anchor.
mode is fixed for the stage's life: change its key to switch.
detail (0.2–1, default 1) is the mesh detail for the page; the
homepage runs .8 with about thirty heads.
surfaces (on by default) paints each head into a 2D canvas inside its
anchor, so heads scroll with the page on the compositor. Mark an ancestor
data-minimoji-surface to have its heads share one canvas: do it for a
group shot, and wherever the anchor clips its overflow.
- Sizing: a head's canvas is sized by what the screen shows of its
anchor, an ancestor's
transform or css zoom included: the backing
store is the on-screen box in device pixels, the canvas's css box that
box in the anchor's own coordinates. A head in a scaled container is
sharp and its own size. The stage follows an anchor resized, and an
ancestor's transform that transitions or animates, until it stops
moving; for a move no event reports (a transform set with no transition,
a canvas library's own zoom) call resize() on a ref to
<MinimojiStage> (or useStage().resize() inside it). A rotated
ancestor is not handled.
3. Showing a head while it loads
Do not draw your own placeholder. A head is built a moment after the page
paints; until it lands, <MinimojiHeadPoster> inside the anchor shows the
local silhouette immediately, then the head's own still: it comes in soft
and breathes, then gives way with a puff
when the head is ready, stays sharp on an error, and is a plain swap under
reduced motion. The silhouette takes currentColor (set style.color to a
contrasting tile tint), fades as the still arrives, and stays sharp if the
still fails. The same loader as the homepage and the Swift Kit.
'use client';
import { useRef } from 'react';
import { MinimojiStage, MinimojiHead, MinimojiHeadPoster, type AvatarInput } from '@minimoji/react';
export function SavedHead({ avatar, avatarKey, service }: { avatar: AvatarInput; avatarKey: string; service: string }) {
const anchor = useRef<HTMLDivElement>(null);
return (
<>
<div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }}>
<MinimojiHeadPoster src={`${service}/avatars/${avatarKey}.png?size=256`} />
</div>
<MinimojiStage>
<MinimojiHead avatar={avatar} anchor={anchor} />
</MinimojiStage>
</>
);
}
- It runs off the anchor's
data-minimoji (loading → ready |
error, set by the head). Write data-minimoji="loading" in your
markup so it runs from the first paint, server-rendered or not; give the
anchor position: relative.
- The still: a saved avatar's
<service>/avatars/<avatarKey>.png?size=256
(drawn at save), or any transparent picture of the head. A character has
no saved picture until it is saved: ship your own still (the homepage
ships .webp stills), or no poster.
- A grid of stills (a picker, a list of people): add
&frame=face, which
frames each picture by the head's skin, so every face is the same size and
a tall hat or long hair is clipped at the edge instead of shrinking it.
Leave it off for a poster under a live head (the default frames the whole
head, as the live head does).
- A small resting D.A.S.H. needs no poster: the first builds in about
0.2–0.35 s, the rest about 50–120 ms each, and each draws at its final size
from its first frame (§ 8,
rest).
- No app CSS: the sheet is a React 19 hoisted
<style>. Without React's
hoisting, add POSTER_CSS to a stylesheet. style re-places the still
({ inset: 'auto', left, top, width, height }); puff={false} drops
the puff.
4. Making it talk
Feed the head speech and the rest follows: the mouth articulates (lips
meet on m/b/p), the breath follows the phrases, and natural talk
(naturalTalk, on by default) plans glances aside and lifts the brows on the
pitch. Moods ride on top as emotes. Never hand-draw talking frames or animate
the jaw yourself.
From least to most:
talking={2} (seconds) or talking={true}: a generic talking jaw, no
audio. A changing number (Date.now()) re-triggers it.
voiceLevel={0…1} (a call's level meter): drives the optional sound arcs
or lines (talkStyle="arcs" | "lines"; the default 'mouth' is the jaw
alone). It does not move the jaw.
performance: the real lip-sync. A function the head calls every
frame, returning the mouth for that moment of the audio. From a recorded
line, mouthTrack turns the clip's samples into one mouth per 1/60 s:
Say a line: one call
Hand the head the audio. useLine().say({ audio, transcript }) makes
the head lip-sync to it, emote and caption it, with no timeline and no
lip-sync code in your app. The SDK fetches the clip, decodes it with Web
Audio, builds the line with buildLine (the analyser the homepage's lines
are made with) and caches it. prepare(clip) does that ahead of time, so the
click starts the line at once.
'use client';
import { useEffect, useRef } from 'react';
import { MinimojiStage, MinimojiHead, MinimojiCaptions, useLine, type SpeechClip } from '@minimoji/react';
const HEY: SpeechClip = { audio: '/voice/dash-hey.mp3', transcript: 'Hey! I am D.A.S.H.', mood: 'happy' };
export function DashSaysHey() {
const anchor = useRef<HTMLButtonElement>(null);
const line = useLine({ onEnd: (_g, reason, error) => { if (reason === 'failed') console.warn(error); } });
// build it ahead of the click, so the click's play() runs inside the gesture
useEffect(() => { line.prepare(HEY).catch(() => {}); }, []);
return (
<>
<button ref={anchor} type="button" aria-label="Say hi to D.A.S.H." data-minimoji="loading"
=> line.say(HEY)}
style={{ position: 'relative', width: 160, height: 160 }} />
<MinimojiCaptions player={line} />
<MinimojiStage>
<MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor} emotes={false}
expression={line.expression ?? 'neutral'} performance={line.performance} cue={line.cue} />
</MinimojiStage>
</>
);
}
The clip is { audio, transcript?, words?, letters?, alignment?, captions?, mood?, cues?, transcribe? }.
audio can be a URL, a Blob (a TTS response), an ArrayBuffer or an
AudioBuffer. words ([{ text, start, end }] in seconds, from your TTS
provider's timestamps) give phrase captions and word cues, such as a nod on
"yes" or a laugh on "haha". A transcript, or a captions string, gives
one caption over the voiced part. With none of these there are no
captions. Clips are cached by URL (or by the Blob or buffer object)
together with their words and letters, keeping the last 8.
Pass your TTS alignment and the lips land on the letters. A provider's
per-character timestamps shape the mouth from the words instead of guessing
from the sound: the lips meet on m, b and p and only there, and a vowel
never snaps shut. Hand ElevenLabs' with-timestamps reply over as it comes,
say({ audio, words, alignment: tts.alignment }), or as letters
([{ text, start, end }], one character each with the spaces, seconds;
lettersFromAlignment from @minimoji/react builds them). Words only (a
transcriber's) spread into letters on their own: a clip with words and no
letters or alignment gets lettersFromWords(words) by default
(letters: false opts out, the mouth guessed from the audio). A direct
buildLine call does not do this: pass letters: lettersFromWords(words)
yourself. Captions ending a few ms past the audio (a provider's timestamps
often do) end with it instead of failing the clip. A URL that serves new audio
each time needs a fresh URL per clip, or pass the Blob.
Any voice, not only ElevenLabs. Every provider's timings become our
words ([{ text, start, end }], seconds) with a small reader from
@minimoji/react (also in /sdk/minimoji-heads.js); then
say({ audio, words }) (the words spread into letters by default):
| Provider |
What it gives |
Reader |
| ElevenLabs with-timestamps |
characters + start/end arrays |
alignment: tts.alignment (or lettersFromAlignment); wordsFromAlignment(tts.alignment) for the words |
| ms words you stored |
{ text, startMs, durationMs } |
wordsFromMs(words) |
| Azure Speech |
WordBoundary events: text, audioOffset + duration in 100 ns ticks |
wordsFromAzure(events) (punctuation boundaries skipped) |
| Amazon Polly |
speech marks: JSON lines { time (ms), type: "word", value } |
wordsFromPolly(marks, clipSeconds) (a word ends where the next starts; a cut-off line throws) |
| Cartesia |
word_timestamps: { words, start, end } (seconds) |
wordsFromCartesia(word_timestamps) (one or a stream's pieces) |
| Dictation, Scribe |
words only |
words (spread by lettersFromWords by default) |
| OpenAI TTS, any voice with no timings, a human take |
nothing |
say({ audio, transcript: 'what it says', transcribe: true }): the service aligns the text to the audio |
Spread letters are an estimate (the lips still meet inside the right
word); a provider's characters, or the service's alignment, are exact.
No audio, only words? Say the text. Give useLine a synthesize
(your publishable key and the service) and say { text, voice }: Minimoji's
POST /lines/say speaks it on its own ElevenLabs voice and answers the
WAV and the line built on it, the letters timed on that very audio, so the
mouth timings come from the call that made the sound. voice is a name from
GET /lines/voices (dash is D.A.S.H.: Brian with the robot effect;
person, alien, cat, penguin, ghost…), or one of their ids as
{ voiceId, effect: 'robot', settings }; any other ElevenLabs voice id
needs your own key (below), since Minimoji's account speaks only its
catalogue. A text past about 60 s of speech (~900 characters at speed 1)
is refused before anything is spent. prepare({ text, voice }) ahead
of the click makes the say start inside it (a repeat is never asked again):
'use client';
import { useEffect } from 'react';
import { useLine, MinimojiCaptions, type TextClip } from '@minimoji/react';
const HI: TextClip = { text: "[happy] Hi, I'm D.A.S.H.!", voice: 'dash' };
export function DashSaysHi() {
const line = useLine({ synthesize: { key: process.env.NEXT_PUBLIC_MINIMOJI_KEY!, service: process.env.NEXT_PUBLIC_MINIMOJI_SERVICE_URL! } });
useEffect(() => { line.prepare(HI).catch(() => {}); }, []);
// wire line.performance / line.cue / line.expression to a <MinimojiHead> as above
return (
<>
<button type="button" => line.say(HI)}>Say hi</button>
<MinimojiCaptions player={line} />
</>
);
}
[tags] set the face. On Minimoji's voice a key has 5,000
characters a UTC day (a repeat of the same line costs none: it is served
from the cache), then a 429 with the reset. Bring your own ElevenLabs
key for no character quota and any voice on your account: synthesize: { key, service, elevenLabsKey }
sends it in the ElevenLabs-Key header (never a query string; it is used
for the one call and never stored or logged); the minute limit stays.
Calling it yourself: POST /lines/say with Authorization: Bearer mk_pub_…
and { text, voice, mood? } answers { audio, line, words, letters, durationMs, cached, charged }; play say(answer.line, { audio: answer.audio }). Audio you process afterwards (isolated, mixed, sped
up) no longer matches those letters: send the final clip with its text to
POST /lines (multipart { audio, text }, below) for letters aligned on it.
From a terminal: npx minimoji say kai "Hi" --server writes the same
<name>.wav + <name>.json on your Minimoji key.
Clips you already have, in a batch: npx minimoji lines ./clips --texts lines.json --timings
sends each clip (.wav, or .mp3/.m4a with ffmpeg) with its text to
POST /lines on your Minimoji key and writes <name>.json (the playable
line: say(line, { audio })) beside it; --timings adds
<name>.timings.json ({ transcript, words, letters, alignedTo, loss })
for an app that keeps its own line format. The text comes from --text,
--texts ({ "<name>": "text" } or { "<name>": { text } }) or a
<name>.txt beside the clip; a clip with none is transcribed. --dry-run
sends nothing. Each clip is one of the key's 200 lines a day, at most 30 s.
A voice note with no transcript (a recording a person made, a voice
chat message): pass your publishable key and the service to useLine, and
say the audio alone. The SDK sends it to Minimoji's POST /lines, which
transcribes it, and the line plays with phrase captions and word cues:
'use client';
import { useLine, MinimojiCaptions } from '@minimoji/react';
export function VoiceNote({ note }: { note: Blob }) { // a Blob from MediaRecorder, a URL or bytes
const line = useLine({ transcribe: { key: process.env.NEXT_PUBLIC_MINIMOJI_KEY!, service: process.env.NEXT_PUBLIC_MINIMOJI_SERVICE_URL! } });
// wire line.performance / line.cue / line.expression to a <MinimojiHead> as above
return (
<>
<button type="button" => line.say({ audio: note, transcribe: true })}>Play</button>
<MinimojiCaptions player={line} />
</>
);
}
With transcribe on the hook, a clip with no words, transcript or
captions is transcribed even without transcribe: true, and if that
fails (over 30 s, offline, the key's 200 a day spent) it plays as the plain
waveform line with a console warning. With transcribe: true a failure
ends the say onEnd(…, 'failed', error) with the service's words.
transcribe: false never sends it. The SDK decodes any audio the browser
plays and sends it as a 16 kHz WAV; if you call POST /lines yourself,
send a WAV (it refuses mp3, m4a and webm, whose length it cannot check).
Know what it says? Give the clip its transcript with
transcribe: true (and no words or letters): the SDK sends the text too,
the service force-aligns that script to the audio instead of transcribing
it, and the lips follow the words as written (the answer says
alignedTo: 'text'; a high loss means text and audio disagree; a
transcript with no words outside its [tags], or over 2,000 characters,
is transcribed as before). Calling
it yourself: multipart/form-data with audio (the WAV) and text
(at most 2,000 characters; [tags] are kept off the aligner and set the
face). Privacy:
the audio (and the text, if given) is sent to Minimoji and to ElevenLabs for transcription or alignment and is
not stored. Tell your people so where they record. The vanilla bundle's
createVoicedPerformance({ …, transcribe: { key, service } }) does the same.
Not prepared? say still works. The line starts once it has been built
(about 20 ms per second of audio on a laptop). line.preparing is true
until then, and the head stays as it is.
A clip that fails (it will not load, it is not audio, or it runs past
60 s) never throws and never hangs. The head stays still,
onEnd(generation, 'failed', error) reports it, and line.error holds the
error until the next say.
A prebuilt line is the fast path: a *.timeline.json (the public format
in docs/speech-line-format.md: mouth frames at 60 fps, captions,
optional timed words, mood and gesture cues), played with
line.say(timeline, { audio: '/lines/dash-hey.mp3' }). The homepage's
hellos run on this. Use it when you build lines ahead of time.
No React? The site serves /sdk/minimoji-heads.js
(apps/web/public/sdk/), a single ESM file with three bundled. It provides
mountHeadPerformance and createVoicedPerformance, whose
select({ audio, transcript }) takes the same plain clip, plus
createLineSession (this hook without React) and createClipCache.
createVoicedPerformance({ ..., muted, volume }) and its setMuted(m) /
setVolume(v) hold a sound-off narrator across stop, replay and the next
clip (every run makes a fresh element); the head still talks on a muted
element. Unset, the element stays as your createMedia made it.
The mood stickers' scripts load after the first paint from
minimoji-heads-bursts.js beside the bundle (vendor both files). Hint the
bundle early with <link rel="modulepreload" href=".../sdk/minimoji-heads.js">;
a head built from its JSON draws sooner than a baked .glb (several MB). For a
baked head, mountHeadPoster(el, { src: <the still> }) before
prepareBakedHead, then mountHeadPerformance(el, { bakedHead, poster }).
When you call prepareBakedHead yourself, the mount is synchronous and
only happens once the GLB is in, so the poster must go up first: call
const poster = mountHeadPoster(el, { src }), then
await prepareBakedHead(...), then pass that same handle as
mountHeadPerformance(el, { bakedHead, poster }). The still shows during
the download and hands off to the live head.
emotes={false} on a talking head, for the whole line: the line's strong mood
cues emote through cue, quiet ones (k under 0.35) only change
expression, gestures play through cue. expression is null between
lines, so yours applies.
Never hangs. If play() is refused (autoplay blocked), the audio
errors or its clock stalls (1.5 s; 4 s before it first moves), the line
carries on a silent clock: mouth and captions still run, and it ends.
The newest say wins (a generation token): it cuts the line before
it, and a late promise or event from the old one does nothing. stop()
and unmounting end it.
audio (with a prebuilt line): a URL (the hook makes and frees the
element), your own HTMLAudioElement (paused, never freed), or none (the
silent clock).
Captions: phrases by default — at most four words, broken after
punctuation, the word being said lit (data-lit) and staying lit through
the pause after it; the first phrase shows before the voice starts and the
last stays a second after it ends; a new phrase moves up. mode="window"
is the Kit 9.44 sliding window (about 7 words / 40 characters). Reduced
motion shows the whole line, still; maxLines={1} keeps it to a subtitle
slot (then an ellipsis). A screen reader hears the whole line once per
line (the moving words are hidden from it). Style the box with
className / style; it must survive 200% text.
Making a line ahead of time from your own audio and timed words (a
TTS provider's timestamps, dictation): buildLine({ pcm, sampleRate, words, mood }) from
@minimoji/react/line, offline (what say({ audio }) runs for you); packages/engine/dev/line-from-words.mjs
converts ElevenLabs-style { text, startMs, durationMs } words plus the
clips. Never derive mouth shapes from letters. mood sets the opening
face quietly (no emote burst at the start); audio tags in the words
([excited], [curious], [whispers]…) leave the captions and become
quiet face changes at their word (TAG_MOODS), [laughs] a laugh.
Directing the line: your own cues, a look, stage directions
A script can time the head to its words. clip.cues are your cues, merged
with the ones the SDK derives (a nod on "yes"…); at is seconds or a word
of the clip ({ word: 7 }, an index into the timed words from 0, or
{ word: 'card', nth? }). The stored line holds seconds. A word the clip
does not say fails the say, naming the word.
import type { RefObject } from 'react';
import { lookTargetFor, type LinePlayerApi } from '@minimoji/react';
// `line` is your useLine(); `words` your TTS provider's timed words; the refs your head's anchor and the card
export function present(line: LinePlayerApi, audio: string, words: { text: string; start: number; end: number }[],
anchor: RefObject<HTMLDivElement | null>, card: RefObject<HTMLDivElement | null>) {
line.say({ audio, words, cues: [
{ at: { word: 7 }, gesture: 'knowing-nod' },
{ at: 3.2, look: { x: .6, y: -.2 }, hold: 2 }, // eyes up-right for 2 s
{ at: { word: 'card' }, look: lookTargetFor(card.current!, anchor.current!) }, // at the card on the page
] });
}
| cue |
does |
{ at, mood, k? } |
a face (k under 0.35: quietly, no emote) |
{ at, gesture } |
one of the engine's tracks (knowing-nod, head-shake…) |
{ at, nod: true } / { at, shake: true } |
the face's own nod / shake |
{ at, brow: 'up' | 'down', k } |
a brow accent |
{ at, look, hold? } |
eyes on { x, y } (−1…1, + right / up), 'away' (aside, alternating sides) or 'viewer' (back to you), for hold s (1.2 by default), then the head's own gaze |
Tags in the words or transcript do the same with no code, and leave the
captions: [nod] [shake] [brow] [brow down] [look away]
[look back] [smile] (plus the mood tags, [surprised]…). An authored
gesture, brow or look within 0.6 s of a derived one replaces it. The look
rides in line.performance (and line.look), so the head needs nothing
new. lookTargetFor(el, anchorEl) turns two DOM rects into the { x, y }.
No line at all (a game's NPC, a party host): playCues(stage, cues, clock?)
plays the same cues (seconds from the start) on their own clock, through the
same dispatch. cueStage(head.life) is the stage for one head (onReady
hands you the head; give that <MinimojiHead> look="manual" so its own look
setting does not take the eyes back). With no clock it runs on timers; with
one (() => seconds) call tick() from your game loop. It returns
{ tick, stop, done }.
Driving the mouth yourself (your own clock)
For live or decoded audio with no line: mouthTrack turns samples into one
mouth per 1/60 s, and a performance you write reads your own clock:
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { MinimojiStage, MinimojiHead, mouthTrack, type GlossFace, type MouthFrame, type PerformanceInput } from '@minimoji/react';
// the clip, and the mood its word lands on (seconds into the clip)
const LINE = { audio: '/lines/dash-hey.mp3', cue: { at: 0.24, mood: 'happy' as GlossFace } };
export function DashSaysHey() {
const anchor = useRef<HTMLButtonElement>(null);
const audio = useRef<HTMLAudioElement | null>(null);
const frames = useRef<MouthFrame[] | null>(null);
const cued = useRef(false);
const [speaking, setSpeaking] = useState(false);
const [cue, setCue] = useState<{ mood: GlossFace; generation: number } | null>(null);
// decode the line ahead of the click: the click's play() must run inside the gesture
useEffect(() => {
let live = true;
const ctx = new AudioContext();
fetch(LINE.audio).then(r => r.arrayBuffer()).then(bytes => ctx.decodeAudioData(bytes))
.then(clip => { if (live) frames.current = mouthTrack(clip.getChannelData(0), clip.sampleRate); })
.catch(() => {}).finally(() => void ctx.close());
return () => { live = false; audio.current?.pause(); };
}, []);
// called by the head every frame while it speaks: one stable function, reading the audio's own clock
const perform = useCallback<PerformanceInput>(() => {
const a = audio.current, f = frames.current;
if (!a || !f || a.paused) return { active: false };
if (!cued.current && a.currentTime >= LINE.cue.at) {
cued.current = true;
setCue(c => ({ mood: LINE.cue.mood, generation: (c?.generation ?? 0) + 1 }));
}
const m = f[Math.min(f.length - 1, Math.floor(a.currentTime * 60))];
return { active: true, mouth: { open: m.open, width: m.width, round: m.round } };
}, []);
const say = () => {
if (!frames.current) return;
const a = (audio.current ??= new Audio(LINE.audio));
a.onended = () => setSpeaking(false);
a.currentTime = 0; cued.current = false;
a.play().then(() => setSpeaking(true), () => setSpeaking(false));
};
return (
<>
<button ref={anchor} type="button" aria-label="Say hi to D.A.S.H." data-minimoji="loading"
style={{ position: 'relative', width: 160, height: 160 }} />
<MinimojiStage>
<MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor}
emotes={false} cue={cue} performance={speaking ? perform : null} />
</MinimojiStage>
</>
);
}
- Keep the source's identity stable (
useCallback, a ref, a module
function) and read your own clock inside it (audio.currentTime). While
set it owns gaze, mouth, beat and blinks; expression and listening
stay yours. Set it to null when the voice ends: that releases the mouth.
- Feed every frame while the voice plays, silences included (the
track's rest frames); a mouth not refreshed for 0.3 s closes.
- The homepage precomputes the same frames offline (60 fps,
[open, width, round, level, pitch], plus captions and cues) so
nothing decodes on the page; mouthTrack in the browser is the same
mouth. Return { active: false } between lines: natural talk then
plans the glance back to the visitor.
- Optional snapshot fields:
voiceLevel (the arcs), mouth.pitch
(semitones off the speaker's median: natural talk's brows), blink and
drop (counters: bump to fire once), beat (the listening nod's clock).
- Live audio (a call, no recording): the engine's
createLiveVisemeTimeline and createSpeechVoice (not in this package
yet: ask Minimoji) are the web twins of the Swift Kit's
LiveVisemes and SpeechVoice: PCM in, a viseme and a level out, eased
into a mouth per head. Look-ahead (voice chat): delay the voice's
playout by 100 ms on your side and pass lookAhead: .1 to
createLiveVisemeTimeline (settable later as timeline.lookAhead): the
shapes lead the sound by 70 ms and the lips meet on m, b and p before
they are heard. Not where the speaker hears themselves (their own mic):
there it is only lag. It adds to playoutOffset. Without it a closure
shows as the voice comes back; a fading vowel never shuts the mouth.
Mouthing a streaming reply (no audio)
An agent's reply that arrives as silent text: the head mouths the words as
they stream in, paced like speech. Not useLine: a line is a finished clip
with a duration, and a stream has neither. No key and no network.
'use client';
import { useRef, useState } from 'react';
import { MinimojiStage, MinimojiHead, useTextMouth } from '@minimoji/react';
export function AgentReply({ stream }: { stream: () => AsyncIterable<string> }) {
const anchor = useRef<HTMLDivElement>(null);
const mouth = useTextMouth();
const [text, setText] = useState('');
const run = async () => {
mouth.cancel(); setText('');
for await (const token of stream()) { mouth.append(token); setText(t => t + token); }
mouth.finish();
};
return (
<>
<button type="button"
<div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 54, height: 54 }} />
<p>{text}</p>
<MinimojiStage>
<MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor} expression="happy"
performance={mouth.speaking ? mouth.performance : null} />
</MinimojiStage>
</>
);
}
- The pace is the hook's. About 15 characters a second, up to 1.5x when
behind. More than
lag behind the newest text it skips forward, at a word
boundary where there is one, to about 3/4 of lag behind; the last phrase is
still mouthed. So a long reply never leaves the mouth talking long after the
text has landed. After finish() the same rules run, then the mouth closes;
cancel() closes it at once. Text after that starts a new reply.
lag is your call: useTextMouth({ lag: 1 }), in seconds, default 1.5
(sized for a chat reply streaming at 10+ words a second: the mouth stays
within a phrase of the text and runs on about a second after it ends). It
trades closeness for letters: a smaller lag follows the text closer and skips
more of it; a larger one mouths more and trails further. It hurries from 3/8
of it. A change takes hold at the next reply; a non-positive or non-finite
value throws.
- Tokens can split anything: a word, a two-letter rule, an emoji. Hand them
over as they come; the last letter of a chunk waits for the next one.
- Send what you want mouthed. It does not strip markdown or code: symbols
take no time, but
const x = 1 is mouthed as text. Filter first.
- Faces stay yours:
expression and listening compose with it as with a
line, and the mood holds through the talking. Choose the mood yourself; it
reads none from the text.
- Gaze and blinks: it hands over a mouth and its loudness, and no blink
events. While
performance is set the look prop is not read: the head
glances about on its own (as during a line), or, with
useTextMouth({ look: { x, y } }) (-1..1, + x to the head's right, + y up),
looks where you say while it speaks. Its own blinks go on. Pass
mouth.speaking ? mouth.performance : null, as above, so look is back the
moment it stops.
- Reduced motion is a line's rule: the mouth still moves (it is direct
feedback), the head's natural motion and the stickers stop. Add no check.
- A caption that keeps up:
useTextMouth({ onSpoken: n => setShown(text.slice(0, n)) }),
or read mouth.spoken(). The count jumps forward over a skip.
- Your own frame loop:
createTextMouth({ lag }) from @minimoji/react
(append, finish, cancel, sample(dt)). With no React, on the vanilla bundle:
const reply = stage.speak('Hel'); reply.append('lo!'); reply.finish();
(reply.cancel(), reply.spoken, reply.speaking, stage.speak(text, id)
for a tile, and stage.speak(text, id, { lag }): the head keeps that lag
until another speak names one, and a reply already playing keeps its own).
The stage draws its own frames when you draw none.
Talking with your voice (live mic)
The person talks into their mic and the head's mouth follows, live. The
analyser runs in the page (the same live viseme analyser as MinimojiKit), so
there is no key, no network, and nothing is played, stored or sent.
'use client';
import { useRef } from 'react';
import { MinimojiStage, MinimojiHead, useLiveMic } from '@minimoji/react';
export function TalkAsYourAvatar({ avatar }: { avatar: object }) {
const anchor = useRef<HTMLDivElement>(null);
const mic = useLiveMic();
return (
<>
<button type="button" => (mic.live ? mic.stop() : mic.start())}>
{mic.live ? 'Stop' : mic.state === 'starting' ? 'Opening the mic…' : 'Talk'}
</button>
{mic.error && <p>{mic.error.code === 'denied' ? 'Allow the microphone to talk as your avatar.' : mic.error.message}</p>}
<div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }} />
<MinimojiStage>
<MinimojiHead avatar={avatar} anchor={anchor} expression="happy"
performance={mic.live ? mic.performance : null} />
</MinimojiStage>
</>
);
}
start() from a click or a key press. Browsers only run audio from a
user gesture, and Safari only from one made in the same tick: call it in the
handler, not after an await. It needs https:// (or localhost). The
hook's start() resolves true once live and false otherwise (no catch
needed): the failure is mic.error (and onError's), an Error whose
code is denied, no-device, busy (another app has the mic),
blocked (the browser kept audio off: not from a gesture), unsupported or
failed. Without the hook, start() and liveMic() reject with it.
A mic that goes away mid-talk stops it with ended
(mic.on('error', fn) hears every failure).
Voice processing is on: echo cancelling, noise suppression and auto gain
(LIVE_MIC_CONSTRAINTS). useLiveMic({ deviceId }) picks a mic from
enumerateDevices(), from the next start.
The head between words is its own: performance is the mouth while you
talk and inactive in the silences, so the gaze and idle carry on. Pass
mic.live ? mic.performance : null so look is back when it stops.
A meter: mic.level() is how loud the voice is now, 0..1; read it in
your own animation frame.
Unmounting stops the mic. Faces (expression, listening) compose with
it as with a line.
No React: createLiveMicSession() from @minimoji/react is the same
session (start, stop, performance(), level(), on). On the vanilla
bundle (/sdk/minimoji-heads.js on minimoji.com, once the site deploys):
import { mountHeadPerformance, liveMic } from 'https://minimoji.com/sdk/minimoji-heads.js';
const stage = mountHeadPerformance(el, { avatar });
talk.onclick = async () => {
const mic = await liveMic(); // from the click; rejects with a coded Error
stage.setPerformance(mic); // the head talks with your voice; the stage draws its own frames
stop.onclick = () => { mic.stop(); stage.setPerformance(null); };
};
stage.setPerformance(source, id) takes any live source (anything with
performance()); id picks a tile.
Change a head with the whirl (vanilla stage)
A look picker on the vanilla bundle changes the head with the phone's spin,
no remount:
await stage.swapAvatar(nextDoc, { id: 'guest' }); // id: the tile; omit on a solo stage
The old head stays until the new one is built, turns two turns and the new
one comes out of the last half turn on a spring (the same timing as
<MinimojiHead> and the Kit). It resolves when the whirl is over and the old
head is disposed. The head keeps its tile, mood, live source and mouthed
text. A second call mid-whirl ends on the newest look. Reduced motion trades
at once. setAvatar stays instant. On a stepped stage, step it, then await.
A new colour changes in place; only a new shape spins. whirl: false is the
instant change on any head, a tile too (the old head stays until the new one
is built, then the new one is drawn in its place; the promise resolves on the
next frame):
await stage.swapAvatar({ ...doc, skin: 'deep' }, { id: 'guest', whirl: false }); // colour, skin: no spin
await stage.swapAvatar({ ...doc, hair: { ...doc.hair, style: 'bob' } }, { id: 'guest' }); // a style: the whirl
An editor's lists come from the same bundle (and @minimoji/react), with the
same values: INVENTORY, optionsFor(doc, 'hair.style') (each value with
allowed), optionLabel(value) for a tile's words, swatchHex(path, value)
for a chip, HAIR_COLORS / HAIR_IDS, and normalize(doc):
import { mountHeadPerformance, optionsFor, optionLabel, swatchHex, HAIR_COLORS } from 'https://www.minimoji.com/sdk/minimoji-heads.js';
const styles = optionsFor(doc, 'hair.style').filter(o => o.allowed).map(o => ({ value: o.value, label: optionLabel(o.value) }));
const colours = HAIR_COLORS.map(c => ({ id: c.id, hex: c.hex }));
Emotes with speech
Two ways, pick one per head:
- The mood as an
expression: change expression and the head plays
that mood's emote on the change (one of three, never the same one twice in a row).
- Cued moods over a held face (what the homepage does):
emotes={false}
so expression changes play nothing, and cue={{ mood, generation }} at
the line's moments. A cue plays once per distinct value: bump
generation to play the same mood again.
A host that talks (onboarding, tours)
A character that says one line per screen: useLine plus a few rules. For a
whole onboarding or product intro the character presents (slides, a voiced
line each, bubble captions, steps that wait for a choice or a sign-in), use
the minimoji-presenter skill and its starter deck.
- One line per screen. Start it on appear after a 250–500 ms lead-in;
a tap on the head replays it. Pick lines at random, never the same one
twice in a row.
- Recorded audio plus its line (above). Mouth, cues and captions all
read one clock, the audio's, and
useLine falls back to its silent clock
on its own, so a blocked or muted start still moves the screen on.
- Cancel by generation, not by unmount:
say already does. A late
callback from an older screen's line does nothing, so an old screen's
cleanup can't cut the new line.
- Accessibility:
<MinimojiCaptions> announces each line once; make
the head a button labelled "Replay" and hide off-screen duplicate heads
from assistive tech.
- The audio's owner and the head can live apart: pass the
useLine()
value down, or hand { cue, expression, performance } to the head through
a small external store (useSyncExternalStore), as the homepage does.
- Load the host early, keep it mounted for the session, and show
MinimojiHeadPoster until it lands (section 3).
- A character like D.A.S.H. reads about 10% larger than a person in the
same anchor: size its anchor down a little.
- Never break the host. A missing clip, a line that won't parse, an
audio error: fall back to the still head or the silent clock
(
say(line) with no audio still moves the mouth and captions), log it
under one prefix, and never block the page on it.
- Own long-lived things once: the
useLine() player in the component
that stays mounted (or a module-level store), each line's JSON fetched and
parsed once per page load, not per render.
- Post-processing the provider's audio (a robot filter, a pitch shift)
must keep the exact duration: pad or trim back to the raw recording's
sample count, or every word timing drifts against the mouth and captions.
- Screen readers hear the line once (
<MinimojiCaptions> announces it),
never the captions word by word. Skipping the audio while a screen reader
runs is an option, not the rule.
- A host on a sign-in page (before auth): a character builds on the page
from its id, so it needs no key and no network beyond your own bundle:
ship its lines and clips with the page, and the form never waits on it.
'use client';
import { useEffect, useRef, useState } from 'react';
import { MinimojiStage, MinimojiHead, MinimojiCaptions, useLine, type SpeechLine } from '@minimoji/react';
export function OnboardingHost({ clip }: { clip: { audio: string; line: string } }) {
const anchor = useRef<HTMLButtonElement>(null);
const [data, setData] = useState<SpeechLine | null>(null);
const line = useLine();
useEffect(() => { fetch(clip.line).then(r => r.json()).then(setData).catch(() => {}); }, [clip.line]);
// the screen's line after a short lead-in (blocked autoplay plays it on the silent clock)
useEffect(() => {
if (!data) return;
const id = setTimeout(() => line.say(data, { audio: clip.audio }), 350);
return () => clearTimeout(id);
}, [data, clip.audio]); // eslint-disable-line react-hooks/exhaustive-deps -- say is stable per hook
return (
<>
<button ref={anchor} type="button" aria-label="Replay" data-minimoji="loading"
=> data && line.say(data, { audio: clip.audio })} style={{ position: 'relative', width: 120, height: 120 }} />
<MinimojiCaptions player={line} />
<MinimojiStage>
<MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor} emotes={false}
expression={line.expression ?? 'happy'} performance={line.performance} cue={line.cue} />
</MinimojiStage>
</>
);
}
5. Moods and gestures
'use client';
import { useRef, useState } from 'react';
import { MinimojiStage, MinimojiHead, GLOSS_FACES, type AvatarInput, type GlossFace } from '@minimoji/react';
export function Reacting({ avatar }: { avatar: AvatarInput }) {
const anchor = useRef<HTMLDivElement>(null);
const [face, setFace] = useState<GlossFace>('neutral');
const [cue, setCue] = useState<{ gesture: string; generation: number } | null>(null);
return (
<>
<div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 120, height: 120 }} />
<select value={face} => setFace(e.target.value as GlossFace)}>
{GLOSS_FACES.map(f => <option key={f}>{f}</option>)}
</select>
<button type="button" => setCue(c => ({ gesture: 'double-take', generation: (c?.generation ?? 0) + 1 }))}>Double take</button>
<MinimojiStage>
<MinimojiHead avatar={avatar} anchor={anchor} expression={face} cue={cue}
{ cancelled }) => { if (!cancelled) console.log('done', id); }} />
</MinimojiStage>
</>
);
}
expression is one of GLOSS_FACES (idle, an alias of neutral; neutral, happy, joy,
laugh, sad, angry, furious, surprised, worried, scared,
dead, smug, sleeping, crying, thinking). A change plays the
mood's emote unless emotes={false}.
- Stickers: a change to a mood also pops its comic stickers around the
head (a "!" for
surprised, sweat for worried, flames for angry,
hearts for happy…), as MinimojiKit does. On by default; bursts={false}
turns them off, and reduced motion shows none. Every mood above has them
but neutral/idle. They fire on a CHANGE: never the first face, never
the same face twice in a row, and at any strength (a line's quiet 0.3 cue
pops them too); a change to neutral lets them fade, and so does the end
of a line. Nothing to wire: a line's mood cues reach expression, so
useLine lines pop them at each cue. The PNGs load from
https://www.minimoji.com/emote-bursts/ (allow it in img-src), or
serve your own: the package ships them in emote-bursts/, so copy
node_modules/@minimoji/react/emote-bursts/ into your static folder
(public/emote-bursts/ in Next.js) and pass
<MinimojiStage burstBase="/emote-bursts/">.
- Face only:
decorations={false} (and decorations: false on the
vanilla bundle's mountHeadPerformance) shows no stickers (it overrides
bursts) and none of the rig's own effects: tears, sparkles, steam,
sleep Zs, notes, a screen face's effects. Expressions, blush, lip sync
(its sound arcs and lines too) and motion are unchanged. On by default.
- D.A.S.H.'s screen shows the mood on the whole glass (the LEDs, their
glow and the glass take the mood's colour: pink for happy, red for angry,
blue for sad; neutral is the theme's own), and its eyes change shape for
sad/crying/worried (a drooping arc), angry/furious (a slash) and
surprised/scared (a wide ring). Nothing to wire: expression drives it.
Its CRT look (scanlines and glass brightness that follow the mood) is
crt: 0 off, 1 (the default), 2 loud. crt={0} for a flat screen;
reduced motion keeps the scanlines dark. A head of skin ignores it. On the
vanilla bundle: mountHeadPerformance(el, { crt: 0 }); on a runtime,
life.setScreenCrt(level).
- D.A.S.H. as an agent (bake 19):
agentState makes his screen show what
an agent is doing. 'thinking' is a wave of three neon dots in his
theme's colours; 'working' is code flowing up a line every 0.35 s;
'needsYou' is one big glitching neon ! in place of his face; the rest
are his face in the state's colour on dark glass: 'waiting' (eyes up, a … mouth), 'done'
(a check that stays), 'errored' (> < eyes, a zigzag mouth, an RGB
glitch), 'asleep' (closed eyes). 'needs-you' works too. Each state
has its own colour; pass your app's with screenColor="#ff9f43" (and
screenGlass: about .3 keeps the glass dark so only the face lights,
2.2 floods it). null (the default) leaves the screen exactly as it
was. Vanilla bundle:
mountHeadPerformance(el, { agentState: 'working' }), then
stage.setAgentState('done') / stage.setScreenColor('#4ade80', { glass: .3 });
on a runtime, life.setAgentState(state, { color, glass }) and
life.setScreenColor(hex, { glass }).
- Connecting with progress:
agentState="connecting" plus
agentProgress={0.5} turns D.A.S.H.'s screen into a 16 × 8 dot matrix, a
mint wave scrolling over a yellow progress bar you fill, 0..1 (clamped;
it eases to each new value; null shows only a pulse at its start). Send
discrete steps (0, .25, .5, .75, 1) as your connect steps finish; don't draw
your own bar under him. On a runtime, life.setAgentProgress(v) and
life.setAgentState('connecting', { color, barColor }) (color the wave,
barColor the bar). Every bake 19 Dash shows it, a lite: 'agent' one too;
any other head thinks, as for 'thinking'. With performances: false
(reduced motion) the wave holds still and the bar still follows the value.
- Agent states on every head:
agentState works on every Mini avatar, not
only D.A.S.H. A head without a screen (a person, an animal, the ghost, the
penguin) shows the state with its own face and one held sticker beside it,
in the state's colour (or yours, from screenColor): 'thinking' the
thinking face and a thought bubble; 'working' the happy face typing on a
small keyboard in front of it, real code flowing up behind the head
(monospace, syntax-coloured, a line every .35 s, still while it thinks), and
every few seconds a look up and aside with the bubble; 'needsYou' surprised with
one ! standing behind the head; 'waiting' a glance up and a clock in a thought bubble; 'done' a nod and a check behind the head that stays; 'errored' X eyes, a head shake every 3 s and a ✕ in a thought bubble; 'asleep' the gentle asleep pose with Zs rising beside it. Clearing it hands back
the neutral face. Same prop, same stage.setAgentState / life.setAgentState;
life.agentStickers() is what the sticker layer draws (decorations={false}
draws none). Runtime only: any bake works.
- The code flow follows your theme:
theme="light" | "dark" on
<MinimojiStage> (every head) or <MinimojiHead> (that head; it wins) gives
the code deeper ink on a light surface and brighter neon on a dark one.
null (the default) follows the page's prefers-color-scheme, so set it
whenever your app's theme can differ from the system's (an in-app toggle).
Under about 40 css px each line draws as one coloured bar per token, since
glyphs that small speckle. Vanilla bundle: mountHeadPerformance(el, { theme: 'dark' }),
then stage.setTheme('light').
cue={{ gesture }} plays one named track over the face as it is (the
face never changes): double-take, head-shake, sunny-nod,
knowing-nod, ponder-tilt, side-eye-hmm, lightbulb, … (the
engine's authored tracks). cue={{ mood }} picks one of that mood's
three. One shot only: chain the next from onGestureEnd, which always
comes (cancelled when replaced, the next frame under
performances={false}).
- To time moods, gestures and looks to a script (or play them with no audio
in a game), see "Directing the line" in § 4:
clip.cues, the [nod]-style
tags and playCues.
performances={false} stills every one-shot, cues included (reduced
motion). To cue your own gestures over a beat, pass emotes={false},
not performances={false}.
- A face you set for bookkeeping (a mood lapsing back to neutral, a
mute, a reset) goes with
emotes={false} in the same render; a face the
person picked goes with emotes={true}. emotes is live, never a
rebuild, and is read on the next expression change, so the lapse changes
the face with no emote. Cues still play, and one already
playing plays on. Stickers are bursts's: a lapse to neutral pops none;
to a mood that has one, pass bursts={false} on the same render.
- A mood from text:
POST <service>/expressions/pick with
{ text, gesture: true } answers expression (null: keep the face) and
a gesture. Ask on a typing pause, never per keystroke.
Poke and drag
'use client';
import { useRef } from 'react';
import { MinimojiStage, MinimojiHead, type AvatarInput, type MinimojiHeadHandle } from '@minimoji/react';
export function Pokeable({ avatar }: { avatar: AvatarInput }) {
const anchor = useRef<HTMLDivElement>(null);
const head = useRef<MinimojiHeadHandle>(null);
return (
<>
<div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }} />
<button type="button" => head.current?.react('giggle')}>Tickle</button>
<MinimojiStage>
<MinimojiHead ref={head} avatar={avatar} anchor={anchor}
interactive={{ poke: { reactions: ['oof', 'ah', 'flinch', 'dizzy'] }, drag: { maxPx: 60 }, label: 'Poke Dash' }}
reaction }) => console.log('poked:', reaction)}
distance, flung }) => console.log(distance, flung)} />
</MinimojiStage>
</>
);
}
interactive is off by default (no listener is attached); interactive alone (true) turns on both
poke and drag. Only the head's skull counts: a press anywhere else in the anchor goes to the page.
- A poke plays a reaction:
oof (squash + wince), ah (surprised hop back), flinch (recoils away from
the poke), giggle (laugh + shake) or dizzy (× eyes + wobble). Never the same one twice in a row, one
at a time with a short cooldown. poke.reactions replaces the pool (unknown names warn once, skipped).
- It works idle, paused or mid-line: the face changes for a moment and lip-sync carries on under it. A poke
never stops a line: pause it yourself from
onPoke if you want to. No sound ships: play your own there.
- A drag pulls the head on a rubber band (toward
drag.maxPx, 80 css px, never past), tilted toward the
pull; it springs back with a wobble. A fast release is a fling and plays dizzy. A touch that starts on
the head drags it instead of scrolling the page; anywhere else the page scrolls as usual. A head painted
into its own anchor is cut at the anchor's padded box, so its drag stops there; give a group a
data-minimoji-surface frame for more room.
ref.current.react(name?) plays one from code (with no name, one from the pool), interactive or not,
and answers what played (null for an unknown name). React 19 passes ref as a prop.
- Events:
onPoke({ reaction }), onDragStart(), onDragEnd({ distance, flung }).
- The anchor becomes a button (
role="button", focusable, label as its name, default "Poke the
avatar"): Enter or Space pokes it. Under reduced motion nothing moves; the faces still change.
- The vanilla bundle (
/sdk/minimoji-heads.js) takes the same interactive, onPoke, onDragStart and
onDragEnd options on mountHeadPerformance, and its stage has react(name?, id?).
6. Listening, presence and thinking
'use client';
import { useEffect, useRef } from 'react';
import { MinimojiStage, MinimojiHead, type AvatarInput, type Head } from '@minimoji/react';
export function Friend({ avatar, online, typing, music }: { avatar: AvatarInput; online: boolean; typing: boolean; music: boolean }) {
const anchor = useRef<HTMLDivElement>(null);
const head = useRef<Head | null>(null);
// presence and thinking are on the head's face api, not props: apply them when the head lands and on each change
const apply = (h: Head | null) => {
if (!h) return;
h.life.setPresence(online ? 'online' : { state: 'asleep', z: true });
h.life.think(typing);
};
useEffect(() => apply(head.current));
return (
<>
<div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 96, height: 96 }} />
<MinimojiStage>
<MinimojiHead avatar={avatar} anchor={anchor} listening={music ? { tempo: 96, mouth: 'hum' } : null}
=> { head.current = h; apply(h); }} />
</MinimojiStage>
</>
);
}
listening composes with any expression (a sad head nods sadly): a nod
on tempo, notes rising; notes: false keeps the nod alone. A host
with its own beat feeds beat through performance; drop (a counter)
fires the bigger nod and a burst of notes.
setPresence: 'online', 'asleep' (eyes shut, slow breath; z: true
lies it down with Zs), 'party' (a bounce on the beat). Leaving asleep
plays the wake-up. { state: 'asleep', z: true, roll: ASLEEP_GENTLE_ROLL }
(exported, 16° in radians) stops the head at a gentle roll instead, the Zs
upright and the snore kept; the matching still is .png?face=asleep (no Zs).
A presence set as the head lands (in onReady, as above; within its first 0.25 s) is its
mount presence: asleep at once, no doze-in. A later change eases.
think(true): the typing state, a thinking face with a looping tilt;
any speech takes the mouth at once.
onReady hands you the Head (and again after the avatar changes);
head.life is the whole face api (FaceApi in index.d.ts).
7. Bodies
@minimoji/react draws heads only. The homepage's full-body tile is the
engine's own stage, with the site's own assets, and is not a public web API
yet. For bodies in an app use
the Swift Kit's MinimojiBody, or ask Minimoji.
8. Many heads on a page
- One stage, every head in it. Heads build one per animation frame, in
mount order, and scale in as they land (
rest heads, or land={false}:
at their final size from the first frame); scrolling holds builds back.
- Lower
detail (.8 on the homepage) before anything else.
- Under 48 px a head wears the compact arcs by itself; nothing to do.
- A group sharing a floor:
shadow={false} on each head and one
<MinimojiShadow anchor={…} /> under them.
- Respect
prefers-reduced-motion: pass drift={false},
performances={false} and look={null} (the homepage does). The
package already drops natural motion and screen effects under it.
- A changed
performances, naturalTalk, drift or character rebuilds
the head: set them once, not per frame. emotes is live (no rebuild). A changed avatar whirls the new head in.
- One voice at a time: stop the other heads' audio when one starts.
Status heads in an app's chrome (rest)
A crew rail, pane pills, a sidebar of agents: small heads that sit open all
day and should cost nothing while nothing happens. Put rest on each one.
'use client';
import { useRef, type RefObject } from 'react';
import { MinimojiStage, MinimojiHead, type AgentState } from '@minimoji/react';
type Agent = { id: string; name: string; theme: string; state: AgentState | null };
export function CrewRail({ crew }: { crew: Agent[] }) {
const anchors = useRef(new Map<string, RefObject<HTMLDivElement | null>>());
const anchor = (id: string) => {
if (!anchors.current.has(id)) anchors.current.set(id, { current: null });
return anchors.current.get(id)!;
};
return (
<>
{crew.map(a => (
<div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div ref={anchor(a.id)} style={{ width: 30, height: 30 }} />
{a.name}
</div>
))}
<MinimojiStage>
{crew.map(a => (
<MinimojiHead key={a.id} avatar={{}} character={{ id: a.theme }} anchor={anchor(a.id)}
agentState={a.state} rest shadow={false} bursts={false} />
))}
</MinimojiStage>
</>
);
}
theme is a D.A.S.H. id: agent, dashGold, dashRose, dashOcean, …
- A resting head is there when the window is: drawn at its final size from
its first frame (no scale-in), and a changed
avatar or character takes
its place at once (no whirl). land overrides it either way. Ten cold
D.A.S.H. heads: the first drawn about 0.6 s after the stage mounts, all ten
by about 1 s (Chrome, a busy dev machine; 2.9 and 7.4 s before 19.2.0). The
first D.A.S.H. on a page builds in about 0.2–0.35 s (its plates extruded,
after the renderer's setup); the rest of a burst about 50–120 ms each.
- A resting head is built without its breath and drift and looks straight
out of its tile (
look as {x,y} or 'manual' still applies). A change
(agentState, expression, screenColor, a cue, talking, a resize) is
drawn, plays out for about a second and a half, and is held.
- When every head on the stage is held, the stage asks for no animation
frame and issues no WebGL draw at all until something changes. Ten idle
D.A.S.H. heads: 0 frames and 0 draws, against 120 rAF/s and ~12% of a
main thread without
rest.
'thinking' and 'working' are patterns: a head showing one keeps the
stage drawing while it does, and only that head is drawn: the held heads
beside it are left out of the render and keep their pixels. A small one
(anchor ≤ 56 px) draws at the stage's restFps (default 15; at most 30),
with no animation frame asked for in between. One working 30 px head
among nine at rest: about 2% of a main thread in Electron (1.9–2.5%
across runs), against 13.6% without rest. For margin, set
<MinimojiStage restFps={12}>: about a fifth less (0.4–0.5 points);
15 is the rate the patterns were checked at. Every other agent state is held at a clean moment of its screen
(the ! lit, the check without its sparkles, the … full).
- What wakes a held stage: a prop change, a scroll (the page's or a box
inside it), a window resize, an anchor resized or scrolled into view, an
ancestor's transform transition or animation, a device-pixel-ratio change,
a poke,
resize() on the stage's ref. Nothing else; the pointer does not.
Woken, it draws until every anchor's size stops changing, so a head is
held at the size it lands on, never one it passed through.
- Held only when the head has a canvas of its own (the default
surfaces,
its anchor not inside a data-minimoji-surface); otherwise it keeps
drawing. Driving head.life yourself (think, setPresence, lookAt)
announces nothing: call ref.current.wake() after.
rest is opt-in at any size, and set once: changing it rebuilds the head.
Without it heads breathe, blink and glance exactly as before.
shadow={false} on every head (and no <MinimojiShadow>) also skips the
stage's shadow pass while it draws.
- Electron: works with
contextIsolation, sandbox and a strict CSP,
from file:// or a custom protocol, no unsafe-eval:
default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'.
A D.A.S.H. head needs no network. Only the comic stickers fetch (images
from https://www.minimoji.com/emote-bursts/ on a mood change): pass
bursts={false}, add that origin to img-src, or serve the package's
emote-bursts/ folder yourself with <MinimojiStage burstBase>.
A baked head (a bake's GLB, no avatar document)
When you hold a bake rather than a document (GET /avatars/<key>.glb, or
bytes your server stored), draw it as it is. A small one comes as
?detail=.25&lite=1 (no effect plates); for a D.A.S.H. you drive with
agentState, ask lite=agent (POST /avatars/bake {lite: "agent"}):
lite, but it keeps his agent screens, which lite=1 leaves out (MinimojiHead
builds from the document and always has them):
import { prepareBakedHead, buildBakedHead } from '@minimoji/react';
const prepared = await prepareBakedHead({ url: glbUrl, sha256 }); // or bytes; once per file
const head = buildBakedHead(prepared, { gaze: false }); // as many as you need
The vanilla bundle takes it as mountHeadPerformance(el, { bakedHead: prepared })
(also per tile, tiles[i].bakedHead), mountBakedHeadPerformance(el, { bakedHead }),
and stage.setBakedHead(prepared). prepareBakedHead checks the file before
parsing it (data only: no images, textures, external buffers or extensions
beyond four material ones; 32 MB at most; the bundle's own bake version) and
rejects a bad one; there is never a stand-in head. A URL is fetched with
same-origin credentials (http(s) or a /path; pass bytes otherwise); account checks are your server's. Each head from one
prepared file owns its geometry and materials; prepared.dispose() frees only
the template.
A packed character's colours (recolour by slot)
A character pack (minimoji characters pack) declares colour slots; each look's file says which
parts wear each slot. prepared.slots is that map ({ shell: ['body', …], trim: [] }, or null
for a file with none: its colours are fixed). Recolour live, no reload:
const stage = mountBakedHeadPerformance(el, { bakedHead: prepared, colors: { skin: '#9b5de5' } });
stage.setColors({ trim: '#ffcc00' }); // instant
stage.setBakedHead(nextLook, { colors: current }); // another look of the same character
buildBakedHead(prepared, { colors }) and setBakedHeadColors(head, colors) do the same on a
head you mount yourself. They throw on an unknown slot or a colour that is not #rrggbb; a slot
that is empty on this look changes nothing. An editor for a character's looks and colours is the
minimoji-editor skill.
Recording a video frame by frame (no GPU needed)
To export a head to video (an MP4 of a narrated deck, recorded in headless
Chromium where WebGL runs on SwiftShader at a few fps), put the stage on a
stepped clock. It then runs no loop of its own and reads no wall clock:
nothing moves and nothing draws until you call step(dt), each step moves
every clock the head has (blinks, breath, emotes, stickers, cues, a line) by
exactly dt seconds and draws one frame into the normal canvas, and the same
seed and the same calls draw the same frames every run, however slow the
recorder is between steps.
'use client';
import { useEffect, useMemo, useRef } from 'react';
import { MinimojiStage, MinimojiHead, useLine, createManualClock, type SpeechLine } from '@minimoji/react';
export function Recorder({ line, onFrame }: { line: SpeechLine; onFrame: (i: number) => Promise<void> }) {
const anchor = useRef<HTMLDivElement>(null);
const clock = useMemo(() => createManualClock({ seed: 7 }), []); // the dice: same seed, same blinks
const talk = useLine({ clock }); // the line runs on the steps, with no sound
useEffect(() => {
let stop = false;
(async () => {
await clock.ready; // the head built, its sculpted parts and the stickers loaded
talk.say(line); // mux the line's audio into the video yourself, starting at this frame
for (let i = 0; i < 300 && !stop; i++) { clock.step(1 / 30); await onFrame(i); }
})();
return () => { stop = true; };
}, []);
return (
<>
<div ref={anchor} style={{ position: 'relative', width: 360, height: 360 }} />
<MinimojiStage clock={clock}>
<MinimojiHead avatar={{ seed: 4821 }} anchor={anchor} emotes={false}
expression={talk.expression ?? 'neutral'} performance={talk.performance} cue={talk.cue} />
</MinimojiStage>
</>
);
}
The vanilla bundle (/sdk/minimoji-heads.js, what a recorder page uses):
import { mountHeadPerformance, createVoicedPerformance, createManualClock } from './minimoji-heads.js';
const stage = mountHeadPerformance(el, { avatar, clock: createManualClock({ seed: 7 }), poster });
const voice = createVoicedPerformance({ stage, loadTimeline }); // no createMedia: the line runs on the stage's clock
await voice.select({ timeline: '/lines/hey.timeline.json', audio: '/lines/hey.mp3' });
await stage.ready; // parts, the sticker file (minimoji-heads-bursts.js) and sprites; the poster leaves
voice.play(); // no sound: the line starts on the stage's clock, here
for (let i = 0; i < 300; i++) { stage.step(1 / 30); await recordFrame(stage.capture()); }
One timebase with your own captions: give createMedia a silent
element whose currentTime is your recorder's clock, and the line follows
that element (voice.timebase === 'media'): its currentTime, paused
and ended are the truth, exactly as live, and the steps draw it. Without
createMedia the line runs on the stage's clock ('clock'), and
voice.time / voice.playing are its time for your captions. Pause, stop
and replay work in both, per performance, with several stages on one clock.
step(dt) draws synchronously, inside the call, and reads no
performance.now, Date.now, timer or animation frame: a recorder that
patches those to its own tick can step and screenshot.
Audio: a line on a stepped clock never plays (no element is made for
a URL, a host's element is never played). Mux the clip into the video
yourself, offset to the frame you started the line on.
The seed deals every head's dice on the clock: when it blinks, where
the eyes glance, which emote of a mood plays, a poke's reaction. Two
recordings match only with the same seed, so derive it from a stable id
for the content (a deck's id, a slide's id plus the speaker), never from
location, a URL or a served path: a server that serves each run under a
fresh prefix gives every run other blinks.
Wait for ready (clock.ready, or stage.ready on the vanilla stage)
before the first step you keep: lazy loads (a sculpted cut, the sticker
file and its PNGs, a line being loaded or built) land on the wall clock, and
a frame stepped before them would draw without them. Selecting a line
while you record (the next slide's)? Await clock.ready before every
step: the line's load is held on the clock, so it then starts on the same
step every run. Hold a load of your own the frames wait on with
clock.hold(promise, 'what it is').
ready rejects when a load failed (the sculpted parts, a line), with
an Error naming each (error.failed), reported once, so a retry reads a
clean ready. Stickers are decoration: a failed sticker file only warns.
The first frame is drawn at ready (vanilla stage): the canvas holds
the head as mounted, with no step, so a page screenshot before your first
step shows it. On the vanilla stage step(0) only redraws the frame as
it stands (nothing moves, no line ticks, no dice), so it never changes
the frames that follow.
Your own media as the timebase: its currentTime is read snapped to
10 µs on a stepped stage, so float noise in a host clock (a page clock
frozen at another wall time each run) cannot tip a step that lands on a
line's frame edge into the next frame.
The poster stays until stage.ready resolves, then leaves at once
(no fade, no puff). A frame stepped before ready records it under the
head: only do that if you want it.
Your own object as the voice's stage (one that forwards the calls,
or a head you mount again after a lost WebGL context):
voice.attach(stage) points the voice at the stepped stage's clock and
drive, and again at the new stage after a remount; the line goes on from
where it was. The calls still go to the object you made it with.
stage.capture() answers the frame just drawn as ImageData, stickers
included, with the stage's transparency (flatten it on your background).
React: yield between steps (await your frame capture, or
await new Promise(r => setTimeout(r))). A line's face and cues reach the
head as props, and React commits them between tasks: steps run back to back
in one task would skip them. The vanilla stage needs no yield.
frame/idleFrame on a stepped vanilla stage only set what the next step
draws; a stepped stage follows no pointer, and its heads open on
themselves (no landing). A live stage is unchanged: leave clock off.
9. Keys
Drawing a head needs no key. A key is for the service's HTTP API
(Authorization: Bearer <key>):
- A publishable key (
mk_pub_…) may ship in the browser: it bakes
heads, generates avatars from a selfie or a sentence, picks moods.
- A secret key (
mk_sec_…) never reaches the browser: saving an avatar
(POST /avatars) is your server's call with it.
- The service URL is the deployment's
.convex.site origin, never
.convex.cloud.
Several heads from one selfie
POST /avatars/generate with a publishable key makes a document from a
selfie (image: base64 JPEG or PNG, downscaled to a 1024 px long edge) or
a sentence (prompt). Add candidates (2–6) to get several likely heads to
let the person pick from, at no extra cost: one call, one generation of the
day's quota.
const res = await fetch(`${serviceUrl}/avatars/generate`, {
method: "POST",
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
body: JSON.stringify({ image: base64Jpeg, candidates: 4 }),
});
const { doc, candidates, candidateSource } = await res.json();
// candidates: [{ doc, score, differs }], best first; candidates[0].doc equals doc.
// differs: ["hair.style"], the paths a head changes from doc (for a label);
// score: its likelihood among these heads (they sum to 1).
// candidateSource: "decisions" (runner-ups of the read) or "single" (doc is the only head).
Render each candidate.doc with <MinimojiHead avatar={candidate.doc} />.
A sure read may offer fewer heads than asked; without candidates the
answer is {doc, notes, changes, usage} as before.
Getting a key with npx minimoji
In the app's folder:
npx minimoji login # prints a code and a link; the person approves it in the browser
npx minimoji init --with-skill # mints a publishable key, writes .env.local, installs this skill
init writes NEXT_PUBLIC_MINIMOJI_KEY and NEXT_PUBLIC_MINIMOJI_SERVICE_URL
(VITE_… in a Vite app) to .env.local and never writes a secret key. A
secret key for your server: npx minimoji keys create --kind secret.
Without the CLI, mint keys at minimoji.com/developers/keys.
Signed in, npx minimoji generate "red curls" --name kai keeps the avatar in
the account's library: npx minimoji avatars lists it on any machine, and
npx minimoji avatars get kai prints its avatarKey for the app to show.
npx minimoji edit kai "make the hair blue" (or --photo me.jpg) changes
it: the name follows the edit to a new avatarKey (the first line it
prints; --json gives avatarKey and previousKey), and --as kai-blue
keeps the edit as a new entry instead.
An app showing a hard-coded key keeps the old look until you update the key.
npx minimoji voice kai 21m00Tcm4TlvDq8ikWAM gives a library avatar an
ElevenLabs voice (--effect robot for D.A.S.H.; --list shows your voices),
and npx minimoji say kai "[excited] Hi, I'm Billie" makes the line, one
ElevenLabs call on the developer's own key (ELEVENLABS_API_KEY, which is
never sent to Minimoji): minimoji-lines/hi-i-m-billie.json plus a .wav.
That JSON is a prebuilt line, played with line.say(line, { audio: '/lines/hi-i-m-billie.wav' }). Never hand-roll TTS timestamps
into a line: say already ran buildLine on them.
Use my Minimoji: a person's own avatar
A person with a Minimoji account (minimoji.com/me) can bring their avatar
to your app. You never ask for their email: they pick one on minimoji.com
and your app gets that pick. The host's three lines:
import { MinimojiConnectButton, loadMinimojiGrantHead, prepareBakedHead, refreshMinimojiGrant } from '@minimoji/react';
// 1. show the button; the popup opens on the click
<MinimojiConnectButton minimojiKey={process.env.NEXT_PUBLIC_MINIMOJI_KEY} service={process.env.NEXT_PUBLIC_MINIMOJI_SERVICE_URL}
grantId, avatarKey }) => saveForUser({ grantId, avatarKey })} /> // 2. store both against your user
// 3. on launch, follow their edits and re-picks; null means they disconnected your app
const now = await refreshMinimojiGrant({ service, key, grantId }); // { grantId, avatarKey, status, character } | null
- One live grant per app and person: connecting again (another device, or the person reconnecting) replaces the grant, and the old id answers 410. On a 410, re-read the grant you stored before clearing it; another device may have saved a new one.
- Refresh on the device at launch, not from your server for every user: the grant routes are limited per key and caller address.
- The key is your app's publishable key; its label (set at
minimoji.com/developers/keys) is the app name the person sees, so name it
after the app.
useMinimojiConnect({ key, service }) gives { connect, connecting, error }
for your own button. connect() resolves null on "Not now", on expiry, or
when the popup is closed without an answer.
- Show the head with
<MinimojiHeadPoster src={${service}/avatars/${avatarKey}.png?size=256} />
and fetch ${service}/avatars/${avatarKey}.json to draw it live.
- A private character as their avatar. At minimoji.com/me the person can
pick one of their own private characters (made with
minimoji characters)
for your app. The refresh then carries character: { id, name, revision, bakeVersion, speech, sha256 } (null otherwise) and avatarKey stays their
Mini avatar. The character's file is private, so there is no public URL:
fetch it from the grant with your key and load it like any baked head:const now = await refreshMinimojiGrant({ service, key, grantId });
const bytes = now?.character ? await loadMinimojiGrantHead({ service, key, grantId }) : null; // GET /connect/grants/<id>/head
if (bytes) {
const head = await prepareBakedHead(bytes, { sha256: now.character.sha256 });
// mount `head` as you mount any prepared baked head
} // else show avatarKey as before (no character, or it came off between the two calls)
Pass etag: lastSha256 to get 'unchanged' (a 304) while it is the same;
null means it is no longer worn (switched back, archived, deleted). If
the head changed between the refresh and the fetch, the sha256 check fails:
refresh again, and show avatarKey meanwhile. Never cache
the bytes anywhere shared, and never send them on: they are the person's.
An app on an older SDK keeps showing the Mini avatar, and /me tells the
person so.
- An avatar made in your own editor, which your server saves with
POST /avatars: addToMinimojiLibrary({ service, key, grantId, avatarKey })
puts it in their library and picks it for your app (a 403 if they said no
to that on the sheet).
Upgrading an old document
Editors write v3 documents. If your server refuses a write below the stored
version, upgrade a v1/v2 document before saving it; never hand-stamp v: 3
(v2+ dropped some v1 rules and redraws a few parts):
import { upgradeAvatar } from '@minimoji/react';
const { doc, effects, changes } = upgradeAvatar(oldDoc);
// doc.v === 3 and it draws the head oldDoc drew; the rest stays as sparse as it came
// effects: the rules whose fallbacks were written in ({ id, reason })
// changes: [{ path: 'freckles' | 'facialHair', reason }] — v2 redrew v1 freckles and facial hair; usually empty
A v3 document (or an unknown version) comes back as the same object; it
never throws for a version and never downgrades. The Kit's
MinimojiDocument.upgraded(_:) gives the same answer.
Their status: the line beside their head
What the person types or says on the Minimoji app's you screen (or sets with
npx minimoji status kai "back at 3") is their avatar's status, and it comes
with the grant: refreshMinimojiGrant answers status: { text, mood, gesture, setAt }, or status: null when there is none. The mood was read once, on
Minimoji's side, so every app shows the same face: never send text to
/expressions/pick again.
import { MinimojiStatusBubble, refreshMinimojiGrant } from '@minimoji/react';
// on focus, and every 30 s while the head is on screen (a status changes without a re-pick)
const grant = await refreshMinimojiGrant({ service, key, grantId });
const status = grant?.status; // { text: 'on a deadline', mood: 'thinking', gesture: 'ponder-tilt', setAt } | null
<div style={{ position: 'relative' }}>
<div ref={anchor} data-minimoji="loading" style={{ width: 120, height: 120 }} />
{/* the tail's tip is the bubble's bottom-left: put it just above and right of the head */}
<MinimojiStatusBubble text={status?.text} size={14} style={{ position: 'absolute', left: '60%', bottom: '85%' }} />
</div>
<MinimojiHead avatar={avatar} anchor={anchor} expression={status?.mood ?? 'neutral'}
cue={status?.gesture ? { gesture: status.gesture, generation: status.setAt } : null} />
<MinimojiStatusBubble text size tail> is Bunch's bubble (cream, Lilita
One, two lines at most, a 3° tilt); size is the text's px (Bunch draws
11, 14 and 22), tail={false} drops the tail. No text draws nothing. Load
Lilita One yourself (Google Fonts) or it falls back to a rounded system font.
mood is a face name for expression (null when the read was unsure:
keep the face). gesture is a track for cue (null: none); with
generation: status.setAt it plays once per new status, not on every poll.
setAt is epoch ms: say "2h ago" if you like.
- No React? The heads bundle (
/sdk/minimoji-heads.js) has
mountStatusBubble(element, { text, size, tail }) → { update, destroy }.
A status may carry an optional voice (url, durationMs, words, and optional
letters: {characters, starts, ends}). Download the clip and play it with the
line player using these timings, without transcription. In Swift use
try voice.line(audioFile: downloadedURL), then MinimojiLinePlayer.say;
on the web use lettersFromAlignment when building the line. Partner apps
choose their own play control. These clips are public URL media.
10. Never do
- Never hand-draw or keyframe talking, blinking or emoting: feed speech
(section 4), set
expression, send a cue.
- Never put a
<div> (or any DOM) inside <MinimojiStage>; anchors live
outside it.
- Never mount a second stage for more heads, or one stage per head.
- Never draw your own loading placeholder:
MinimojiHeadPoster.
- Never pass a new
performance function every render, and never drive
the mouth from wall-clock time: read the audio's clock.
- Never send audio to the service; only text goes to
/expressions/pick.
- Never ship a secret key, or the
.convex.cloud URL, to the browser.
- Never store an avatar document as the user's identity: store the
avatar key from
POST /avatars.
- Never reach for the engine itself: it ships bundled and minified inside
this package, and only
@minimoji/react and its /characters, /line
and /clip subpaths are public.
11. Swift twin
The same heads, moods, cues, speech and loader exist in Swift: the
minimoji-swift skill (MinimojiKit). cue={{ gesture: 'double-take' }}
is HeadCue(.gesture(.doubleTake)); mouthTrack is the recorded twin of
LiveVisemes + SpeechVoice.
1---2name: minimoji-web3description: Add Minimoji 3D avatar heads to a React or Next.js web app with @minimoji/react — use when asked to "add Minimoji" to a web page, show a Mini avatar head or a c4---5---6name: minimoji-web7description: Add Minimoji 3D avatar heads to a React or Next.js web app with @minimoji/react — use when asked to "add Minimoji" to a web page, show a Mini avatar head or a character (D.A.S.H., an alien, an animal, the penguin, the ghost), make a head talk with lip-sync and emotes from audio or a recorded line, cue a mood or gesture, show the head's loader, or get a Minimoji key for a web app.8---910# @minimoji/react: Minimoji heads in a web app1112`@minimoji/react` draws **live Minimoji heads in the browser**: one13`<MinimojiStage>` per page (a WebGL canvas), and `<MinimojiHead>`s placed14over ordinary DOM elements (their **anchors**). A head is built on the page15from its avatar JSON or a character id: drawing one fetches nothing and needs16no key. The head already blinks, breathes, glances, emotes on a mood change,17lip-syncs what you feed it and talks naturally while it does; build on that,18never redraw it.1920This file is the rules and the smallest snippets. Every `tsx` snippet here is21typechecked against the package's `src/index.d.ts` by a test in the Minimoji22repo, so it compiles against the version you have. The full API is23`src/index.d.ts` and `README.md` in the package. The minimoji.com homepage is24the reference integration: its hello row and cast conversation are built25exactly as section 4 shows.2627## 1. Install2829`@minimoji/react` is on npm, with its peers:3031```sh32npm install @minimoji/react react@19 react-dom@19 three@0.160 @react-three/fiber@933```3435In the Minimoji monorepo it is `"@minimoji/react": "workspace:*"`.3637- It is plain ESM with types, no build step. In Next.js it renders on the38 client only: put `'use client'` on the file that mounts the stage.39- WebGL: a stage needs a browser. Server-render the anchors and the poster40 (section 4), never the stage.41- What it fetches by default: the engine is inside the package, so a head42 draws with no network beyond what you point it at, but for two things from `https://www.minimoji.com` (allow43 them in a strict CSP): a sculpted haircut or hat's mesh from `/sdk/parts/`44 (`connect-src`; if it fails the head draws a hand-made fallback) and the45 mood stickers' PNGs from `/emote-bursts/` (`img-src`, or serve your own,46 section 5).4748## 2. One head4950```tsx51'use client';52import { useRef } from 'react';53import { MinimojiStage, MinimojiHead, type AvatarInput } from '@minimoji/react';5455// the same JSON the avatar service and the Swift Kit take; the same document is always the same head56const me: AvatarInput = { seed: 4821, head: 'round', skin: 'brown', hair: { style: 'afro', color: 'ink' } };5758export function Me() {59 const anchor = useRef<HTMLDivElement>(null);60 return (61 <>62 <div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }} />63 <MinimojiStage>64 <MinimojiHead avatar={me} anchor={anchor} expression="happy" look="mouse" />65 </MinimojiStage>66 </>67 );68}69```7071- **The anchor is a DOM element outside the stage.** The stage's children72 render inside its WebGL canvas: only `MinimojiHead` and `MinimojiShadow`73 go there, never a `<div>`. The head is placed in its anchor's rect every74 frame, so the anchor can live anywhere on the page, scroll, move or resize.75- `anchor` is required in the default `mode="overlay"`; without it the head76 is built and never placed.77- A saved avatar is stored by its **avatar key**; keep the document (or78 fetch it by key from the service) to draw it live. `avatarKey(avatar)` is79 the normalized JSON, for React keys and caches.80- `look`: `'mouse'` (follows the pointer anywhere), `'near'` (within81 `reach` px), `'idle'` (glances about on its own), `{ x, y }` in −1…1,82 `null` (the camera), `'manual'` (you call `head.life.lookAt`).8384### A character: D.A.S.H., an alien, an animal8586```tsx87'use client';88import { useRef } from 'react';89import { MinimojiStage, MinimojiHead } from '@minimoji/react';9091export function Dash() {92 const anchor = useRef<HTMLDivElement>(null);93 return (94 <>95 <div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }} />96 <MinimojiStage>97 {/* `avatar` is still required: a character draws instead of it */}98 <MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor} expression="joy" />99 </MinimojiStage>100 </>101 );102}103```104105- Ids: `agent` (D.A.S.H.), its themes (`dashGold`, `dashNeon`, …), the106 aliens (`alien`, `alienMint`, …), `cat`, `kitty`, `rabbit`, `monkey`,107 `dog`, `penguin`, `ghost`. The service's `GET /capabilities` lists them108 (`characters`), and `CHARACTERS` in `@minimoji/react/characters`.109- A dealt one (`dashDealt`, `alienDealt`) takes a `seed`: the same seed is110 the same face. `{ id, pick }` fixes parts of a kit.111- Play a character exactly like a person: expressions, cues, talking,112 listening. No per-species code; D.A.S.H. draws its mouth on its screen.113114### The stage115116- **One `<MinimojiStage>` per page**, high in the tree, holding every head.117 It is fixed over the page and transparent (`mode="overlay"`, the default).118 `mode="wall"` is the opaque viewer wall: the head sits in the stage's119 own box (give it a size with `style`), no anchor.120- `mode` is fixed for the stage's life: change its `key` to switch.121- `detail` (0.2–1, default 1) is the mesh detail for the page; the122 homepage runs `.8` with about thirty heads.123- `surfaces` (on by default) paints each head into a 2D canvas inside its124 anchor, so heads scroll with the page on the compositor. Mark an ancestor125 `data-minimoji-surface` to have its heads share one canvas: do it for a126 group shot, and wherever the anchor clips its overflow.127- **Sizing**: a head's canvas is sized by what the screen shows of its128 anchor, an ancestor's `transform` or css `zoom` included: the backing129 store is the on-screen box in device pixels, the canvas's css box that130 box in the anchor's own coordinates. A head in a scaled container is131 sharp and its own size. The stage follows an anchor resized, and an132 ancestor's transform that transitions or animates, until it stops133 moving; for a move no event reports (a transform set with no transition,134 a canvas library's own zoom) call `resize()` on a `ref` to135 `<MinimojiStage>` (or `useStage().resize()` inside it). A rotated136 ancestor is not handled.137138## 3. Showing a head while it loads139140Do not draw your own placeholder. A head is built a moment after the page141paints; until it lands, `<MinimojiHeadPoster>` inside the anchor shows the142local silhouette immediately, then the head's own still: it comes in soft143and breathes, then gives way with a puff144when the head is ready, stays sharp on an error, and is a plain swap under145reduced motion. The silhouette takes `currentColor` (set `style.color` to a146contrasting tile tint), fades as the still arrives, and stays sharp if the147still fails. The same loader as the homepage and the Swift Kit.148149```tsx150'use client';151import { useRef } from 'react';152import { MinimojiStage, MinimojiHead, MinimojiHeadPoster, type AvatarInput } from '@minimoji/react';153154export function SavedHead({ avatar, avatarKey, service }: { avatar: AvatarInput; avatarKey: string; service: string }) {155 const anchor = useRef<HTMLDivElement>(null);156 return (157 <>158 <div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }}>159 <MinimojiHeadPoster src={`${service}/avatars/${avatarKey}.png?size=256`} />160 </div>161 <MinimojiStage>162 <MinimojiHead avatar={avatar} anchor={anchor} />163 </MinimojiStage>164 </>165 );166}167```168169- It runs off the anchor's `data-minimoji` (`loading` → `ready` |170 `error`, set by the head). Write `data-minimoji="loading"` in your171 markup so it runs from the first paint, server-rendered or not; give the172 anchor `position: relative`.173- The still: a saved avatar's `<service>/avatars/<avatarKey>.png?size=256`174 (drawn at save), or any transparent picture of the head. A character has175 no saved picture until it is saved: ship your own still (the homepage176 ships `.webp` stills), or no poster.177- A grid of stills (a picker, a list of people): add `&frame=face`, which178 frames each picture by the head's skin, so every face is the same size and179 a tall hat or long hair is clipped at the edge instead of shrinking it.180 Leave it off for a poster under a live head (the default frames the whole181 head, as the live head does).182- A small resting D.A.S.H. needs no poster: the first builds in about183 0.2–0.35 s, the rest about 50–120 ms each, and each draws at its final size184 from its first frame (§ 8, `rest`).185- No app CSS: the sheet is a React 19 hoisted `<style>`. Without React's186 hoisting, add `POSTER_CSS` to a stylesheet. `style` re-places the still187 (`{ inset: 'auto', left, top, width, height }`); `puff={false}` drops188 the puff.189190## 4. Making it talk191192**Feed the head speech and the rest follows**: the mouth articulates (lips193meet on m/b/p), the breath follows the phrases, and natural talk194(`naturalTalk`, on by default) plans glances aside and lifts the brows on the195pitch. Moods ride on top as emotes. Never hand-draw talking frames or animate196the jaw yourself.197198From least to most:199200- `talking={2}` (seconds) or `talking={true}`: a generic talking jaw, no201 audio. A changing number (`Date.now()`) re-triggers it.202- `voiceLevel={0…1}` (a call's level meter): drives the optional sound arcs203 or lines (`talkStyle="arcs" | "lines"`; the default `'mouth'` is the jaw204 alone). It does not move the jaw.205- **`performance`**: the real lip-sync. A function the head calls every206 frame, returning the mouth for that moment of the audio. From a recorded207 line, `mouthTrack` turns the clip's samples into one mouth per 1/60 s:208209### Say a line: one call210211**Hand the head the audio.** `useLine().say({ audio, transcript })` makes212the head lip-sync to it, emote and caption it, with no timeline and no213lip-sync code in your app. The SDK fetches the clip, decodes it with Web214Audio, builds the line with `buildLine` (the analyser the homepage's lines215are made with) and caches it. `prepare(clip)` does that ahead of time, so the216click starts the line at once.217218```tsx219'use client';220import { useEffect, useRef } from 'react';221import { MinimojiStage, MinimojiHead, MinimojiCaptions, useLine, type SpeechClip } from '@minimoji/react';222223const HEY: SpeechClip = { audio: '/voice/dash-hey.mp3', transcript: 'Hey! I am D.A.S.H.', mood: 'happy' };224225export function DashSaysHey() {226 const anchor = useRef<HTMLButtonElement>(null);227 const line = useLine({ onEnd: (_g, reason, error) => { if (reason === 'failed') console.warn(error); } });228 // build it ahead of the click, so the click's play() runs inside the gesture229 useEffect(() => { line.prepare(HEY).catch(() => {}); }, []);230 return (231 <>232 <button ref={anchor} type="button" aria-label="Say hi to D.A.S.H." data-minimoji="loading"233 onClick={() => line.say(HEY)}234 style={{ position: 'relative', width: 160, height: 160 }} />235 <MinimojiCaptions player={line} />236 <MinimojiStage>237 <MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor} emotes={false}238 expression={line.expression ?? 'neutral'} performance={line.performance} cue={line.cue} />239 </MinimojiStage>240 </>241 );242}243```244245- **The clip** is `{ audio, transcript?, words?, letters?, alignment?, captions?, mood?, cues?, transcribe? }`.246 `audio` can be a URL, a `Blob` (a TTS response), an `ArrayBuffer` or an247 `AudioBuffer`. `words` (`[{ text, start, end }]` in seconds, from your TTS248 provider's timestamps) give phrase captions and word cues, such as a nod on249 "yes" or a laugh on "haha". A `transcript`, or a `captions` string, gives250 one caption over the voiced part. With none of these there are no251 captions. Clips are cached by URL (or by the `Blob` or buffer object)252 together with their words and letters, keeping the last 8.253- **Pass your TTS alignment and the lips land on the letters.** A provider's254 per-character timestamps shape the mouth from the words instead of guessing255 from the sound: the lips meet on m, b and p and only there, and a vowel256 never snaps shut. Hand ElevenLabs' `with-timestamps` reply over as it comes,257 `say({ audio, words, alignment: tts.alignment })`, or as `letters`258 (`[{ text, start, end }]`, one character each with the spaces, seconds;259 `lettersFromAlignment` from `@minimoji/react` builds them). Words only (a260 transcriber's) spread into letters on their own: a clip with `words` and no261 `letters` or `alignment` gets `lettersFromWords(words)` by default262 (`letters: false` opts out, the mouth guessed from the audio). A direct263 `buildLine` call does not do this: pass `letters: lettersFromWords(words)`264 yourself. Captions ending a few ms past the audio (a provider's timestamps265 often do) end with it instead of failing the clip. A URL that serves new audio266 each time needs a fresh URL per clip, or pass the `Blob`.267- **Any voice, not only ElevenLabs.** Every provider's timings become our268 words (`[{ text, start, end }]`, seconds) with a small reader from269 `@minimoji/react` (also in `/sdk/minimoji-heads.js`); then270 `say({ audio, words })` (the words spread into letters by default):271272 | Provider | What it gives | Reader |273 |---|---|---|274 | ElevenLabs with-timestamps | characters + start/end arrays | `alignment: tts.alignment` (or `lettersFromAlignment`); `wordsFromAlignment(tts.alignment)` for the words |275 | ms words you stored | `{ text, startMs, durationMs }` | `wordsFromMs(words)` |276 | Azure Speech | WordBoundary events: `text`, `audioOffset` + `duration` in 100 ns ticks | `wordsFromAzure(events)` (punctuation boundaries skipped) |277 | Amazon Polly | speech marks: JSON lines `{ time (ms), type: "word", value }` | `wordsFromPolly(marks, clipSeconds)` (a word ends where the next starts; a cut-off line throws) |278 | Cartesia | `word_timestamps: { words, start, end }` (seconds) | `wordsFromCartesia(word_timestamps)` (one or a stream's pieces) |279 | Dictation, Scribe | words only | `words` (spread by `lettersFromWords` by default) |280 | OpenAI TTS, any voice with no timings, a human take | nothing | `say({ audio, transcript: 'what it says', transcribe: true })`: the service aligns the text to the audio |281282 Spread letters are an estimate (the lips still meet inside the right283 word); a provider's characters, or the service's alignment, are exact.284- **No audio, only words? Say the text.** Give `useLine` a `synthesize`285 (your publishable key and the service) and say `{ text, voice }`: Minimoji's286 `POST /lines/say` speaks it on its own ElevenLabs voice and answers the287 WAV and the line built on it, the letters timed on that very audio, so the288 mouth timings come from the call that made the sound. `voice` is a name from289 `GET /lines/voices` (`dash` is D.A.S.H.: Brian with the robot effect;290 `person`, `alien`, `cat`, `penguin`, `ghost`…), or one of their ids as291 `{ voiceId, effect: 'robot', settings }`; any other ElevenLabs voice id292 needs your own key (below), since Minimoji's account speaks only its293 catalogue. A text past about 60 s of speech (~900 characters at speed 1)294 is refused before anything is spent. `prepare({ text, voice })` ahead295 of the click makes the say start inside it (a repeat is never asked again):296297 ```tsx298 'use client';299 import { useEffect } from 'react';300 import { useLine, MinimojiCaptions, type TextClip } from '@minimoji/react';301302 const HI: TextClip = { text: "[happy] Hi, I'm D.A.S.H.!", voice: 'dash' };303304 export function DashSaysHi() {305 const line = useLine({ synthesize: { key: process.env.NEXT_PUBLIC_MINIMOJI_KEY!, service: process.env.NEXT_PUBLIC_MINIMOJI_SERVICE_URL! } });306 useEffect(() => { line.prepare(HI).catch(() => {}); }, []);307 // wire line.performance / line.cue / line.expression to a <MinimojiHead> as above308 return (309 <>310 <button type="button" onClick={() => line.say(HI)}>Say hi</button>311 <MinimojiCaptions player={line} />312 </>313 );314 }315 ```316317 `[tags]` set the face. On Minimoji's voice a key has 5,000318 characters a UTC day (a repeat of the same line costs none: it is served319 from the cache), then a 429 with the reset. **Bring your own ElevenLabs320 key** for no character quota and any voice on your account: `synthesize: { key, service, elevenLabsKey }`321 sends it in the `ElevenLabs-Key` header (never a query string; it is used322 for the one call and never stored or logged); the minute limit stays.323 Calling it yourself: `POST /lines/say` with `Authorization: Bearer mk_pub_…`324 and `{ text, voice, mood? }` answers `{ audio, line, words, letters,325 durationMs, cached, charged }`; play `say(answer.line, { audio:326 answer.audio })`. **Audio you process afterwards** (isolated, mixed, sped327 up) no longer matches those letters: send the final clip with its text to328 `POST /lines` (multipart `{ audio, text }`, below) for letters aligned on it.329 From a terminal: `npx minimoji say kai "Hi" --server` writes the same330 `<name>.wav` + `<name>.json` on your Minimoji key.331- **Clips you already have, in a batch:** `npx minimoji lines ./clips --texts lines.json --timings`332 sends each clip (`.wav`, or `.mp3`/`.m4a` with ffmpeg) with its text to333 `POST /lines` on your Minimoji key and writes `<name>.json` (the playable334 line: `say(line, { audio })`) beside it; `--timings` adds335 `<name>.timings.json` (`{ transcript, words, letters, alignedTo, loss }`)336 for an app that keeps its own line format. The text comes from `--text`,337 `--texts` (`{ "<name>": "text" }` or `{ "<name>": { text } }`) or a338 `<name>.txt` beside the clip; a clip with none is transcribed. `--dry-run`339 sends nothing. Each clip is one of the key's 200 lines a day, at most 30 s.340- **A voice note with no transcript** (a recording a person made, a voice341 chat message): pass your publishable key and the service to `useLine`, and342 say the audio alone. The SDK sends it to Minimoji's `POST /lines`, which343 transcribes it, and the line plays with phrase captions and word cues:344345 ```tsx346 'use client';347 import { useLine, MinimojiCaptions } from '@minimoji/react';348349 export function VoiceNote({ note }: { note: Blob }) { // a Blob from MediaRecorder, a URL or bytes350 const line = useLine({ transcribe: { key: process.env.NEXT_PUBLIC_MINIMOJI_KEY!, service: process.env.NEXT_PUBLIC_MINIMOJI_SERVICE_URL! } });351 // wire line.performance / line.cue / line.expression to a <MinimojiHead> as above352 return (353 <>354 <button type="button" onClick={() => line.say({ audio: note, transcribe: true })}>Play</button>355 <MinimojiCaptions player={line} />356 </>357 );358 }359 ```360361 With `transcribe` on the hook, a clip with no `words`, `transcript` or362 `captions` is transcribed even without `transcribe: true`, and if that363 fails (over 30 s, offline, the key's 200 a day spent) it plays as the plain364 waveform line with a console warning. With `transcribe: true` a failure365 ends the say `onEnd(…, 'failed', error)` with the service's words.366 `transcribe: false` never sends it. The SDK decodes any audio the browser367 plays and sends it as a 16 kHz WAV; if you call `POST /lines` yourself,368 send a WAV (it refuses mp3, m4a and webm, whose length it cannot check).369 **Know what it says?** Give the clip its `transcript` with370 `transcribe: true` (and no words or letters): the SDK sends the text too,371 the service force-aligns that script to the audio instead of transcribing372 it, and the lips follow the words as written (the answer says373 `alignedTo: 'text'`; a high `loss` means text and audio disagree; a374 transcript with no words outside its `[tags]`, or over 2,000 characters,375 is transcribed as before). Calling376 it yourself: `multipart/form-data` with `audio` (the WAV) and `text`377 (at most 2,000 characters; `[tags]` are kept off the aligner and set the378 face). **Privacy:**379 the audio (and the text, if given) is sent to Minimoji and to ElevenLabs for transcription or alignment and is380 not stored. Tell your people so where they record. The vanilla bundle's381 `createVoicedPerformance({ …, transcribe: { key, service } })` does the same.382- **Not prepared?** `say` still works. The line starts once it has been built383 (about 20 ms per second of audio on a laptop). `line.preparing` is true384 until then, and the head stays as it is.385- **A clip that fails** (it will not load, it is not audio, or it runs past386 60 s) never throws and never hangs. The head stays still,387 `onEnd(generation, 'failed', error)` reports it, and `line.error` holds the388 error until the next `say`.389- **A prebuilt line** is the fast path: a `*.timeline.json` (the public format390 in `docs/speech-line-format.md`: mouth frames at 60 fps, captions,391 optional timed words, mood and gesture cues), played with392 `line.say(timeline, { audio: '/lines/dash-hey.mp3' })`. The homepage's393 hellos run on this. Use it when you build lines ahead of time.394- **No React?** The site serves `/sdk/minimoji-heads.js`395 (`apps/web/public/sdk/`), a single ESM file with three bundled. It provides396 `mountHeadPerformance` and `createVoicedPerformance`, whose397 `select({ audio, transcript })` takes the same plain clip, plus398 `createLineSession` (this hook without React) and `createClipCache`.399 `createVoicedPerformance({ ..., muted, volume })` and its `setMuted(m)` /400 `setVolume(v)` hold a sound-off narrator across stop, replay and the next401 clip (every run makes a fresh element); the head still talks on a muted402 element. Unset, the element stays as your `createMedia` made it.403 The mood stickers' scripts load after the first paint from404 `minimoji-heads-bursts.js` beside the bundle (vendor both files). Hint the405 bundle early with `<link rel="modulepreload" href=".../sdk/minimoji-heads.js">`;406 a head built from its JSON draws sooner than a baked .glb (several MB). For a407 baked head, `mountHeadPoster(el, { src: <the still> })` before408 `prepareBakedHead`, then `mountHeadPerformance(el, { bakedHead, poster })`.409 When you call `prepareBakedHead` yourself, the mount is synchronous and410 only happens once the GLB is in, so the poster must go up first: call411 `const poster = mountHeadPoster(el, { src })`, then412 `await prepareBakedHead(...)`, then pass that same handle as413 `mountHeadPerformance(el, { bakedHead, poster })`. The still shows during414 the download and hands off to the live head.415- **`emotes={false}` on a talking head**, for the whole line: the line's strong mood416 cues emote through `cue`, quiet ones (k under 0.35) only change417 `expression`, gestures play through `cue`. `expression` is null between418 lines, so yours applies.419- **Never hangs.** If `play()` is refused (autoplay blocked), the audio420 errors or its clock stalls (1.5 s; 4 s before it first moves), the line421 carries on a silent clock: mouth and captions still run, and it ends.422- **The newest `say` wins** (a generation token): it cuts the line before423 it, and a late promise or event from the old one does nothing. `stop()`424 and unmounting end it.425- **`audio`** (with a prebuilt line): a URL (the hook makes and frees the426 element), your own `HTMLAudioElement` (paused, never freed), or none (the427 silent clock).428- **Captions**: phrases by default — at most four words, broken after429 punctuation, the word being said lit (`data-lit`) and staying lit through430 the pause after it; the first phrase shows before the voice starts and the431 last stays a second after it ends; a new phrase moves up. `mode="window"`432 is the Kit 9.44 sliding window (about 7 words / 40 characters). Reduced433 motion shows the whole line, still; `maxLines={1}` keeps it to a subtitle434 slot (then an ellipsis). A screen reader hears the whole line once per435 line (the moving words are hidden from it). Style the box with436 `className` / `style`; it must survive 200% text.437- **Making a line ahead of time** from your own audio and timed words (a438 TTS provider's timestamps, dictation): `buildLine({ pcm, sampleRate, words, mood })` from439 `@minimoji/react/line`, offline (what `say({ audio })` runs for you); `packages/engine/dev/line-from-words.mjs`440 converts ElevenLabs-style `{ text, startMs, durationMs }` words plus the441 clips. Never derive mouth shapes from letters. `mood` sets the opening442 face quietly (no emote burst at the start); audio tags in the words443 (`[excited]`, `[curious]`, `[whispers]`…) leave the captions and become444 quiet face changes at their word (`TAG_MOODS`), `[laughs]` a laugh.445446#### Directing the line: your own cues, a look, stage directions447448A script can time the head to its words. `clip.cues` are your cues, merged449with the ones the SDK derives (a nod on "yes"…); `at` is seconds or a word450of the clip (`{ word: 7 }`, an index into the timed words from 0, or451`{ word: 'card', nth? }`). The stored line holds seconds. A word the clip452does not say fails the say, naming the word.453454```tsx455import type { RefObject } from 'react';456import { lookTargetFor, type LinePlayerApi } from '@minimoji/react';457458// `line` is your useLine(); `words` your TTS provider's timed words; the refs your head's anchor and the card459export function present(line: LinePlayerApi, audio: string, words: { text: string; start: number; end: number }[],460 anchor: RefObject<HTMLDivElement | null>, card: RefObject<HTMLDivElement | null>) {461 line.say({ audio, words, cues: [462 { at: { word: 7 }, gesture: 'knowing-nod' },463 { at: 3.2, look: { x: .6, y: -.2 }, hold: 2 }, // eyes up-right for 2 s464 { at: { word: 'card' }, look: lookTargetFor(card.current!, anchor.current!) }, // at the card on the page465 ] });466}467```468469| cue | does |470| --- | --- |471| `{ at, mood, k? }` | a face (k under 0.35: quietly, no emote) |472| `{ at, gesture }` | one of the engine's tracks (`knowing-nod`, `head-shake`…) |473| `{ at, nod: true }` / `{ at, shake: true }` | the face's own nod / shake |474| `{ at, brow: 'up' \| 'down', k }` | a brow accent |475| `{ at, look, hold? }` | eyes on `{ x, y }` (−1…1, + right / up), `'away'` (aside, alternating sides) or `'viewer'` (back to you), for `hold` s (1.2 by default), then the head's own gaze |476477Tags in the words or transcript do the same with no code, and leave the478captions: `[nod]` `[shake]` `[brow]` `[brow down]` `[look away]`479`[look back]` `[smile]` (plus the mood tags, `[surprised]`…). An authored480gesture, brow or look within 0.6 s of a derived one replaces it. The look481rides in `line.performance` (and `line.look`), so the head needs nothing482new. `lookTargetFor(el, anchorEl)` turns two DOM rects into the `{ x, y }`.483484**No line at all (a game's NPC, a party host):** `playCues(stage, cues, clock?)`485plays the same cues (seconds from the start) on their own clock, through the486same dispatch. `cueStage(head.life)` is the stage for one head (`onReady`487hands you the head; give that `<MinimojiHead>` `look="manual"` so its own look488setting does not take the eyes back). With no `clock` it runs on timers; with489one (`() => seconds`) call `tick()` from your game loop. It returns490`{ tick, stop, done }`.491492### Driving the mouth yourself (your own clock)493494For live or decoded audio with no line: `mouthTrack` turns samples into one495mouth per 1/60 s, and a `performance` you write reads your own clock:496497```tsx498'use client';499import { useCallback, useEffect, useRef, useState } from 'react';500import { MinimojiStage, MinimojiHead, mouthTrack, type GlossFace, type MouthFrame, type PerformanceInput } from '@minimoji/react';501502// the clip, and the mood its word lands on (seconds into the clip)503const LINE = { audio: '/lines/dash-hey.mp3', cue: { at: 0.24, mood: 'happy' as GlossFace } };504505export function DashSaysHey() {506 const anchor = useRef<HTMLButtonElement>(null);507 const audio = useRef<HTMLAudioElement | null>(null);508 const frames = useRef<MouthFrame[] | null>(null);509 const cued = useRef(false);510 const [speaking, setSpeaking] = useState(false);511 const [cue, setCue] = useState<{ mood: GlossFace; generation: number } | null>(null);512513 // decode the line ahead of the click: the click's play() must run inside the gesture514 useEffect(() => {515 let live = true;516 const ctx = new AudioContext();517 fetch(LINE.audio).then(r => r.arrayBuffer()).then(bytes => ctx.decodeAudioData(bytes))518 .then(clip => { if (live) frames.current = mouthTrack(clip.getChannelData(0), clip.sampleRate); })519 .catch(() => {}).finally(() => void ctx.close());520 return () => { live = false; audio.current?.pause(); };521 }, []);522523 // called by the head every frame while it speaks: one stable function, reading the audio's own clock524 const perform = useCallback<PerformanceInput>(() => {525 const a = audio.current, f = frames.current;526 if (!a || !f || a.paused) return { active: false };527 if (!cued.current && a.currentTime >= LINE.cue.at) {528 cued.current = true;529 setCue(c => ({ mood: LINE.cue.mood, generation: (c?.generation ?? 0) + 1 }));530 }531 const m = f[Math.min(f.length - 1, Math.floor(a.currentTime * 60))];532 return { active: true, mouth: { open: m.open, width: m.width, round: m.round } };533 }, []);534535 const say = () => {536 if (!frames.current) return;537 const a = (audio.current ??= new Audio(LINE.audio));538 a.onended = () => setSpeaking(false);539 a.currentTime = 0; cued.current = false;540 a.play().then(() => setSpeaking(true), () => setSpeaking(false));541 };542543 return (544 <>545 <button ref={anchor} type="button" onClick={say} aria-label="Say hi to D.A.S.H." data-minimoji="loading"546 style={{ position: 'relative', width: 160, height: 160 }} />547 <MinimojiStage>548 <MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor}549 emotes={false} cue={cue} performance={speaking ? perform : null} />550 </MinimojiStage>551 </>552 );553}554```555556- **Keep the source's identity stable** (`useCallback`, a ref, a module557 function) and read your own clock inside it (`audio.currentTime`). While558 set it owns gaze, mouth, beat and blinks; `expression` and `listening`559 stay yours. Set it to `null` when the voice ends: that releases the mouth.560- **Feed every frame while the voice plays**, silences included (the561 track's rest frames); a mouth not refreshed for 0.3 s closes.562- The homepage precomputes the same frames offline (60 fps,563 `[open, width, round, level, pitch]`, plus `captions` and `cues`) so564 nothing decodes on the page; `mouthTrack` in the browser is the same565 mouth. Return `{ active: false }` between lines: natural talk then566 plans the glance back to the visitor.567- Optional snapshot fields: `voiceLevel` (the arcs), `mouth.pitch`568 (semitones off the speaker's median: natural talk's brows), `blink` and569 `drop` (counters: bump to fire once), `beat` (the listening nod's clock).570- **Live audio** (a call, no recording): the engine's571 `createLiveVisemeTimeline` and `createSpeechVoice` (not in this package572 yet: ask Minimoji) are the web twins of the Swift Kit's573 `LiveVisemes` and `SpeechVoice`: PCM in, a viseme and a level out, eased574 into a mouth per head. **Look-ahead** (voice chat): delay the voice's575 playout by 100 ms on your side and pass `lookAhead: .1` to576 `createLiveVisemeTimeline` (settable later as `timeline.lookAhead`): the577 shapes lead the sound by 70 ms and the lips meet on m, b and p before578 they are heard. Not where the speaker hears themselves (their own mic):579 there it is only lag. It adds to `playoutOffset`. Without it a closure580 shows as the voice comes back; a fading vowel never shuts the mouth.581582### Mouthing a streaming reply (no audio)583584An agent's reply that arrives as silent text: the head mouths the words as585they stream in, paced like speech. Not `useLine`: a line is a finished clip586with a duration, and a stream has neither. No key and no network.587588```tsx589'use client';590import { useRef, useState } from 'react';591import { MinimojiStage, MinimojiHead, useTextMouth } from '@minimoji/react';592593export function AgentReply({ stream }: { stream: () => AsyncIterable<string> }) {594 const anchor = useRef<HTMLDivElement>(null);595 const mouth = useTextMouth();596 const [text, setText] = useState('');597598 const run = async () => {599 mouth.cancel(); setText('');600 for await (const token of stream()) { mouth.append(token); setText(t => t + token); }601 mouth.finish();602 };603604 return (605 <>606 <button type="button" onClick={run}>Ask</button>607 <div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 54, height: 54 }} />608 <p>{text}</p>609 <MinimojiStage>610 <MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor} expression="happy"611 performance={mouth.speaking ? mouth.performance : null} />612 </MinimojiStage>613 </>614 );615}616```617618- **The pace is the hook's.** About 15 characters a second, up to 1.5x when619 behind. More than `lag` behind the newest text it skips forward, at a word620 boundary where there is one, to about 3/4 of `lag` behind; the last phrase is621 still mouthed. So a long reply never leaves the mouth talking long after the622 text has landed. After `finish()` the same rules run, then the mouth closes;623 `cancel()` closes it at once. Text after that starts a new reply.624- **`lag` is your call:** `useTextMouth({ lag: 1 })`, in seconds, default 1.5625 (sized for a chat reply streaming at 10+ words a second: the mouth stays626 within a phrase of the text and runs on about a second after it ends). It627 trades closeness for letters: a smaller lag follows the text closer and skips628 more of it; a larger one mouths more and trails further. It hurries from 3/8629 of it. A change takes hold at the next reply; a non-positive or non-finite630 value throws.631- **Tokens can split anything:** a word, a two-letter rule, an emoji. Hand them632 over as they come; the last letter of a chunk waits for the next one.633- **Send what you want mouthed.** It does not strip markdown or code: symbols634 take no time, but `const x = 1` is mouthed as text. Filter first.635- **Faces stay yours:** `expression` and `listening` compose with it as with a636 line, and the mood holds through the talking. Choose the mood yourself; it637 reads none from the text.638- **Gaze and blinks:** it hands over a mouth and its loudness, and no blink639 events. While `performance` is set the `look` prop is not read: the head640 glances about on its own (as during a line), or, with641 `useTextMouth({ look: { x, y } })` (-1..1, + x to the head's right, + y up),642 looks where you say while it speaks. Its own blinks go on. Pass643 `mouth.speaking ? mouth.performance : null`, as above, so `look` is back the644 moment it stops.645- **Reduced motion** is a line's rule: the mouth still moves (it is direct646 feedback), the head's natural motion and the stickers stop. Add no check.647- **A caption that keeps up:** `useTextMouth({ onSpoken: n => setShown(text.slice(0, n)) })`,648 or read `mouth.spoken()`. The count jumps forward over a skip.649- **Your own frame loop:** `createTextMouth({ lag })` from `@minimoji/react`650 (`append`, `finish`, `cancel`, `sample(dt)`). With no React, on the vanilla bundle:651 `const reply = stage.speak('Hel'); reply.append('lo!'); reply.finish();`652 (`reply.cancel()`, `reply.spoken`, `reply.speaking`, `stage.speak(text, id)`653 for a tile, and `stage.speak(text, id, { lag })`: the head keeps that lag654 until another `speak` names one, and a reply already playing keeps its own).655 The stage draws its own frames when you draw none.656657### Talking with your voice (live mic)658659The person talks into their mic and the head's mouth follows, live. The660analyser runs in the page (the same live viseme analyser as MinimojiKit), so661there is no key, no network, and nothing is played, stored or sent.662663```tsx664'use client';665import { useRef } from 'react';666import { MinimojiStage, MinimojiHead, useLiveMic } from '@minimoji/react';667668export function TalkAsYourAvatar({ avatar }: { avatar: object }) {669 const anchor = useRef<HTMLDivElement>(null);670 const mic = useLiveMic();671 return (672 <>673 <button type="button" onClick={() => (mic.live ? mic.stop() : mic.start())}>674 {mic.live ? 'Stop' : mic.state === 'starting' ? 'Opening the mic…' : 'Talk'}675 </button>676 {mic.error && <p>{mic.error.code === 'denied' ? 'Allow the microphone to talk as your avatar.' : mic.error.message}</p>}677 <div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }} />678 <MinimojiStage>679 <MinimojiHead avatar={avatar} anchor={anchor} expression="happy"680 performance={mic.live ? mic.performance : null} />681 </MinimojiStage>682 </>683 );684}685```686687- **`start()` from a click or a key press.** Browsers only run audio from a688 user gesture, and Safari only from one made in the same tick: call it in the689 handler, not after an `await`. It needs `https://` (or localhost). The690 hook's `start()` resolves `true` once live and `false` otherwise (no catch691 needed): the failure is `mic.error` (and `onError`'s), an `Error` whose692 `code` is `denied`, `no-device`, `busy` (another app has the mic),693 `blocked` (the browser kept audio off: not from a gesture), `unsupported` or694 `failed`. Without the hook, `start()` and `liveMic()` reject with it.695 A mic that goes away mid-talk stops it with `ended`696 (`mic.on('error', fn)` hears every failure).697- **Voice processing is on:** echo cancelling, noise suppression and auto gain698 (`LIVE_MIC_CONSTRAINTS`). `useLiveMic({ deviceId })` picks a mic from699 `enumerateDevices()`, from the next start.700- **The head between words is its own:** `performance` is the mouth while you701 talk and inactive in the silences, so the gaze and idle carry on. Pass702 `mic.live ? mic.performance : null` so `look` is back when it stops.703- **A meter:** `mic.level()` is how loud the voice is now, 0..1; read it in704 your own animation frame.705- **Unmounting stops the mic.** Faces (`expression`, `listening`) compose with706 it as with a line.707- **No React:** `createLiveMicSession()` from `@minimoji/react` is the same708 session (`start`, `stop`, `performance()`, `level()`, `on`). On the vanilla709 bundle (`/sdk/minimoji-heads.js` on minimoji.com, once the site deploys):710711 ```js712 import { mountHeadPerformance, liveMic } from 'https://minimoji.com/sdk/minimoji-heads.js';713 const stage = mountHeadPerformance(el, { avatar });714 talk.onclick = async () => {715 const mic = await liveMic(); // from the click; rejects with a coded Error716 stage.setPerformance(mic); // the head talks with your voice; the stage draws its own frames717 stop.onclick = () => { mic.stop(); stage.setPerformance(null); };718 };719 ```720721 `stage.setPerformance(source, id)` takes any live source (anything with722 `performance()`); `id` picks a tile.723724### Change a head with the whirl (vanilla stage)725726A look picker on the vanilla bundle changes the head with the phone's spin,727no remount:728729```js730await stage.swapAvatar(nextDoc, { id: 'guest' }); // id: the tile; omit on a solo stage731```732733The old head stays until the new one is built, turns two turns and the new734one comes out of the last half turn on a spring (the same timing as735`<MinimojiHead>` and the Kit). It resolves when the whirl is over and the old736head is disposed. The head keeps its tile, mood, live source and mouthed737text. A second call mid-whirl ends on the newest look. Reduced motion trades738at once. `setAvatar` stays instant. On a stepped stage, step it, then await.739740A new colour changes in place; only a new shape spins. `whirl: false` is the741instant change on any head, a tile too (the old head stays until the new one742is built, then the new one is drawn in its place; the promise resolves on the743next frame):744745```js746await stage.swapAvatar({ ...doc, skin: 'deep' }, { id: 'guest', whirl: false }); // colour, skin: no spin747await stage.swapAvatar({ ...doc, hair: { ...doc.hair, style: 'bob' } }, { id: 'guest' }); // a style: the whirl748```749750An editor's lists come from the same bundle (and `@minimoji/react`), with the751same values: `INVENTORY`, `optionsFor(doc, 'hair.style')` (each value with752`allowed`), `optionLabel(value)` for a tile's words, `swatchHex(path, value)`753for a chip, `HAIR_COLORS` / `HAIR_IDS`, and `normalize(doc)`:754755```js756import { mountHeadPerformance, optionsFor, optionLabel, swatchHex, HAIR_COLORS } from 'https://www.minimoji.com/sdk/minimoji-heads.js';757const styles = optionsFor(doc, 'hair.style').filter(o => o.allowed).map(o => ({ value: o.value, label: optionLabel(o.value) }));758const colours = HAIR_COLORS.map(c => ({ id: c.id, hex: c.hex }));759```760761### Emotes with speech762763Two ways, pick one per head:764765- **The mood as an `expression`**: change `expression` and the head plays766 that mood's emote on the change (one of three, never the same one twice in a row).767- **Cued moods over a held face** (what the homepage does): `emotes={false}`768 so expression changes play nothing, and `cue={{ mood, generation }}` at769 the line's moments. A cue plays once per distinct value: bump770 `generation` to play the same mood again.771772### A host that talks (onboarding, tours)773774A character that says one line per screen: `useLine` plus a few rules. For a775whole onboarding or product intro the character presents (slides, a voiced776line each, bubble captions, steps that wait for a choice or a sign-in), use777the `minimoji-presenter` skill and its starter deck.778779- **One line per screen.** Start it on appear after a 250–500 ms lead-in;780 a tap on the head replays it. Pick lines at random, never the same one781 twice in a row.782- **Recorded audio plus its line** (above). Mouth, cues and captions all783 read one clock, the audio's, and `useLine` falls back to its silent clock784 on its own, so a blocked or muted start still moves the screen on.785- **Cancel by generation, not by unmount**: `say` already does. A late786 callback from an older screen's line does nothing, so an old screen's787 cleanup can't cut the new line.788- **Accessibility**: `<MinimojiCaptions>` announces each line once; make789 the head a button labelled "Replay" and hide off-screen duplicate heads790 from assistive tech.791- **The audio's owner and the head can live apart**: pass the `useLine()`792 value down, or hand `{ cue, expression, performance }` to the head through793 a small external store (`useSyncExternalStore`), as the homepage does.794- **Load the host early**, keep it mounted for the session, and show795 `MinimojiHeadPoster` until it lands (section 3).796- A character like D.A.S.H. reads about 10% larger than a person in the797 same anchor: size its anchor down a little.798- **Never break the host.** A missing clip, a line that won't parse, an799 audio error: fall back to the still head or the silent clock800 (`say(line)` with no audio still moves the mouth and captions), log it801 under one prefix, and never block the page on it.802- **Own long-lived things once**: the `useLine()` player in the component803 that stays mounted (or a module-level store), each line's JSON fetched and804 parsed once per page load, not per render.805- **Post-processing the provider's audio** (a robot filter, a pitch shift)806 must keep the exact duration: pad or trim back to the raw recording's807 sample count, or every word timing drifts against the mouth and captions.808- **Screen readers** hear the line once (`<MinimojiCaptions>` announces it),809 never the captions word by word. Skipping the audio while a screen reader810 runs is an option, not the rule.811- **A host on a sign-in page** (before auth): a character builds on the page812 from its id, so it needs no key and no network beyond your own bundle:813 ship its lines and clips with the page, and the form never waits on it.814815```tsx816'use client';817import { useEffect, useRef, useState } from 'react';818import { MinimojiStage, MinimojiHead, MinimojiCaptions, useLine, type SpeechLine } from '@minimoji/react';819820export function OnboardingHost({ clip }: { clip: { audio: string; line: string } }) {821 const anchor = useRef<HTMLButtonElement>(null);822 const [data, setData] = useState<SpeechLine | null>(null);823 const line = useLine();824 useEffect(() => { fetch(clip.line).then(r => r.json()).then(setData).catch(() => {}); }, [clip.line]);825 // the screen's line after a short lead-in (blocked autoplay plays it on the silent clock)826 useEffect(() => {827 if (!data) return;828 const id = setTimeout(() => line.say(data, { audio: clip.audio }), 350);829 return () => clearTimeout(id);830 }, [data, clip.audio]); // eslint-disable-line react-hooks/exhaustive-deps -- say is stable per hook831 return (832 <>833 <button ref={anchor} type="button" aria-label="Replay" data-minimoji="loading"834 onClick={() => data && line.say(data, { audio: clip.audio })} style={{ position: 'relative', width: 120, height: 120 }} />835 <MinimojiCaptions player={line} />836 <MinimojiStage>837 <MinimojiHead avatar={{}} character={{ id: 'agent' }} anchor={anchor} emotes={false}838 expression={line.expression ?? 'happy'} performance={line.performance} cue={line.cue} />839 </MinimojiStage>840 </>841 );842}843```844845## 5. Moods and gestures846847```tsx848'use client';849import { useRef, useState } from 'react';850import { MinimojiStage, MinimojiHead, GLOSS_FACES, type AvatarInput, type GlossFace } from '@minimoji/react';851852export function Reacting({ avatar }: { avatar: AvatarInput }) {853 const anchor = useRef<HTMLDivElement>(null);854 const [face, setFace] = useState<GlossFace>('neutral');855 const [cue, setCue] = useState<{ gesture: string; generation: number } | null>(null);856 return (857 <>858 <div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 120, height: 120 }} />859 <select value={face} onChange={e => setFace(e.target.value as GlossFace)}>860 {GLOSS_FACES.map(f => <option key={f}>{f}</option>)}861 </select>862 <button type="button" onClick={() => setCue(c => ({ gesture: 'double-take', generation: (c?.generation ?? 0) + 1 }))}>Double take</button>863 <MinimojiStage>864 <MinimojiHead avatar={avatar} anchor={anchor} expression={face} cue={cue}865 onGestureEnd={(id, { cancelled }) => { if (!cancelled) console.log('done', id); }} />866 </MinimojiStage>867 </>868 );869}870```871872- `expression` is one of `GLOSS_FACES` (`idle`, an alias of `neutral`; `neutral`, `happy`, `joy`,873 `laugh`, `sad`, `angry`, `furious`, `surprised`, `worried`, `scared`,874 `dead`, `smug`, `sleeping`, `crying`, `thinking`). A change plays the875 mood's emote unless `emotes={false}`.876- **Stickers**: a change to a mood also pops its comic stickers around the877 head (a "!" for `surprised`, sweat for `worried`, flames for `angry`,878 hearts for `happy`…), as MinimojiKit does. On by default; `bursts={false}`879 turns them off, and reduced motion shows none. Every mood above has them880 but `neutral`/`idle`. They fire on a CHANGE: never the first face, never881 the same face twice in a row, and at any strength (a line's quiet 0.3 cue882 pops them too); a change to `neutral` lets them fade, and so does the end883 of a line. Nothing to wire: a line's mood cues reach `expression`, so884 `useLine` lines pop them at each cue. The PNGs load from885 `https://www.minimoji.com/emote-bursts/` (allow it in `img-src`), or886 serve your own: the package ships them in `emote-bursts/`, so copy887 `node_modules/@minimoji/react/emote-bursts/` into your static folder888 (`public/emote-bursts/` in Next.js) and pass889 `<MinimojiStage burstBase="/emote-bursts/">`.890- **Face only**: `decorations={false}` (and `decorations: false` on the891 vanilla bundle's `mountHeadPerformance`) shows no stickers (it overrides892 `bursts`) and none of the rig's own effects: tears, sparkles, steam,893 sleep Zs, notes, a screen face's effects. Expressions, blush, lip sync894 (its sound arcs and lines too) and motion are unchanged. On by default.895- **D.A.S.H.'s screen** shows the mood on the whole glass (the LEDs, their896 glow and the glass take the mood's colour: pink for happy, red for angry,897 blue for sad; neutral is the theme's own), and its eyes change shape for898 `sad`/`crying`/`worried` (a drooping arc), `angry`/`furious` (a slash) and899 `surprised`/`scared` (a wide ring). Nothing to wire: `expression` drives it.900 Its **CRT look** (scanlines and glass brightness that follow the mood) is901 `crt`: `0` off, `1` (the default), `2` loud. `crt={0}` for a flat screen;902 reduced motion keeps the scanlines dark. A head of skin ignores it. On the903 vanilla bundle: `mountHeadPerformance(el, { crt: 0 })`; on a runtime,904 `life.setScreenCrt(level)`.905- **D.A.S.H. as an agent** (bake 19): `agentState` makes his screen show what906 an agent is doing. `'thinking'` is a wave of three neon dots in his907 theme's colours; `'working'` is code flowing up a line every 0.35 s;908 `'needsYou'` is one big glitching neon `!` in place of his face; the rest909 are his face in the state's colour on dark glass: `'waiting'` (eyes up, a `…` mouth), `'done'`910 (a check that stays), `'errored'` (`> <` eyes, a zigzag mouth, an RGB911 glitch), `'asleep'` (closed eyes). `'needs-you'` works too. Each state912 has its own colour; pass your app's with `screenColor="#ff9f43"` (and913 `screenGlass`: about `.3` keeps the glass dark so only the face lights,914 `2.2` floods it). `null` (the default) leaves the screen exactly as it915 was. Vanilla bundle:916 `mountHeadPerformance(el, { agentState: 'working' })`, then917 `stage.setAgentState('done')` / `stage.setScreenColor('#4ade80', { glass: .3 })`;918 on a runtime, `life.setAgentState(state, { color, glass })` and919 `life.setScreenColor(hex, { glass })`.920- **Connecting with progress**: `agentState="connecting"` plus921 `agentProgress={0.5}` turns D.A.S.H.'s screen into a 16 × 8 dot matrix, a922 mint wave scrolling over a yellow progress bar you fill, `0..1` (clamped;923 it eases to each new value; `null` shows only a pulse at its start). Send924 discrete steps (0, .25, .5, .75, 1) as your connect steps finish; don't draw925 your own bar under him. On a runtime, `life.setAgentProgress(v)` and926 `life.setAgentState('connecting', { color, barColor })` (`color` the wave,927 `barColor` the bar). Every bake 19 Dash shows it, a `lite: 'agent'` one too;928 any other head thinks, as for `'thinking'`. With `performances: false`929 (reduced motion) the wave holds still and the bar still follows the value.930- **Agent states on every head**: `agentState` works on every Mini avatar, not931 only D.A.S.H. A head without a screen (a person, an animal, the ghost, the932 penguin) shows the state with its own face and one held sticker beside it,933 in the state's colour (or yours, from `screenColor`): `'thinking'` the934 thinking face and a thought bubble; `'working'` the happy face typing on a935 small keyboard in front of it, real code flowing up behind the head936 (monospace, syntax-coloured, a line every .35 s, still while it thinks), and937 every few seconds a look up and aside with the bubble; `'needsYou'` surprised with938 one `!` standing behind the head; `'waiting'` a glance up and a clock in a thought bubble; `'done'` a nod and a check behind the head that stays; `'errored'` X eyes, a head shake every 3 s and a ✕ in a thought bubble; `'asleep'` the gentle asleep pose with Zs rising beside it. Clearing it hands back939 the neutral face. Same prop, same `stage.setAgentState` / `life.setAgentState`;940 `life.agentStickers()` is what the sticker layer draws (`decorations={false}`941 draws none). Runtime only: any bake works.942- **The code flow follows your theme**: `theme="light" | "dark"` on943 `<MinimojiStage>` (every head) or `<MinimojiHead>` (that head; it wins) gives944 the code deeper ink on a light surface and brighter neon on a dark one.945 `null` (the default) follows the page's `prefers-color-scheme`, so set it946 whenever your app's theme can differ from the system's (an in-app toggle).947 Under about 40 css px each line draws as one coloured bar per token, since948 glyphs that small speckle. Vanilla bundle: `mountHeadPerformance(el, { theme: 'dark' })`,949 then `stage.setTheme('light')`.950- `cue={{ gesture }}` plays one named track over the face as it is (the951 face never changes): `double-take`, `head-shake`, `sunny-nod`,952 `knowing-nod`, `ponder-tilt`, `side-eye-hmm`, `lightbulb`, … (the953 engine's authored tracks). `cue={{ mood }}` picks one of that mood's954 three. One shot only: chain the next from `onGestureEnd`, which always955 comes (cancelled when replaced, the next frame under956 `performances={false}`).957- To time moods, gestures and looks to a script (or play them with no audio958 in a game), see "Directing the line" in § 4: `clip.cues`, the `[nod]`-style959 tags and `playCues`.960- `performances={false}` stills every one-shot, cues included (reduced961 motion). To cue your own gestures over a beat, pass `emotes={false}`,962 not `performances={false}`.963- **A face you set for bookkeeping** (a mood lapsing back to neutral, a964 mute, a reset) goes with `emotes={false}` in the same render; a face the965 person picked goes with `emotes={true}`. `emotes` is live, never a966 rebuild, and is read on the next `expression` change, so the lapse changes967 the face with no emote. Cues still play, and one already968 playing plays on. Stickers are `bursts`'s: a lapse to `neutral` pops none;969 to a mood that has one, pass `bursts={false}` on the same render.970- A mood from text: `POST <service>/expressions/pick` with971 `{ text, gesture: true }` answers `expression` (null: keep the face) and972 a `gesture`. Ask on a typing pause, never per keystroke.973974### Poke and drag975976```tsx977'use client';978import { useRef } from 'react';979import { MinimojiStage, MinimojiHead, type AvatarInput, type MinimojiHeadHandle } from '@minimoji/react';980981export function Pokeable({ avatar }: { avatar: AvatarInput }) {982 const anchor = useRef<HTMLDivElement>(null);983 const head = useRef<MinimojiHeadHandle>(null);984 return (985 <>986 <div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 160, height: 160 }} />987 <button type="button" onClick={() => head.current?.react('giggle')}>Tickle</button>988 <MinimojiStage>989 <MinimojiHead ref={head} avatar={avatar} anchor={anchor}990 interactive={{ poke: { reactions: ['oof', 'ah', 'flinch', 'dizzy'] }, drag: { maxPx: 60 }, label: 'Poke Dash' }}991 onPoke={({ reaction }) => console.log('poked:', reaction)}992 onDragEnd={({ distance, flung }) => console.log(distance, flung)} />993 </MinimojiStage>994 </>995 );996}997```998999- `interactive` is off by default (no listener is attached); `interactive` alone (true) turns on both1000 poke and drag. Only the head's skull counts: a press anywhere else in the anchor goes to the page.1001- A poke plays a reaction: `oof` (squash + wince), `ah` (surprised hop back), `flinch` (recoils away from1002 the poke), `giggle` (laugh + shake) or `dizzy` (× eyes + wobble). Never the same one twice in a row, one1003 at a time with a short cooldown. `poke.reactions` replaces the pool (unknown names warn once, skipped).1004- It works idle, paused or mid-line: the face changes for a moment and lip-sync carries on under it. A poke1005 never stops a line: pause it yourself from `onPoke` if you want to. No sound ships: play your own there.1006- A drag pulls the head on a rubber band (toward `drag.maxPx`, 80 css px, never past), tilted toward the1007 pull; it springs back with a wobble. A fast release is a fling and plays `dizzy`. A touch that starts on1008 the head drags it instead of scrolling the page; anywhere else the page scrolls as usual. A head painted1009 into its own anchor is cut at the anchor's padded box, so its drag stops there; give a group a1010 `data-minimoji-surface` frame for more room.1011- `ref.current.react(name?)` plays one from code (with no name, one from the pool), interactive or not,1012 and answers what played (null for an unknown name). React 19 passes `ref` as a prop.1013- Events: `onPoke({ reaction })`, `onDragStart()`, `onDragEnd({ distance, flung })`.1014- The anchor becomes a button (`role="button"`, focusable, `label` as its name, default "Poke the1015 avatar"): Enter or Space pokes it. Under reduced motion nothing moves; the faces still change.1016- The vanilla bundle (`/sdk/minimoji-heads.js`) takes the same `interactive`, `onPoke`, `onDragStart` and1017 `onDragEnd` options on `mountHeadPerformance`, and its stage has `react(name?, id?)`.10181019## 6. Listening, presence and thinking10201021```tsx1022'use client';1023import { useEffect, useRef } from 'react';1024import { MinimojiStage, MinimojiHead, type AvatarInput, type Head } from '@minimoji/react';10251026export function Friend({ avatar, online, typing, music }: { avatar: AvatarInput; online: boolean; typing: boolean; music: boolean }) {1027 const anchor = useRef<HTMLDivElement>(null);1028 const head = useRef<Head | null>(null);1029 // presence and thinking are on the head's face api, not props: apply them when the head lands and on each change1030 const apply = (h: Head | null) => {1031 if (!h) return;1032 h.life.setPresence(online ? 'online' : { state: 'asleep', z: true });1033 h.life.think(typing);1034 };1035 useEffect(() => apply(head.current));1036 return (1037 <>1038 <div ref={anchor} data-minimoji="loading" style={{ position: 'relative', width: 96, height: 96 }} />1039 <MinimojiStage>1040 <MinimojiHead avatar={avatar} anchor={anchor} listening={music ? { tempo: 96, mouth: 'hum' } : null}1041 onReady={h => { head.current = h; apply(h); }} />1042 </MinimojiStage>1043 </>1044 );1045}1046```10471048- `listening` composes with any expression (a sad head nods sadly): a nod1049 on `tempo`, notes rising; `notes: false` keeps the nod alone. A host1050 with its own beat feeds `beat` through `performance`; `drop` (a counter)1051 fires the bigger nod and a burst of notes.1052- `setPresence`: `'online'`, `'asleep'` (eyes shut, slow breath; `z: true`1053 lies it down with Zs), `'party'` (a bounce on the beat). Leaving asleep1054 plays the wake-up. `{ state: 'asleep', z: true, roll: ASLEEP_GENTLE_ROLL }`1055 (exported, 16° in radians) stops the head at a gentle roll instead, the Zs1056 upright and the snore kept; the matching still is `.png?face=asleep` (no Zs).1057 A presence set as the head lands (in `onReady`, as above; within its first 0.25 s) is its1058 mount presence: asleep at once, no doze-in. A later change eases.1059- `think(true)`: the typing state, a thinking face with a looping tilt;1060 any speech takes the mouth at once.1061- `onReady` hands you the `Head` (and again after the avatar changes);1062 `head.life` is the whole face api (`FaceApi` in `index.d.ts`).10631064## 7. Bodies10651066`@minimoji/react` draws heads only. The homepage's full-body tile is the1067engine's own stage, with the site's own assets, and is not a public web API1068yet. For bodies in an app use1069the Swift Kit's `MinimojiBody`, or ask Minimoji.10701071## 8. Many heads on a page10721073- **One stage**, every head in it. Heads build one per animation frame, in1074 mount order, and scale in as they land (`rest` heads, or `land={false}`:1075 at their final size from the first frame); scrolling holds builds back.1076- Lower `detail` (`.8` on the homepage) before anything else.1077- Under 48 px a head wears the compact arcs by itself; nothing to do.1078- A group sharing a floor: `shadow={false}` on each head and one1079 `<MinimojiShadow anchor={…} />` under them.1080- Respect `prefers-reduced-motion`: pass `drift={false}`,1081 `performances={false}` and `look={null}` (the homepage does). The1082 package already drops natural motion and screen effects under it.1083- A changed `performances`, `naturalTalk`, `drift` or `character` rebuilds1084 the head: set them once, not per frame. `emotes` is live (no rebuild). A changed `avatar` whirls the new head in.1085- One voice at a time: stop the other heads' audio when one starts.10861087### Status heads in an app's chrome (`rest`)10881089A crew rail, pane pills, a sidebar of agents: small heads that sit open all1090day and should cost nothing while nothing happens. Put `rest` on each one.10911092```tsx1093'use client';1094import { useRef, type RefObject } from 'react';1095import { MinimojiStage, MinimojiHead, type AgentState } from '@minimoji/react';10961097type Agent = { id: string; name: string; theme: string; state: AgentState | null };10981099export function CrewRail({ crew }: { crew: Agent[] }) {1100 const anchors = useRef(new Map<string, RefObject<HTMLDivElement | null>>());1101 const anchor = (id: string) => {1102 if (!anchors.current.has(id)) anchors.current.set(id, { current: null });1103 return anchors.current.get(id)!;1104 };1105 return (1106 <>1107 {crew.map(a => (1108 <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>1109 <div ref={anchor(a.id)} style={{ width: 30, height: 30 }} />1110 {a.name}1111 </div>1112 ))}1113 <MinimojiStage>1114 {crew.map(a => (1115 <MinimojiHead key={a.id} avatar={{}} character={{ id: a.theme }} anchor={anchor(a.id)}1116 agentState={a.state} rest shadow={false} bursts={false} />1117 ))}1118 </MinimojiStage>1119 </>1120 );1121}1122```11231124`theme` is a D.A.S.H. id: `agent`, `dashGold`, `dashRose`, `dashOcean`, …11251126- A resting head is there when the window is: drawn at its final size from1127 its first frame (no scale-in), and a changed `avatar` or `character` takes1128 its place at once (no whirl). `land` overrides it either way. Ten cold1129 D.A.S.H. heads: the first drawn about 0.6 s after the stage mounts, all ten1130 by about 1 s (Chrome, a busy dev machine; 2.9 and 7.4 s before 19.2.0). The1131 first D.A.S.H. on a page builds in about 0.2–0.35 s (its plates extruded,1132 after the renderer's setup); the rest of a burst about 50–120 ms each.1133- A resting head is built without its breath and drift and looks straight1134 out of its tile (`look` as `{x,y}` or `'manual'` still applies). A change1135 (`agentState`, `expression`, `screenColor`, a cue, talking, a resize) is1136 drawn, plays out for about a second and a half, and is held.1137- When every head on the stage is held, the stage asks for no animation1138 frame and issues no WebGL draw at all until something changes. Ten idle1139 D.A.S.H. heads: 0 frames and 0 draws, against 120 rAF/s and ~12% of a1140 main thread without `rest`.1141- `'thinking'` and `'working'` are patterns: a head showing one keeps the1142 stage drawing while it does, and only that head is drawn: the held heads1143 beside it are left out of the render and keep their pixels. A small one1144 (anchor ≤ 56 px) draws at the stage's `restFps` (default 15; at most 30),1145 with no animation frame asked for in between. One working 30 px head1146 among nine at rest: about 2% of a main thread in Electron (1.9–2.5%1147 across runs), against 13.6% without `rest`. For margin, set1148 `<MinimojiStage restFps={12}>`: about a fifth less (0.4–0.5 points);1149 15 is the rate the patterns were checked at. Every other agent state is held at a clean moment of its screen1150 (the `!` lit, the check without its sparkles, the `…` full).1151- What wakes a held stage: a prop change, a scroll (the page's or a box1152 inside it), a window resize, an anchor resized or scrolled into view, an1153 ancestor's transform transition or animation, a device-pixel-ratio change,1154 a poke, `resize()` on the stage's `ref`. Nothing else; the pointer does not.1155 Woken, it draws until every anchor's size stops changing, so a head is1156 held at the size it lands on, never one it passed through.1157- Held only when the head has a canvas of its own (the default `surfaces`,1158 its anchor not inside a `data-minimoji-surface`); otherwise it keeps1159 drawing. Driving `head.life` yourself (`think`, `setPresence`, `lookAt`)1160 announces nothing: call `ref.current.wake()` after.1161- `rest` is opt-in at any size, and set once: changing it rebuilds the head.1162 Without it heads breathe, blink and glance exactly as before.1163- `shadow={false}` on every head (and no `<MinimojiShadow>`) also skips the1164 stage's shadow pass while it draws.1165- **Electron**: works with `contextIsolation`, `sandbox` and a strict CSP,1166 from `file://` or a custom protocol, no `unsafe-eval`:1167 `default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'`.1168 A D.A.S.H. head needs no network. Only the comic stickers fetch (images1169 from `https://www.minimoji.com/emote-bursts/` on a mood change): pass1170 `bursts={false}`, add that origin to `img-src`, or serve the package's1171 `emote-bursts/` folder yourself with `<MinimojiStage burstBase>`.11721173### A baked head (a bake's GLB, no avatar document)11741175When you hold a bake rather than a document (`GET /avatars/<key>.glb`, or1176bytes your server stored), draw it as it is. A small one comes as1177`?detail=.25&lite=1` (no effect plates); for a D.A.S.H. you drive with1178`agentState`, ask `lite=agent` (`POST /avatars/bake` `{lite: "agent"}`):1179lite, but it keeps his agent screens, which `lite=1` leaves out (`MinimojiHead`1180builds from the document and always has them):11811182```js1183import { prepareBakedHead, buildBakedHead } from '@minimoji/react';1184const prepared = await prepareBakedHead({ url: glbUrl, sha256 }); // or bytes; once per file1185const head = buildBakedHead(prepared, { gaze: false }); // as many as you need1186```11871188The vanilla bundle takes it as `mountHeadPerformance(el, { bakedHead: prepared })`1189(also per tile, `tiles[i].bakedHead`), `mountBakedHeadPerformance(el, { bakedHead })`,1190and `stage.setBakedHead(prepared)`. `prepareBakedHead` checks the file before1191parsing it (data only: no images, textures, external buffers or extensions1192beyond four material ones; 32 MB at most; the bundle's own bake version) and1193rejects a bad one; there is never a stand-in head. A URL is fetched with1194same-origin credentials (http(s) or a /path; pass bytes otherwise); account checks are your server's. Each head from one1195prepared file owns its geometry and materials; `prepared.dispose()` frees only1196the template.11971198### A packed character's colours (recolour by slot)11991200A character pack (`minimoji characters pack`) declares colour slots; each look's file says which1201parts wear each slot. `prepared.slots` is that map (`{ shell: ['body', …], trim: [] }`, or `null`1202for a file with none: its colours are fixed). Recolour live, no reload:12031204```js1205const stage = mountBakedHeadPerformance(el, { bakedHead: prepared, colors: { skin: '#9b5de5' } });1206stage.setColors({ trim: '#ffcc00' }); // instant1207stage.setBakedHead(nextLook, { colors: current }); // another look of the same character1208```12091210`buildBakedHead(prepared, { colors })` and `setBakedHeadColors(head, colors)` do the same on a1211head you mount yourself. They throw on an unknown slot or a colour that is not `#rrggbb`; a slot1212that is empty on this look changes nothing. An editor for a character's looks and colours is the1213`minimoji-editor` skill.12141215### Recording a video frame by frame (no GPU needed)12161217To export a head to video (an MP4 of a narrated deck, recorded in headless1218Chromium where WebGL runs on SwiftShader at a few fps), put the stage on a1219**stepped clock**. It then runs no loop of its own and reads no wall clock:1220nothing moves and nothing draws until you call `step(dt)`, each step moves1221every clock the head has (blinks, breath, emotes, stickers, cues, a line) by1222exactly `dt` seconds and draws one frame into the normal canvas, and the same1223seed and the same calls draw the same frames every run, however slow the1224recorder is between steps.12251226```tsx1227'use client';1228import { useEffect, useMemo, useRef } from 'react';1229import { MinimojiStage, MinimojiHead, useLine, createManualClock, type SpeechLine } from '@minimoji/react';12301231export function Recorder({ line, onFrame }: { line: SpeechLine; onFrame: (i: number) => Promise<void> }) {1232 const anchor = useRef<HTMLDivElement>(null);1233 const clock = useMemo(() => createManualClock({ seed: 7 }), []); // the dice: same seed, same blinks1234 const talk = useLine({ clock }); // the line runs on the steps, with no sound1235 useEffect(() => {1236 let stop = false;1237 (async () => {1238 await clock.ready; // the head built, its sculpted parts and the stickers loaded1239 talk.say(line); // mux the line's audio into the video yourself, starting at this frame1240 for (let i = 0; i < 300 && !stop; i++) { clock.step(1 / 30); await onFrame(i); }1241 })();1242 return () => { stop = true; };1243 }, []);1244 return (1245 <>1246 <div ref={anchor} style={{ position: 'relative', width: 360, height: 360 }} />1247 <MinimojiStage clock={clock}>1248 <MinimojiHead avatar={{ seed: 4821 }} anchor={anchor} emotes={false}1249 expression={talk.expression ?? 'neutral'} performance={talk.performance} cue={talk.cue} />1250 </MinimojiStage>1251 </>1252 );1253}1254```12551256The vanilla bundle (`/sdk/minimoji-heads.js`, what a recorder page uses):12571258```js1259import { mountHeadPerformance, createVoicedPerformance, createManualClock } from './minimoji-heads.js';1260const stage = mountHeadPerformance(el, { avatar, clock: createManualClock({ seed: 7 }), poster });1261const voice = createVoicedPerformance({ stage, loadTimeline }); // no createMedia: the line runs on the stage's clock1262await voice.select({ timeline: '/lines/hey.timeline.json', audio: '/lines/hey.mp3' });1263await stage.ready; // parts, the sticker file (minimoji-heads-bursts.js) and sprites; the poster leaves1264voice.play(); // no sound: the line starts on the stage's clock, here1265for (let i = 0; i < 300; i++) { stage.step(1 / 30); await recordFrame(stage.capture()); }1266```12671268- **One timebase with your own captions**: give `createMedia` a silent1269 element whose `currentTime` is your recorder's clock, and the line follows1270 that element (`voice.timebase === 'media'`): its `currentTime`, `paused`1271 and `ended` are the truth, exactly as live, and the steps draw it. Without1272 `createMedia` the line runs on the stage's clock (`'clock'`), and1273 `voice.time` / `voice.playing` are its time for your captions. Pause, stop1274 and replay work in both, per performance, with several stages on one clock.1275- `step(dt)` draws synchronously, inside the call, and reads no1276 `performance.now`, `Date.now`, timer or animation frame: a recorder that1277 patches those to its own tick can step and screenshot.12781279- **Audio**: a line on a stepped clock never plays (no element is made for1280 a URL, a host's element is never played). Mux the clip into the video1281 yourself, offset to the frame you started the line on.1282- **The seed** deals every head's dice on the clock: when it blinks, where1283 the eyes glance, which emote of a mood plays, a poke's reaction. Two1284 recordings match only with the same seed, so derive it from a stable id1285 for the content (a deck's id, a slide's id plus the speaker), never from1286 `location`, a URL or a served path: a server that serves each run under a1287 fresh prefix gives every run other blinks.1288- **Wait for `ready`** (`clock.ready`, or `stage.ready` on the vanilla stage)1289 before the first step you keep: lazy loads (a sculpted cut, the sticker1290 file and its PNGs, a line being loaded or built) land on the wall clock, and1291 a frame stepped before them would draw without them. **Selecting a line1292 while you record** (the next slide's)? Await `clock.ready` before *every*1293 step: the line's load is held on the clock, so it then starts on the same1294 step every run. Hold a load of your own the frames wait on with1295 `clock.hold(promise, 'what it is')`.1296- **`ready` rejects** when a load failed (the sculpted parts, a line), with1297 an Error naming each (`error.failed`), reported once, so a retry reads a1298 clean `ready`. Stickers are decoration: a failed sticker file only warns.1299- **The first frame is drawn at `ready`** (vanilla stage): the canvas holds1300 the head as mounted, with no step, so a page screenshot before your first1301 step shows it. On the vanilla stage `step(0)` only redraws the frame as1302 it stands (nothing moves, no line ticks, no dice), so it never changes1303 the frames that follow.1304- **Your own media as the timebase**: its `currentTime` is read snapped to1305 10 µs on a stepped stage, so float noise in a host clock (a page clock1306 frozen at another wall time each run) cannot tip a step that lands on a1307 line's frame edge into the next frame.1308- **The poster** stays until `stage.ready` resolves, then leaves at once1309 (no fade, no puff). A frame stepped before `ready` records it under the1310 head: only do that if you want it.1311- **Your own object as the voice's `stage`** (one that forwards the calls,1312 or a head you mount again after a lost WebGL context):1313 `voice.attach(stage)` points the voice at the stepped stage's clock and1314 drive, and again at the new stage after a remount; the line goes on from1315 where it was. The calls still go to the object you made it with.1316- `stage.capture()` answers the frame just drawn as `ImageData`, stickers1317 included, with the stage's transparency (flatten it on your background).1318- **React: yield between steps** (await your frame capture, or1319 `await new Promise(r => setTimeout(r))`). A line's face and cues reach the1320 head as props, and React commits them between tasks: steps run back to back1321 in one task would skip them. The vanilla stage needs no yield.1322- `frame`/`idleFrame` on a stepped vanilla stage only set what the next step1323 draws; a stepped stage follows no pointer, and its heads open on1324 themselves (no landing). A live stage is unchanged: leave `clock` off.13251326## 9. Keys13271328Drawing a head needs no key. A key is for the service's HTTP API1329(`Authorization: Bearer <key>`):13301331- A **publishable key** (`mk_pub_…`) may ship in the browser: it bakes1332 heads, generates avatars from a selfie or a sentence, picks moods.1333- A **secret key** (`mk_sec_…`) never reaches the browser: saving an avatar1334 (`POST /avatars`) is your server's call with it.1335- The service URL is the deployment's `.convex.site` origin, never1336 `.convex.cloud`.13371338### Several heads from one selfie13391340`POST /avatars/generate` with a publishable key makes a document from a1341selfie (`image`: base64 JPEG or PNG, downscaled to a 1024 px long edge) or1342a sentence (`prompt`). Add `candidates` (2–6) to get several likely heads to1343let the person pick from, at no extra cost: one call, one generation of the1344day's quota.13451346```ts1347const res = await fetch(`${serviceUrl}/avatars/generate`, {1348 method: "POST",1349 headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },1350 body: JSON.stringify({ image: base64Jpeg, candidates: 4 }),1351});1352const { doc, candidates, candidateSource } = await res.json();1353// candidates: [{ doc, score, differs }], best first; candidates[0].doc equals doc.1354// differs: ["hair.style"], the paths a head changes from doc (for a label);1355// score: its likelihood among these heads (they sum to 1).1356// candidateSource: "decisions" (runner-ups of the read) or "single" (doc is the only head).1357```13581359Render each `candidate.doc` with `<MinimojiHead avatar={candidate.doc} />`.1360A sure read may offer fewer heads than asked; without `candidates` the1361answer is `{doc, notes, changes, usage}` as before.13621363### Getting a key with `npx minimoji`13641365In the app's folder:13661367```sh1368npx minimoji login # prints a code and a link; the person approves it in the browser1369npx minimoji init --with-skill # mints a publishable key, writes .env.local, installs this skill1370```13711372`init` writes `NEXT_PUBLIC_MINIMOJI_KEY` and `NEXT_PUBLIC_MINIMOJI_SERVICE_URL`1373(`VITE_…` in a Vite app) to `.env.local` and never writes a secret key. A1374secret key for your server: `npx minimoji keys create --kind secret`.1375Without the CLI, mint keys at minimoji.com/developers/keys.13761377Signed in, `npx minimoji generate "red curls" --name kai` keeps the avatar in1378the account's library: `npx minimoji avatars` lists it on any machine, and1379`npx minimoji avatars get kai` prints its `avatarKey` for the app to show.1380`npx minimoji edit kai "make the hair blue"` (or `--photo me.jpg`) changes1381it: the name follows the edit to a new `avatarKey` (the first line it1382prints; `--json` gives `avatarKey` and `previousKey`), and `--as kai-blue`1383keeps the edit as a new entry instead.1384An app showing a hard-coded key keeps the old look until you update the key.13851386`npx minimoji voice kai 21m00Tcm4TlvDq8ikWAM` gives a library avatar an1387ElevenLabs voice (`--effect robot` for D.A.S.H.; `--list` shows your voices),1388and `npx minimoji say kai "[excited] Hi, I'm Billie"` makes the line, one1389ElevenLabs call on the developer's own key (`ELEVENLABS_API_KEY`, which is1390never sent to Minimoji): `minimoji-lines/hi-i-m-billie.json` plus a `.wav`.1391That JSON is a prebuilt line, played with `line.say(line, { audio: '/lines/hi-i-m-billie.wav' })`. Never hand-roll TTS timestamps1392into a line: `say` already ran `buildLine` on them.13931394### Use my Minimoji: a person's own avatar13951396A person with a Minimoji account (minimoji.com/me) can bring their avatar1397to your app. You never ask for their email: they pick one on minimoji.com1398and your app gets that pick. The host's three lines:13991400```jsx1401import { MinimojiConnectButton, loadMinimojiGrantHead, prepareBakedHead, refreshMinimojiGrant } from '@minimoji/react';14021403// 1. show the button; the popup opens on the click1404<MinimojiConnectButton minimojiKey={process.env.NEXT_PUBLIC_MINIMOJI_KEY} service={process.env.NEXT_PUBLIC_MINIMOJI_SERVICE_URL}1405 onConnected={({ grantId, avatarKey }) => saveForUser({ grantId, avatarKey })} /> // 2. store both against your user1406// 3. on launch, follow their edits and re-picks; null means they disconnected your app1407const now = await refreshMinimojiGrant({ service, key, grantId }); // { grantId, avatarKey, status, character } | null1408```14091410- One live grant per app and person: connecting again (another device, or the person reconnecting) replaces the grant, and the old id answers 410. On a 410, re-read the grant you stored before clearing it; another device may have saved a new one.1411- Refresh on the device at launch, not from your server for every user: the grant routes are limited per key and caller address.1412- The key is your app's publishable key; its label (set at1413 minimoji.com/developers/keys) is the app name the person sees, so name it1414 after the app.1415- `useMinimojiConnect({ key, service })` gives `{ connect, connecting, error }`1416 for your own button. `connect()` resolves null on "Not now", on expiry, or1417 when the popup is closed without an answer.1418- Show the head with `<MinimojiHeadPoster src={`${service}/avatars/${avatarKey}.png?size=256`} />`1419 and fetch `${service}/avatars/${avatarKey}.json` to draw it live.1420- **A private character as their avatar.** At minimoji.com/me the person can1421 pick one of their own private characters (made with `minimoji characters`)1422 for your app. The refresh then carries `character: { id, name, revision,1423 bakeVersion, speech, sha256 }` (null otherwise) and `avatarKey` stays their1424 Mini avatar. The character's file is private, so there is no public URL:1425 fetch it from the grant with your key and load it like any baked head:1426 ```js1427 const now = await refreshMinimojiGrant({ service, key, grantId });1428 const bytes = now?.character ? await loadMinimojiGrantHead({ service, key, grantId }) : null; // GET /connect/grants/<id>/head1429 if (bytes) {1430 const head = await prepareBakedHead(bytes, { sha256: now.character.sha256 });1431 // mount `head` as you mount any prepared baked head1432 } // else show avatarKey as before (no character, or it came off between the two calls)1433 ```1434 Pass `etag: lastSha256` to get `'unchanged'` (a 304) while it is the same;1435 `null` means it is no longer worn (switched back, archived, deleted). If1436 the head changed between the refresh and the fetch, the sha256 check fails:1437 refresh again, and show `avatarKey` meanwhile. Never cache1438 the bytes anywhere shared, and never send them on: they are the person's.1439 An app on an older SDK keeps showing the Mini avatar, and /me tells the1440 person so.1441- An avatar made in your own editor, which your server saves with1442 `POST /avatars`: `addToMinimojiLibrary({ service, key, grantId, avatarKey })`1443 puts it in their library and picks it for your app (a 403 if they said no1444 to that on the sheet).14451446### Upgrading an old document14471448Editors write v3 documents. If your server refuses a write below the stored1449version, upgrade a v1/v2 document before saving it; never hand-stamp `v: 3`1450(v2+ dropped some v1 rules and redraws a few parts):14511452```js1453import { upgradeAvatar } from '@minimoji/react';14541455const { doc, effects, changes } = upgradeAvatar(oldDoc);1456// doc.v === 3 and it draws the head oldDoc drew; the rest stays as sparse as it came1457// effects: the rules whose fallbacks were written in ({ id, reason })1458// changes: [{ path: 'freckles' | 'facialHair', reason }] — v2 redrew v1 freckles and facial hair; usually empty1459```14601461A v3 document (or an unknown version) comes back as the same object; it1462never throws for a version and never downgrades. The Kit's1463`MinimojiDocument.upgraded(_:)` gives the same answer.14641465### Their status: the line beside their head14661467What the person types or says on the Minimoji app's you screen (or sets with1468`npx minimoji status kai "back at 3"`) is their avatar's status, and it comes1469with the grant: `refreshMinimojiGrant` answers `status: { text, mood, gesture,1470setAt }`, or `status: null` when there is none. The mood was read once, on1471Minimoji's side, so every app shows the same face: never send `text` to1472`/expressions/pick` again.14731474```jsx1475import { MinimojiStatusBubble, refreshMinimojiGrant } from '@minimoji/react';14761477// on focus, and every 30 s while the head is on screen (a status changes without a re-pick)1478const grant = await refreshMinimojiGrant({ service, key, grantId });1479const status = grant?.status; // { text: 'on a deadline', mood: 'thinking', gesture: 'ponder-tilt', setAt } | null14801481<div style={{ position: 'relative' }}>1482 <div ref={anchor} data-minimoji="loading" style={{ width: 120, height: 120 }} />1483 {/* the tail's tip is the bubble's bottom-left: put it just above and right of the head */}1484 <MinimojiStatusBubble text={status?.text} size={14} style={{ position: 'absolute', left: '60%', bottom: '85%' }} />1485</div>1486<MinimojiHead avatar={avatar} anchor={anchor} expression={status?.mood ?? 'neutral'}1487 cue={status?.gesture ? { gesture: status.gesture, generation: status.setAt } : null} />1488```14891490- `<MinimojiStatusBubble text size tail>` is Bunch's bubble (cream, Lilita1491 One, two lines at most, a 3° tilt); `size` is the text's px (Bunch draws1492 11, 14 and 22), `tail={false}` drops the tail. No text draws nothing. Load1493 Lilita One yourself (Google Fonts) or it falls back to a rounded system font.1494- `mood` is a face name for `expression` (null when the read was unsure:1495 keep the face). `gesture` is a track for `cue` (null: none); with1496 `generation: status.setAt` it plays once per new status, not on every poll.1497- `setAt` is epoch ms: say "2h ago" if you like.1498- No React? The heads bundle (`/sdk/minimoji-heads.js`) has1499 `mountStatusBubble(element, { text, size, tail })` → `{ update, destroy }`.150015011502A status may carry an optional `voice` (`url`, `durationMs`, `words`, and optional1503`letters: {characters, starts, ends}`). Download the clip and play it with the1504line player using these timings, without transcription. In Swift use1505`try voice.line(audioFile: downloadedURL)`, then `MinimojiLinePlayer.say`;1506on the web use `lettersFromAlignment` when building the line. Partner apps1507choose their own play control. These clips are public URL media.15081509## 10. Never do15101511- Never hand-draw or keyframe talking, blinking or emoting: feed speech1512 (section 4), set `expression`, send a `cue`.1513- Never put a `<div>` (or any DOM) inside `<MinimojiStage>`; anchors live1514 outside it.1515- Never mount a second stage for more heads, or one stage per head.1516- Never draw your own loading placeholder: `MinimojiHeadPoster`.1517- Never pass a new `performance` function every render, and never drive1518 the mouth from wall-clock time: read the audio's clock.1519- Never send audio to the service; only text goes to `/expressions/pick`.1520- Never ship a secret key, or the `.convex.cloud` URL, to the browser.1521- Never store an avatar document as the user's identity: store the1522 **avatar key** from `POST /avatars`.1523- Never reach for the engine itself: it ships bundled and minified inside1524 this package, and only `@minimoji/react` and its `/characters`, `/line`1525 and `/clip` subpaths are public.15261527## 11. Swift twin15281529The same heads, moods, cues, speech and loader exist in Swift: the1530`minimoji-swift` skill (`MinimojiKit`). `cue={{ gesture: 'double-take' }}`1531is `HeadCue(.gesture(.doubleTake))`; `mouthTrack` is the recorded twin of1532`LiveVisemes` + `SpeechVoice`.