138 KiB
03 — Avatar, sprites, animation and companion shell (prefix AV)
Source of truth: CapriCore 1.0.4 tree at ~/Capri (read-only). All paths below are relative to that root unless stated. Line numbers refer to the files as read on 2026-11-11. "DIP" = Electron device-independent pixel; in the Rust port read it as logical pixel (= X11 pixel ÷ UI scale, see §8.4).
1. Purpose and scope
This subsystem is everything the user sees of Capri outside the chat text itself: the character artwork and its validation, expression selection plumbing, the local animation director, mouth sync, music dance, taps/headpats, the transparent always-on-top companion window and every satellite window (detached desktop avatar layers, teleport/tether overlays, mini composer, minimized chip, recording chip, settings/attachment window placement), click-through, docking ("perching") on other windows' edges, the startup intro, sleep visuals, procedural visual effects (signal core, CRT, glitch, dimming, float) and small HUDs (wake feedback, stopwatch).
Out of scope (owned by other specs, consumed here through §9 interfaces): the chat/turn pipeline and Gateway (the turn.* events, transcript store), TTS playback engine (only its RMS level is consumed), ASR/wake word, music detection (BPM/energy are consumed), computer-control/desktop-actions bridge (only the avatar_window query and the control border windows are covered), Settings UI panels (only the setting semantics are specified here), subtitles/reply paging (only the detached HUD host is covered), Ollama/model lifecycle (sleep unload/reload is triggered here but implemented elsewhere).
1.1 File map
| Capri file | Role | Features |
|---|---|---|
apps/desktop/avatar-catalog.mjs |
Load/validate sprite catalog, poses, music pack; public snapshots | AV-01..AV-05 |
apps/desktop/music-artwork.mjs (imported) |
Reviewed music pack loader | AV-03 |
apps/desktop/avatar-state.mjs |
Two-phase expression commit + persistence | AV-07 |
apps/desktop/avatar-protocol.mjs |
[avatar:ID] LLM marker instructions + streaming parser |
AV-06 |
apps/desktop/avatar-body-regions.mjs |
Body-part hit test on sprite canvas, seat swing | AV-16 |
apps/desktop/avatar-grip-rig.mjs |
Procedural vector grip rig (legacy dock poses) | AV-14, AV-16 |
apps/desktop/avatar-pose-motion.mjs |
Limb swing segments for reviewed poses | AV-14 |
apps/desktop/avatar-layout.mjs |
Portrait pan/zoom/registration math | AV-22 |
apps/desktop/avatar-docking.mjs |
Dock/perch geometry | AV-41 |
apps/desktop/avatar-click-reactions.mjs |
Tap sequences, spoken cues, LLM reaction | AV-17 |
apps/desktop/desktop-avatar-commands.mjs |
"return to frame"/"sit on window" commands, random destination | AV-43, AV-44 |
apps/desktop/geometry.mjs |
Window placement, hit regions, sprite alpha hit | AV-19, AV-20 |
apps/desktop/startup-intro-assets.mjs, main/startup-intro.mjs, renderer/startup-intro*.mjs |
Startup intro pack, gate, playback | AV-49 |
apps/desktop/startup-progress.mjs |
Startup stage ETA | AV-50 |
apps/desktop/sleep-service.mjs |
Sleep state machine, sleep command, Zzz caption | AV-51 |
apps/desktop/credits-epithets.mjs |
Hall-of-Fame callsigns | AV-57 |
apps/desktop/community-links.mjs |
Fixed community URLs | AV-58 |
apps/desktop/edgerunners-teaser.mjs |
Scripted browser workflow (computer control) | AV-59 |
apps/desktop/preload.cjs, avatar-composer-preload.cjs, minimized-chip-preload.cjs, recording-indicator-preload.cjs |
Renderer↔main capability surface | §5.6, §7 |
apps/desktop/main.mjs (window/avatar parts: 400–610, 1965–2040, 2497–3360, 3466–3760, 4214–4345, 4571–4610, 5690–5740, 6271–6800, 6955–7020, 7070–7080) |
Orchestration | many |
apps/desktop/main/avatar-detach.mjs |
Detached avatar/teleport controller | AV-35..AV-40 |
apps/desktop/main/pointer-controller.mjs |
Click-through + window drag + attached avatar press | AV-20, AV-21 |
apps/desktop/main/avatar-composer*.mjs |
Detached mini input window | AV-42 |
apps/desktop/main/minimized-chip.mjs |
Restore chip + recording indicator | AV-31, AV-32 |
apps/desktop/main/secure-window.mjs, window-topmost.mjs, tray-only-windows.mjs, control-window-layer.mjs |
Window flags/policies | AV-18, AV-33 |
apps/desktop/main/desktop-teleport-menu.mjs |
Windows shell verb + native watchers | AV-45 |
apps/desktop/main/avatar-settings-window.mjs |
Perch on own Settings window | AV-41 |
apps/desktop/main/linux-cursor.mjs + integrations/desktop-actions/native/linux/capri_linux/cursor.py |
Real cursor on KDE Wayland | AV-20, AV-55, §8 |
apps/desktop/main/settings-window.mjs, attachment-viewer.mjs, control-overlay.mjs |
Satellite window geometry/flags | AV-34 |
apps/desktop/main/{ipc,protocol,resources,companion-ipc,access-ipc,screen-ipc,settings-channels,confirmations,localized-dialog,call-audio*,screen-form-state}.mjs |
IPC trust gate, capri:// resource table, glue for other subsystems |
§5.6, §7, §9 |
apps/desktop/renderer/animation-director.mjs |
Local animation director + decoded cache | AV-08, AV-09 |
apps/desktop/renderer/avatar-mouth.mjs |
Visemes + mouth/eye plates + pose landmarks | AV-10 |
apps/desktop/renderer/music-animation.mjs |
Beat clock, dance, notes | AV-11 |
apps/desktop/renderer/avatar-headpat.*, avatar-tap-effect.mjs |
Headpat hearts/face, tap spark | AV-12, AV-13 |
apps/desktop/renderer/avatar-detach.* |
Overlay renderer (parked avatar, HUD, teleport canvas) | AV-35..AV-40 |
apps/desktop/renderer/avatar-teleport-motion.mjs, avatar-teleport-sound.mjs, avatar-drag-tether.mjs |
Lightning choreography, sound, tether | AV-36..AV-38 |
apps/desktop/renderer/avatar-composer.*, minimized-chip.* |
Mini composer & chip UIs | AV-42, AV-31 |
apps/desktop/renderer/{signal-fx,crt-screen,presence-model,glitch-settings,motion-settings,dimming-settings,dimming-mask}.mjs |
Visual effects & presence | AV-23..AV-28 |
apps/desktop/renderer/{wake-feedback,stopwatch-hud}.mjs |
HUDs | AV-52, AV-53 |
apps/desktop/renderer/app.js (lines 384–395, 866–1290, 1429–1620, 2035–2090, 2650–2810, 2987–3184) — not owned, but hosts the attached-avatar logic |
Integration reference | AV-08, AV-19, AV-22 |
assets/capri/sprites/v1/*, assets/capri/sprites/poses-v2/*, assets/default/capri-music-v1/*, assets/capri/intro-v1/*, assets/default/* |
Artwork packs | §3.1 |
packages/runtime/src/default-avatar.mjs |
Procedural fallback symbol generator (build-time, unused at runtime) | AV-05 |
2. Feature catalog
Priority legend: P0 companion broken without it · P1 expected by a Capri user · P2 optional/niche.
2.A Artwork, catalog and expression selection
AV-01 Sprite catalog load and validation (P0)
Source: avatar-catalog.mjs:85-275, typeInvalid 355-393, validateClips 395-435.
- Manifest
assets/capri/sprites/v1/runtime-sprite-set.json(schema 2, "animated") or fallbackassets/default/sprite-set.json(schema 1). Reject if file > 512 KiB; strip UTF-8 BOM before JSON parse. - Top-level checks:
schemaVersion ∈ {1,2};spritesnon-empty array, ≤128 entries (schema 2) / ≤64 (schema 1);canvas.width/heightintegers in 1..4096. - Per sprite:
id,pose,expressionmatch^[a-z][a-z0-9_-]{0,39}$;idunique; for persistable sprites (canPersist !== false) the pairpose/expressionis unique;filematches^[a-zA-Z0-9_-]+\.png$; realpath of the file must be strictly inside the realpath of the manifest folder; size ≤ 20 MiB; bytes start with PNG signature89 50 4E 47 0D 0A 1A 0A, length ≥ 33, IHDR width (u32 BE @16) and height (@20) equal the canvas. - Schema 2 only: reject
kind == "walk_frame"orposestarting withwalk;kind∈ {expression, pose_master, pose_expression, effect, reaction_frame, gesture_frame, micro_frame, gaze_frame, reaction_expression, transition_frame};canPersistboolean and only true for {expression, pose_master, pose_expression};labelstring ≤ 100;anchor.name ∈ {ground, seat, center}, anchor inside canvas;visibleBoundsfinite, positive, inside canvas. sha256optional per sprite, but if present must be 64 lowercase hex and equal SHA-256 of the file bytes (all shipped sprites carry it).- Labels/descriptions: schema 2 uses manifest
label; schema 1 uses the built-inEXPRESSIONStable (lines 61-82) or"<expression with spaces>"/"Expression: <expression>.". Description truncated to 240 chars. - Each frame gets a public URL
capri://desktop/sprites/<id>.png(Rust: an internal frame id; no URL needed) and a private absolutefilepath that never leaves the main process. - Clips (schema 2): array ≤ 48; id NAME regex, unique, not starting with
walk; 1..64 keyframes; each keyframe id must exist and not be of kindeffect,msinteger 50..30000; total ≤ 120000 ms. Optionaleffect {id, onFrame, width}: id must be aneffectframe,onFramemust be one of the clip frames,width === 64. - Actions (schema 2): array ≤ 32; each
idNAME, not colliding with sprite ids,animation= an existing clip id,frameandreturnTomust be persistable frames,label≤100,description≤240. Each action becomes a non-persistable choice{...frame, id: action.id, frameId: frame.id, animation, returnTo, canPersist:false}. defaultSprite(default"neutral") must be a persistable choice;autonomy(schema 2) must have booleansenabled,startExpandedand integersfirstActivityMs,activityGapMsin 5000..120000.- Portrait filter (lines 227-249): active frames are
pose == "idle"with kind ∈ {expression, micro_frame, gaze_frame, reaction_expression} or id ∈ {idle-wink_half,idle-wink_closed}, plus reviewed poses whose anchor isground. Active clips are those whose frames (and effect) are all active. Active choices are those whose frame is active and whose animation/returnTo are active. The default must be an active choice ("Default portrait is inactive"). - Shipped result (verified by running the loader): 68 manifest frames + 7 reviewed poses + 2 music frames = 77 frames; 30 portrait frames; 19 LLM-selectable choices:
neutral, annoyed, attentive, concerned, embarrassed, flirty, focused, happy, sad, skeptical, sleepy, smirk, surprised, thinking, pose-sit-floor, pose-crouch, wink(→flirty), laugh(→happy), excited(→happy); active clipsblink, speech, wink, laugh, excited. Clipsair_kiss, heart_hands, wave, floor_sit, floor_stand, edge_sit, shrug, point_left, point_rightand actionswave, air_kiss, heart_hands, shrug, point_left, point_rightare validated but inactive (kept for future rework).catalog.frames.lengthfrom the bare v1 manifest = 68, choices = 17, portrait frames = 28 (testtests/desktop-animation.test.mjs:28). - Public snapshots (what the UI layer may see):
publicSprites()= choices withoutfile;publicAnimation()={frames: portraitFrames (no file), clips, autonomy, canonicalAnchor};publicMusic()= music frames/notes without file.
AV-02 Reviewed desktop pose pack (P0 for detach/perch, P1 overall)
Source: avatar-catalog.mjs:277-353.
- Manifest
assets/capri/sprites/poses-v2/runtime-poses.json≤ 16 KiB,schemaVersion 1, exactly 7 sprites with ids and required anchor names:pose-ceiling→ceiling,pose-ceiling-upside-down→ceiling-upside-down,pose-dock-left→dock-left,pose-dock-right→dock-right,pose-sit-edge→seat,pose-sit-floor→ground,pose-crouch→ground. - File name must be exactly
capri-<id without "pose-">.pnginsidePNG/; thePNGfolder realpath must equal its literal path (no symlink), and each asset realpath must equal its literal path; size ≤ 20 MiB; PNG signature, IHDR equal to the main canvas (1254×1254), colour type byte @25 == 6 (RGBA);sha256mandatory and must match.poseNAME regex, description ≤240, bounds validated withtypeInvalid(anchor name temporarily treated asground). - Resulting frames:
kind:"reviewed_pose",expression:"neutral_small_smile",canPersist = (anchor == ground)(so only sit-floor and crouch are selectable choices/idle activities). - Pose anchors (canvas px): ceiling (626,119), ceiling-upside-down (626,88), dock-left (215,458), dock-right (1038,425), seat (609,787), sit-floor ground (643,1166), crouch ground (625,1166).
AV-03 Reviewed music pack (P1)
Source: music-artwork.mjs:6-152.
- Optional at runtime (missing manifest → empty pack), required in source/setup packaging. Manifest
assets/default/capri-music-v1/runtime-music.jsonmust be a regular non-symlink file ≤ 16 KiB, its directory realpath must equal<realpath(root)>/assets/default/capri-music-v1. - Exact keys
{schemaVersion:1, canvas:{width:1254,height:1254}, frames[2], notes[4]}. Frames: idsmusic-window(filecapri-music-window.png, anchorseat) andmusic-floor(capri-music-floor.png, anchorground), exact key set{id,file,pose,label,description,anchor,visibleBounds,face,mouth,emitters,sha256},posematches^music_(?:seat|ground)$,mouth=[x,y,angleRad (|a|≤π), width 20..60], 2 emitters, all coordinates in 0..1254. Notes: exactly01-eighth-cyan.png, 02-beamed-lime.png, 03-quarter-pink.png, 04-sixteenth-violet.pngin order, 256×256, id = file stem. - Every PNG:
^[a-z0-9_-]+\.png$, lstat regular file not symlink, realpath identity, ≤20 MiB, PNG signature, IHDR dims, colour type 6, SHA-256 match. - Frames become
kind:"reviewed_music",canPersist:false,expression:"happy".
AV-04 Missing/damaged artwork policy (P0)
Source: avatar-catalog.mjs:9-56, main.mjs:429-431, bootstrap 5694-5740.
requireCapriAvatar(root)loads v1 + poses + music; any exception, or a non-animated catalog, is rethrown with codeCAPRI_ARTWORK_INVALID(orCAPRI_ARTWORK_SOURCE_INVALIDfor installer source validation) and the user-facing repair message (§6.4).loadInstalledAvatar(root)never crashes the app: on failure it loads the fallback catalog and returnsdiagnostics {mode:"fallback", manifest:"assets/default/sprite-set.json", expectedManifest, animated:false, frames:1, failure:{code,message}}andwarning = AVATAR_REPAIR_MESSAGEwhich is shown as a notice at bootstrap. Text chat stays available. The fallback must never be presented silently as Capri.- Diagnostics are logged once:
Capri avatar: {json}.
AV-05 Procedural fallback symbol (P2)
Source: assets/default/avatar.png + sprite-set.json; generator packages/runtime/src/default-avatar.mjs:22-73 (not called at runtime).
- 1536×1536 RGBA; centre (size/2, 0.48·size); unit u = size/1536; pixels on a ring |r−190u|<5u or a diamond ||dx|+|dy|−240u|<5u are RGB(115,245,230); disc r<54u is RGB(250,100,170); alpha 255 there, transparent elsewhere. Single sprite
neutral, poseidle, expressionneutral_small_smile, description "Original digital companion symbol.". Non-animated mode: no director, no detach/teleport (canTeleportrequirescatalog.animated), taps report partbodyonly (headpat disabled), mask visible bounds computed by scanning alpha ≥16. - Rust: ship the PNG as an asset or regenerate it with the same formula.
AV-06 LLM avatar control marker (P0)
Source: avatar-protocol.mjs. Used by chat (chat-service.mjs:437,539-547,916,1094) and visual service.
- Instructions
avatarInstructions(sprites, {followUp})(lines 7-18): text quoted in §6.1. The option list is"<id>: <description>"per active choice (19 lines), example usessprites[0].id(neutral). If there are no sprites: "This interface currently has no controllable avatar. Write only your reply, without control markers." - Streaming parser
AvatarStreamParser(lines 21-145): input is text deltas; output events{type:"text", text}and at most one{type:"avatar", avatar:{id,pose,expression}, followUp?:true}.- Marker starts (case-insensitive):
[avatar:,[аватар:(Cyrillic), closing forms[/avatar:,[/аватар:,[/avatar],[/аватар]. Regex:/\[(?:(\/)(?:avatar|аватар)(?::|(?=\]))|(?:avatar|аватар):)/iu. - A buffer tail that could be the prefix of any start marker is held back (max held = longest marker length − 1).
- Inside a marker: if a newline comes before
], the control is dropped and parsing continues after the newline. If no]yet and buffered length ≤ 128 → wait; > 128 → enter discarding mode (drop everything until the next]or\n). - Frame content
identity;listensplit on;: valid only if not a closing marker,]within 128 chars, at most 2 parts, second part (if any) exactlylisten, identity matches^[a-z][a-z0-9_-]{0,39}(?:\/[a-z][a-z0-9_-]{0,39})?$. Lookup by id, or bypose/expression(first sprite registered for a pair wins; ids override). Only the first valid selection in a reply is emitted; later markers are swallowed silently. ;listensuffix guard on prose: when emitting text, any;whose tail (≤128 chars) is a prefix of;listenor matches^;listen\]?\s*$is held; on divergence (e.g. ";listen carefully") it is released; atfinish()a complete;listentail is dropped, an incomplete one is emitted.finish()drops an unfinished marker buffer.
- Marker starts (case-insensitive):
- Invariant: markers, closing tags and the
;listenflag never reach subtitles, TTS or history (teststests/desktop-avatar.test.mjs:115-201). - If a completed reply had no valid marker, chat emits a fallback selection of the default id with
source:"fallback"(chat-service 1094-1105).
AV-07 Expression state, two-phase commit and persistence (P0)
Source: avatar-state.mjs; wiring main.mjs:466-482, 2316-2334, 6278-6283, 6369-6374.
- State:
currentId(committed),pendingId, monotonically increasingrevision. Restored id fromdata/desktop/avatar.jsonis accepted only if it is a known persistable choice, else default. request(id): unknown id or same as pending →null; else set pending,revision++, return snapshot{id,pose,expression,label,url,frameId,animation,returnTo,revision}. Main emitsavatar.selectionfor the UI.acknowledge({id,revision})(UI reports image decoded): only if revision and id match the pending one; thencurrentId = choice.canPersist === false ? (choice.returnTo ?? currentId) : pendingId; persist{schemaVersion:1,id}only when currentId changed.invalidatePending(): pending = current,revision++, emit snapshot. Called at everyturn.started,turn.cancelled,turn.failed, cancel, and onavatar-failed(image decode failure for the pending id+revision).- Selections from the model are applied only while that turn is the active one and not aborted (
main.mjs:2316-2322). The UI must request decode, then acknowledge; a stale revision is ignored (UI keepsavatarRevisionand drops older selections). - The tap "awakened" complaint forces
avatar.request('annoyed')(main.mjs:2022-2025).
2.B Animation
AV-08 Animation director (P0)
Source: renderer/animation-director.mjs:1-163; driven from app.js:1484-1620 once per signal-FX frame.
- Inputs per tick:
now(ms, monotonic),{expanded, active (a turn is running), typing (draft or live ASR text), speaking (TTS playing), sleeping, reduced (OS reduced motion OR intro pending), dragging}. Output{frameId, choiceId, revision, activity, effect}ornullbefore the firstselect. select(id, revision, now): ignore unknown id orrevision < this.revision; set semantic choice,base = returnTo ?? id, clear sequence; if the choice has an animation, start that clip as areaction;attend(now); next blink atnow + 3000 + rand·3000.attend(now, interrupt):nextActivity = now + autonomy.firstActivityMs(18000); anambientsequence (or any sequence wheninterrupt) is cancelled.- Suspension compensation: if the gap since last tick > 1000 ms, shift sequence start,
nextActivity,nextBlinkby the gap (no burst of missed animation).dt = min(1000, gap). - Priority order inside
tick:sleeping→ clear sequence, pushnextActivity,nextBlink = now+3000, return frameidle-blink_closed(eyes closed) with activitysleep.- not
expanded(core/collapsed) → freeze sequence clock (start += dt), pushnextActivity, return base frame. dragging→ freeze sequence clock and pushnextActivity(continue).active || typing || speaking→attend(now)(cancels ambient activity).reduced→ clear sequence, return base frame (stable pose).- Ambient activity starts when: no sequence,
autonomy.enabled, base isneutral,now ≥ nextActivity, and none of active/typing/speaking/dragging. Activity choice: if reviewed ground poses exist,rand < 0.65 ? pose-sit-floor : pose-crouch, sequence[{pose,4200},{neutral,220}]; else "looking-around"[neutral 1500, idle-look_left 1100, idle-look_up 900, idle-look_right 1400, idle-look_down 900, neutral 2800](frames filtered to existing). - Playing a sequence: walk keyframes by age; the clip
effectis reported withprogress = age/frame.mswhile oneffect.onFrame. At the end: clear andnextActivity = now + activityGapMs (12000) + rand·6000. - Blink (base
neutraland not speaking): whennow ≥ nextBlink, age < 280 ms →idle-blink_halffor age <80 or >190, elseidle-blink_closed; afterwardsnextBlink = now + 3000 + rand·4500. - Base
surprised:idle-surprised_closedwhilenow % 4600 < 220. - Otherwise the base frame (activity
dialogue).
- Note: the manifest
speechclip is not used for lip sync (mouth plates are separate, AV-10). - Attached-portrait overrides applied after the director (app.js 1527-1562): music pose
music-floorwhen music animation is ready and no turn/draft/ASR text/tap reaction/intro/headpat (activity:"Music listening", effect cleared); tap reaction frame (AV-13) for 740 ms if not sleeping/dragging. - The renderer only swaps frames after decode, sends
avatar-frame-ready {id, revision, sequence}(sequence strictly increasing per revision) so main can switch the alpha hit mask; main ignores unknown ids, stale revisions or non-increasing sequences (main.mjs:6284-6303). Main also forwards the frame to the detached overlay (AV-35) or the perch (AV-41). - When the pose changes between frames (different
posefield) in the attached portrait, the layout is shifted so the authored face point stays fixed (moveAvatarby previous face − next face), then the home camera re-centres the face over 320 ms; transitions involving reviewed poses fade the viewport opacity 0.45→1 over 175 ms (cubic-bezier(.19,.75,.2,1)); other pose changes trigger a presence burst (glitch event). - Displayed label: activity label (
Sleeping,Looking around, frame label, or choice label), joined segments separated by" · "and localised.
AV-09 Decoded frame caches (P1)
- Renderer LRU of decoded images, limit 20 (
SpriteImages, animation-director 166-190); detached overlay LRU limit 12 (avatar-detach.mjsrendererloadFrame277-291); main-process alpha mask LRU limit 20 (main.mjs:495-532). A failed decode is evicted so it can be retried. - Alpha mask: RGBA→alpha array at native PNG size;
visibleBoundsfrom the manifest or computed (alpha ≥16). Rust: decode PNG once per frame into anArc<RgbaImage>+Arc<[u8]>alpha plane; budget ≈ 1254²·5 B ≈ 7.9 MB per frame, so keep the LRU bound (20 → ≈160 MB worst case; consider 12).
AV-10 Mouth sync and pose face plates (P0 for speech, mouth "three-level")
Source: renderer/avatar-mouth.mjs; level source renderer/voice-player.mjs:310-316 (RMS of a 256-sample Float32 time-domain analyser window, smoothingTimeConstant 0.7, taken after voice effects).
AvatarVisemes.sample(now, speaking, amplitude): if not speaking, non-finite amplitude, or amplitude < 0.006 →closedand reset. Otherwise hold the current shape for 90 ms; thenlevel = 0.25·level + 0.75·amplitude; shapesclosed < small < round < widewith hysteresis:wideif level > (0.055 when already wide else 0.075); elseroundif level > (0.022 when already round else 0.03); elsesmall.speakingispresence.speaking && !presence.sleeping.- Attached:
AvatarMouthLayer.update(image, shape, frameId); detached: main forwardsavatar-mouthshape only when it changes (app.js:1494-1500,main.mjs:6332-6341, overlaysetMouth). - Portrait frames (no pose landmarks): mouth anchor by frame id — none for frames matching
/heart_hands|kiss/;desktop-perch*(655,524);idle-wave*(658,443);idle-excited(649,421);idle-laughing,happy(648,426);skeptical,sad(644,435); default (646,430). Draw on a 1254² canvas: copy the frame, thensource-atop: dark plate polygon[-36,-12],[36,-24],[30,17],[4,29],[-33,18]fill#070812, then opening polygon[-21,1],[22,-12],[12,o],[-5,o-2]fill#f9faffwhereo = {small:7, round:17, wide:24}. Only when the sprite natural width is 1254 and shape ≠ closed. - Reviewed/music poses use a local patch (
drawPatch):radius = ceil(width·0.87)+3, square patch at (x−radius, y−radius), drawdrawPoseMouth(translate, rotateangle, scalewidth/34; outer polygon[-22,-10],[22,-9],[20,11],[7,15],[-22,11]#080911; inner[-hw,-3],[hw,-5],[0.6hw,d],[-0.57hw,d]#2a1828; teeth[-hw,-3],[hw,-5],[0.56hw,1],[-0.69hw,1]#f8fafb;(hw,d) = small (10,5), round (11,12), wide (16,8)), thendestination-inwith the frame pixels so the patch never exceeds the silhouette. - Pose landmark table (
mouth [x,y,angle,width],face,crown,eyes [x,y,r]×2,inverted) lines 7-90 for: music-window, music-floor, pose-ceiling, pose-ceiling-upside-down (angle π, inverted), pose-dock-left, pose-dock-right, pose-sit-edge, pose-sit-floor, pose-crouch. Copy verbatim. drawPoseEyes(ctx, pose, tone)(lines 144-182): per eye, rotate by mouth angle, scale r/18, clip a radius-18 circle; tonesblink/affectionate→ fill#06100f, curve from (−12,2) via control (0, −13 if affectionate else 7) to (12,2); other tones → lid polygon with tilt (boundary±7,curious±4) and line height (boundary−1,curious−1 on the first eye, else −10); stroke#52ffd9, width 2 (blink) or 3.- The CRT texture composes body + mouth patch lazily (
image()338-354) only when the revision changed.
AV-11 Music dance and notes (P1)
Source: renderer/music-animation.mjs; gate music-listening-settings.mjs:12-24.
- Ready gate
musicAnimationReady(state):enabled && hearingMusic && settings.enabled !== false && tempo ∈ [40,240] && tempoConfidence ∈ [0.45,1]. - Poses:
music-windowanchor (628,771) emitters (533,402),(764,365);music-flooranchor (641,1164) emitters (522,642),(775,591). Attached portrait usesmusic-floor; perched seat usesmusic-window, ground perch usesmusic-floor(main.mjs:2849-2858). MusicAnimation.sample(now, {active, strength(energy 0..1), autoBpm, tempo, tempoConfidence, beatAt (wall ms of a detected beat), wallTime, reduced, frameId}):- Reset if time goes backwards or the gap > 5000 ms, or
reducedtoggles. - Envelope
amount→ 1/0 with time constant 180 ms (on) / 210 ms (off), dt capped at 250 ms; fully reset whenamount < 0.003and inactive. - Legacy mode (
autoBpm === falseor tempo undefined): fixed 110 BPM. Measured mode requires tempo 40..240 and confidence > 0.rhythmAmountfollowslegacy ? 1 : confidencewith τ = 260 ms. - Beat clock: tempo glides to target with τ = 600 ms (
advanceTempo); a fresh anchor (beatAt within −100..+5000 ms of wallTime) sets a phase error = nearest-beat difference, corrected at ≤0.18·confidencebeats/s then exponential with τ = 0.9 s (correctPhase). New anchor keybeatAt:bpmtriggers a new correction. - Body is rigid and held on twos: 12 FPS hold clock (
holdMs = 83.33), using wall time in measured mode. Angle =amount·((1−rhythm)·calm + rhythm·sway·(0.5+0.5·strength))degrees withsway = sin(2πb)·0.85 + sin(πb)·0.22(legacy) orsin(2πb)·0.85 + sin(4πb)·0.12(measured),calm = 0.1·sin(2π·age/8000). Rotation about the pose anchor.dy = 0. - Notes: one birth per beat crossing (exact sub-frame time via 20-step bisection), max 7 alive, lifetime filter 3150 ms; none in reduced motion. Particles (
musicNoteParticles, lines 257-302): life2.5 + 0.65·noise(n,1)s, alternate emitter byn % 2, horizontal reach±(270 + 60·noise), rise−(185+65·noise)along a cubic, size(92+28·noise)·(0.62+0.38·smoothstep(0,0.22,p))·(0.88+0.12·strength)canvas px, alphasmoothstep(0,0.16,p)·(1−smoothstep(0.68,1,p))·amount, rotationdir·((noise−0.5)·8 + sin(πp)·14)°, sprite index(floor(n/2)+side) % 4.noise(n,seed) = fract(sin((n+1)·12.9898 + seed·78.233)·43758.5453). - Output
{active, listening, amount, frameId, frame (hold index), tempo, beatLocked, beatPhase, angle, dy, notes}.
- Reset if time goes backwards or the gap > 5000 ms, or
- Settings
notesandmotionindependently disable particles / rotation. The detached overlay accepts only an allow-listed music state (AV-35, validationmain/avatar-detach.mjs:353-388). - Note canvas: clipped to the sprite rect ∩ clip rect, device ratio
min(dpr, 2, sqrt(1048576/(w·h))), z-index 14, pointer-events none. - Music stops being animated during sleep, flights, hidden parked avatar, drags, headpat/expression plates, and in
dialoguepresentation.
AV-12 Headpat (P1)
Source: renderer/avatar-headpat.mjs, avatar-headpat.css, trigger in main avatar-drag-end (attached) / releasePress (detached).
- Trigger: a tap whose body part is
head(and avatar not sleeping). Effects: 4 hearts burst at the tap point (min 220 ms between bursts; clamp x to [43, width−43], y to [54, height−10] of the bounds), hearts CSS: sizes 24/17/12/9 px, colours#ff3e83,#ffa7dc,#ff1f63,#ffe0f0, delays 0/65/135/180 ms, 1040 mscubic-bezier(0.19,0.68,0.22,1), offsets (−10,−46),(29,−36),(−34,−25),(15,−63), rotations −9°,16°,−22°,10°; reduced motion: static hearts fading over 1000 ms. - Face plate (
showFacetrue except on music/perch-seat poses): on portrait frames drawassets/default/capri-headpat.png(resourceheadpat-face.png, 1254²) clipped tofaceOutlinepolygon (lines 6-18); on reviewed poses map the authored face with the affine transform solving 3 point pairs (eyes (608,400),(680,373), mouth (646,430) → pose eyes/mouth) (headpatFaceTransform28-43) — on reviewed poses with tone ≠ affectionate draw eye lids instead. Plate cleared after 1450 ms; hides the underlying img while visible. - Also counts as a tap for AV-17 (
part: head,headpat: true).
AV-13 Tap visual feedback (P1)
Source: renderer/avatar-tap-effect.mjs, app.js:2048-2076, overlay pulse 1176-1185.
- Spark element: size
min(56, 24 + taps·4)px centred at the tap; one at a time; animation 230 mssteps(4,end), scale 0.45→1.04 (62%)→1.3 with fade; colours by tone: boundary#ff003d(default), curious#8ff5ff, neutral#d9ff96, affectionate#ff8fae; reduced motion: opacity 0.75→0.1. - Attached portrait (non-reviewed frame): show
spriteReactionframe for 740 ms: affectionate→happy, curious→skeptical, neutral→attentive, boundary→annoyed. Reviewed pose: eye-lid plate by tone for 740 ms. Music pose: hearts only. Detached raster pose: eye lids (740 ms; blink 105 ms); grip rig: overlay the standing expression frame (skeptical/attentive/annoyed) clipped to the face polygon for 740 ms. - Suppressed entirely while
avatarTapsSleeping(AV-51).
AV-14 Secondary pose motion (P2)
Source: avatar-pose-motion.mjs, avatar-grip-rig.mjs:339-342, avatar-body-regions.mjs:5-13, overlay renderer 525-643.
- Reviewed poses: limb segments (bounds
[l,t,r,b], pivot, amplitude°, phase) — ceiling 2 segments, dock-left 1, dock-right 1, sit-edge 1 (lines 4-18). Swing =sin(2π·frame/48 + phase)·amplitudewithframe = floor(t/(1000/12)) % 48(12 FPS, 4 s cycle). Rendered by clipping the limb rectangle (5 px overlap above the hinge) and rotating around the pivot; the static image has the limb rectangles cut out (even-odd clip). Disabled in reduced motion. - Grip rig (legacy fallback when a dock frame has no raster landmarks): swing =
sin(2π·(floor(t/83.33) % 36)/36)·(ceiling ? 3.1 : 2.4)degrees applied to layers withswing:[x,y,dir]. - Legacy seat (
desktop-perch*sprites): shins below 67.8% rotated about hinge (0.58,0.68) by−1.45 + 3.05·phase,phase = min(step, 28−step)/14,step = floor(((t % 4800)·14)/2400). - Overlay pose animation runs on a 1000/12 ms timer; random blink for raster poses every 3300 + rand·2200 ms (not on music poses).
- Hit testing samples the same clock (AV-16) so the pickable pixels follow the moving limbs.
AV-15 Clip effect sprite (P2, inactive with shipped pack)
app.js:1563-1576: when the director reports effect, draw the effect frame (effect-heart) at size width·1254/visibleBounds.width, centred at sprite (0.55w + 28p, 0.36h − 35p), opacity sin(πp), scale 0.65 + 0.4p. Only air_kiss uses it and that clip is inactive; implement for future packs.
2.C Touch: body regions and tap reactions
AV-16 Body-part hit testing (P1)
Source: avatar-body-regions.mjs:15-301, geometry.mjs:83-122.
- All tests run in normalized canvas coordinates (u,v ∈ [0,1)) of the currently displayed frame, after removing the CRT lens (
screenSample, AV-25) and the crop (source).opaque(u,v)= alpha atfloor(u·W), floor(v·H)≥ 16. - Parts:
body, head, hair, torso, chest, pelvis, left-arm, right-arm, left-hand, right-hand, left-leg, right-leg, left-foot, right-foot(labels "left arm" etc.). "right-" = character's right = viewer's left (u < 0.5). - Tone (
avatarReactionTone): head→affectionate, chest/pelvis→boundary,*-leg/*-foot→curious, elseneutral. - Algorithm
avatarBodyPartAt(u,v,opaque,{dock,poseId,now,reducedMotion}):- Reviewed/music pose (
poseId∈ reviewedRegions keys: music-window, music-floor, pose-ceiling, pose-ceiling-upside-down, pose-dock-left, pose-dock-right, pose-sit-edge, pose-sit-floor, pose-crouch): for each animated limb segment (last first, skipped in reduced motion) inverse-rotate the point around the segment pivot by the current swing; if inside the segment bounds →reviewedParton the rotated point (if non-null return it). If the unrotated point lies in any segment rectangle →null(the static cut-out is empty there). ElsereviewedPart(u,v).reviewedPart: transparent → null; first matching region in table order (rectangles[l,t,r,b], or capsules[ax,ay,bx,by,radius]= distance to segment ≤ radius); none →hair. Region tables lines 115-242 (copy verbatim). - Grip rig dock (
dock-left,dock-right,ceilingwithout raster pose): mirror u for dock-right; topmost painted non-behind-head layer whose polygon contains the (inverse-swing-rotated) point; else head raster (head.clippolygon, mapped by(x−head.x)/head.scale) →head/hair; else behind-head layers. - Legacy seat (
dock == "seat", not reduced): inverse-rotate around hinge (0.58,0.68) by the seat swing; if y ≥ 0.678 and opaque → standing classifier with head offset 94/1254; else if v ≥ 0.683 → null. - Standing classifier
avatarBodyPart(lines 40-68): head if crown=v−offset ∈ [0,0.366], u ∈ [0.31,0.72] and (crown < 0.29 or u ∈ [0.445,0.58]); hair if crown < 0.366 or (crown < 0.52 and (u < 0.41 or u > 0.64)); then arms/hands (v < 0.68 and u outside the torso band; arm if v < 0.6 (perched 0.61) else hand), chest box, pelvis box, torso (v < 0.553 / perched 0.59), else leg (v < 0.86) / foot with side split at u 0.5/0.525 (perched 0.55/0.57). Copy constants verbatim.
- Reviewed/music pose (
spritePressKind(point, rect, mask, headpat)returns the part, orbodywhen headpat is disabled (non-animated fallback), or null when transparent. Drag uses a padded box instead (AV-20).
AV-17 Tap sequences and avatar reactions (P1)
Source: avatar-click-reactions.mjs:183-369, generator 110-181, cues 61-94; wiring main.mjs:1965-2047.
press({part, headpat}): headpat forces parthead; unknown part rejected. A press continues the previous sequence (count+1, capped at 11) iff: same sleeping state, (sleeping or same part), andnow − previous.at ≤ avatarTapGapSeconds·1000(default 10 s); otherwise count = 1.- While awake each press calls
onPress({part,tone,count})→ main emitsavatar.tap {part,tone,count,pulse}(pulse = the detached overlay did not already draw it) for AV-13 visuals. - Spoken cue (no inference): on the first tap of a sequence, if
now ≥ nextCueAt, after 420 ms (only if that sequence is still current, not sleeping and reactions allowed) speak one localized cue and setnextCueAt = now + 6000. Cue language = loaded TTS voice language (requires voice enabled + ready + language ≠ off). Cue index: affectionate → 0 (or 1 if current mood is "reserved"), curious → 2, neutral → 3, boundary → 4. Table of 22 languages in lines 61-85 (§6.3). The cue is played as a voice preview (voice.preview-started), not stored in history. - Model reaction: exactly when
count == 10, no reaction active, and (sleeping, ornow ≥ nextAtandnow ≥ nextAtByPart[part]) →react(sequence, until = now+2000). If not allowed yet, retry every 100 ms untiluntil, then drop. On start: global cooldownnextAt = now + 8500 ms, per-part cooldown 10625 ms (not forbody); deadlinetimeoutMs(= first-text timeout of the response timing profile) orwakeTimeoutMs(= full response timeout) while waking;variationcycles 0→1→2 (approach sentence). - Mood: current committed expression; welcoming set {happy, smirk, laugh, laughing, playful, affectionate, flirty, excited}, reserved set {annoyed, angry, concerned, focused, nervous, sad, skeptical, sleepy, thinking, tired}; sleeping → reserved.
- Cue sent to the generator:
{gesture:'many', mood, variation, awakened? | headpat? | part?}. Prompt text in §6.2. HTTP contract in §5.1. Output filter: raw ≤ 320 chars; emoji,*, backticks stripped; trimmed; ≤160 chars; ≤24 words; rejected if it contains control chars,<,>,[avatar:/[аватар:or;listen; rejected ifdone_reason == "length"or tool calls present; body > 16384 bytes rejected. - Delivery (only if still the active reaction, not aborted, not sleeping and still allowed): an assistant message
{id, turnId (fresh UUIDs), role:'assistant', status:'complete', text, createdAt, origin:{kind:'avatar-click', awakened?}}is stored in the transcript and emitted as a normalturn.started(sourceavatar-click) /turn.delta/turn.completedtriple so it is subtitled and spoken. Packet origin label showsCAPRI. - Wake by taps: while
avatarTapsSleeping, taps are silent (no visuals/cues); the 10th tap of a sleeping sequence (any parts) wakes Capri (sleep.wake()or reconnect backend), then generates an "awakened" complaint with toneboundary, and main forces expressionannoyed. - Availability (
avatarReactionAvailable, main 1965-1982): not shutting down/quitting/locked; no computer-control border; companion present (window visible or avatar-only); no active chat turn; no current chat task unless sleep phase issleeping; for non-wake: no draft busy, no interface busy,now ≥ lastSpeechUntil(5 s after any ASR activity); no initiative running, no screen-observation controller, no TTS playback, no voice preview, voice not generating. Plusbackend.phase == ready && !avatarSleepingfor normal reactions. cancel()(on new user message, ASR activity, sleep unload, lock/suspend, companion hidden, quit): clears timers, sequence, aborts the active request.
2.D Companion window and shell
AV-18 Companion window (P0)
Source: main/secure-window.mjs:5-56, main.mjs:537, 596-610, 6472-6512, 6735-6800, geometry.mjs:4-48.
- Size 480×660 logical px (constant), frameless, transparent background
#00000000, not resizable/maximizable/minimizable/fullscreenable, no shadow, no menu, skip taskbar, titleCapri, iconassets/default/icon-source.png, created hidden and shown inactive on first paint (ready-to-show). Always-on-top per preference (default on). Initially click-through. Navigation, new windows, webview attach, F5 and Ctrl+R are blocked (Rust: no equivalent needed beyond "no reload"). - Initial placement: saved
{x,y}; legacy migration:schemaVersion 1→x += 380−480, y += 680−660;schemaVersion 2→x += 460−480, y += 580−660(keeps the bottom-right anchor of older panel sizes). Display = the one matching the saved visible footprint, else nearest to the saved origin, else primary.placeInWorkArea(saved, workArea, size, margin 16): width/height clamped to the work area; missing coordinates → bottom-right corner minus 16 px; x/y clamped inside the work area and rounded. With a valid saved footprint,placeVisibleInWorkAreakeeps only the visible footprint inside the work area (transparent margins may hang off-screen). - Persistence:
moved→ debounce 350 ms →window.json(§3.2); also on window-drag end and on quit. Moving the window to another display while Capri is detached resets the detached avatar (checkDisplay, AV-46). - Close button/OS close → hide to tray (unless quitting). OS minimize → hide to tray. Renderer crash → hide to tray, cancel everything visual, reload once (no more than once per 60 s), reveal again if it was visible (
main.mjs:6710-6735, 2642-2669). - Display topology: display removed → reset detached avatar + clamp window; metrics changed (bounds/scale/rotation) → reset detached avatar + clamp unless a window drag is active.
AV-19 Hit regions and visible footprint (P0)
Source: renderer app.js:2650-2747 (publishRegions), app.js:891-911 (avatarHitRegion), main geometry.mjs:124-177, main.mjs:6387-6404.
- The UI publishes (coalesced to one per animation frame)
{controls[], sprite, footprint?}in window-local logical px:controls: bounding rects of visible elements markeddata-hit-region(clipped to the window, rects fully contained in another are dropped); when a modal dialog is open, one rect covering the whole window.sprite: the clipped sprite rect +sourcecrop (normalized) +lens {x,y,w,h,curve:0.036}when the CRT shader is active, andenabled = portrait expanded && attached && intro neither pending nor playing && not arriving.footprint: only in compact layouts (presence core, or detached "compact dock"): union of visible UI rects at their resting position (float offset removed), floor/ceil to integers.
- Main validates (
validateRegions): ≤32 controls; every rect finite, positive, inside the window (+2 px tolerance); spriteenabledboolean; crop inside [0,1] (1e-6 tolerance); lens curve 0..0.06; footprint clipped to the content size (fractional DPI) and must be integer and inside. Invalid → rejected (previous regions kept). - First footprint, or a changed footprint while not dragging, re-clamps the window: anchor = remembered
compactPlacement(visible compact bounds after the last user drag), so the compact panel reappears where the user left it.
AV-20 Click-through (P0)
Source: main/pointer-controller.mjs:73-123, geometry.mjs:90-112, Linux cursor main/linux-cursor.mjs.
- Every 16 ms while the window is visible: read the global cursor, compute the window-local point, then
interactive = windowDrag || avatarPress || point ∈ any control rect || spriteDragHit(point, sprite, activeMask). Toggle "ignore mouse events" only when the value changes (ElectronsetIgnoreMouseEvents(ignore, {forward:true})). spriteDragHit: inverse lens; then the frame'svisibleBoundsbox (mapped through the crop) padded by 12 px on each side. Taps additionally require an opaque pixel (AV-16), so transparent gaps can start a drag but never a tap.- Requirement for the Rust port: transparent pixels pass clicks to the window below; interactive controls and the sprite's padded visible box receive clicks; the transition must not need focus. On KDE (XWayland) the global cursor must come from KWin (§8.3) because X11 only sees the pointer while it is over an X11 window.
AV-21 Window drag (P0)
Source: pointer-controller.mjs:31-44, 78-98, app.js:2749-2768, main.mjs:6684-6708.
- Primary-button press on the title strip (
#handle, not on its buttons) starts a drag: remember cursor and bounds; each 16 ms tick moves the window by the cursor delta (rounded), keeping the visible footprint inside the work area of the display under the cursor when it fits; no native call when unchanged; set position+size together (avoid DPI size creep). Ends on release, window blur, hide, or after 30 s. On end: clamp to work area, updatecompactPlacementif moved, save.
AV-22 Portrait framing: pan, zoom, home camera (P1)
Source: avatar-layout.mjs, app.js:866-911, 1083-1272, 2797-2808.
- Layout
{x,y,zoom}: x,y ∈ [0,1] normalized over the pan range, zoom ∈ [0.6, 3], default{0.5, 1, 1.15}. Persisted inavatar-layout.json(debounce 250 ms). - Viewport (inside the portrait frame):
x = frame.x+12, y = frame.y+14, w = frame.w−24, h = frame.h−44,baseSize = min(430, w, h)(animated) ormin(430, w, 2h),centerFaces: true. panBounds(viewport, zoom):size = base·zoom; per axisspace = available − size,travel = max(|space|, |available − base·0.6|, 0.4·available),margin = travel − |space|,start = origin + min(0,space) − margin·(alignEnd ? 1 : 0.5)(y axis alignEnd); with centerFaces, extend so a point can be centred:first = min(start, origin + available/2 − size),last = max(start+travel, origin + available/2).avatarRect = {x: x.start + x.travel·layout.x, y: …, size};registeredAvatarRectshifts by anchor:x += (627 − anchor.x)/W·size,y += (refY − anchor.y − 75)/H·sizewithrefY = 807for seat anchors else 1166 — all frames share the floor/contact.- Drag inside the frame (primary button on the sprite region, expanded, attached): asks main
avatar-drag-start {frameId, sprite, point}first (main validates and callsbeginAvatar; refuses during detach operations); move threshold 5 px; positions use inverse-lens deltas; 30 s max; release saves. Release without movement = click (AV-17). Release outside the window with a drag beyond the dead zone = teleport out (AV-39). - Wheel over the sprite: delta = clamp(deltaY × (16 if line mode, innerHeight if page mode, else 1), ±240);
zoom' = zoom·exp(−delta·0.0015); zoom keeps the image point under the cursor fixed until an edge clamps (zoomAvatar). - Home camera:
centerAvatarFacemoves the layout so the authored face (pose landmark face or default (646,400)) is at the viewport centre without changing zoom; animated over 320 ms with ease-out-cubic (instant in reduced motion or on return arrival); runs on pose changes and when returning to the frame. Settings preview of zoom applies without persisting. - "Reset Capri position and zoom" → default layout, saved, detached avatar reset.
AV-23 Presence model: core vs portrait (P0)
Source: renderer/presence-model.mjs:1-150, app.js:384-395, 2770-2790, main.mjs:434-445, 3739-3750.
- Two layouts: core (collapsed procedural "signal core" orb 158×135 px with label
CAPRI // <STATE>near the dock) and portrait (framed character). Clicking the core or the toggle button flipspinned(persistedpresence.json) and reveals/collapses. - Fields: phase (backend phase until
ready), turnId, hasText, voiceBusy, speaking, typing, microphone, wake, pinned, expanded, sleeping, interacting (pointer over the window), lastActivity, burstAt, autonomous (= catalog autonomy enabled), voiceAttentionUntil, expandOnReply. - Rules:
begin(turn)collapses unless pinned/autonomous/within voice attention (60 s after a wake word) and bursts; first text of the active turn and speech start callreplyAttention(reveal ifexpandOnReply);setSleeping(true)reveals once; auto-collapse after 45 s idle only if expanded, not autonomous, not pinned, not sleeping, no turn, no voice, not interacting. With the shipped packautonomous = trueandstartExpanded = true, so the portrait is shown at start and never auto-collapses. - State resolution & labels/colours (
SIGNAL_STATES): starting CONNECTING#a295ff; idle STANDBY#8ef5ed; input TEXT INPUT#8ef5ed; listening LISTENING#8ef5ed; wake SAY CAPRI#8ef5ed; thinking THINKING#f4ed75; replying RECEIVING#f4ed75; buffering VOICE PENDING#f4ed75; speaking SPEAKING#f4ed75; online ONLINE#8ef5ed; offline OFFLINE#ff5679; stopping DISCONNECTING#ff5679; sleeping GOING TO SLEEP#a295ff; asleep SLEEPING#a295ff. Order when ready: speaking > (turn ? hasText ? replying : thinking) > buffering > listening (mic) > input (typing) > wake > online (expanded) > idle. Unknown → offline. The online cyan is replaced by the theme accent when a non-default theme is active.
AV-24 Signal FX layer (P1)
Source: renderer/signal-fx.mjs.
- One render loop (requestAnimationFrame) drives: presence state application, CRT draw, core orb, portrait overlays, frame damage, float motion, glitch, and calls
onFrame(=animateCharacter, AV-08). Stops when the document is hidden. - Redraw pacing: if nothing changed: reduced motion → no idle redraw except while speaking at 12 fps; else 60 fps while the intro plays or music listening is active, 30 fps expanded, 24 fps core. Canvas device ratio capped at 1.25.
- Reveal:
--reveal0→1 over 360 ms after expansion (1 immediately in reduced motion); viewport opacity0.15 + 0.85·reveal. - Core orb (
drawCore, lines 316-389, scale = min(w,h)/144): rings r=49 (α0.3), dashed r=40 rotating0.2·t, three arcs r=51 length 0.34 rad rotating0.25·t, 7 shard polygons (shardPoints, presence-model 203-213) coloured#ff315c/#eeef77/#79f9cd, rotated diamond 24 px#071019, glow ring r=11#88f6ffblur 9, ring r=7#3861e8, pupil r=3.1 wobbling; activity dots (5) under it when thinking/replying/listening (1.0) or input (0.4). - Portrait overlay (
drawPortrait): scanlines every 3 px α0.16#01040a, radial vignette, a slow retrace band moving at 0.026 px/ms (not in reduced motion), glitch slices of tinted 384-px thumbnails (cyan#00ffdd, red#ff1769, normal, violet#a668ff, yellow#edff43) and corruption cells when glitch strength > 0.04; a 14-bar VU meter bottom-right whose heights followmin(1, 5·audioLevel)while speaking. - Frame damage: when glitch strength > 0.04, three offset coloured outlines of every
[data-panel-cut]panel plus one short "interference packet" bar.
AV-25 CRT portrait shader and lens (P1)
Source: renderer/crt-screen.mjs, renderer/screen-geometry.mjs.
- WebGL single pass, scissored to the portrait rect (frame inset 12/14/24/44 as the viewport). Fragment shader (lines 6-47, ~40 lines, port to WGSL/GLSL verbatim): barrel warp
q·(1 + curvature·|q|²)with curvature 0.036; per-row damage (27 rows, reseeded 17×/s, threshold noise > 0.69) shifting up to ±24 px × glitch; slow wavemotion·sin(83·st.y + 1.3t)·0.32; RGB split0.48 + glitch·(1.4 + 6·damaged)px; scanline0.86 + 0.14·cos(2.094·y); phosphor triad1 − 0.065·sin(2.094·x + {0, 2.09, 4.18}); vignette1 − 0.14|q|²; gain 1.13; flicker1 + motion·0.009·sin(8.2t); additive noise(0.02,0.035,0.03)·noise.time = 0andmotion = 0in reduced motion. - Texture = composed image (intro canvas, or music-rotated body, or mouth/headpat plates, or plain frame), re-uploaded only on revision change. When WebGL fails/loses context →
fallbackmode: the plain sprite (with DOM plates) is shown. - Hit-test parity: pointer coordinates are mapped with the same lens
screenSample(x' = lens.x + (x·(1+c·r²)+1)·w/2, normalised to [−1,1]) before alpha sampling. The Rust renderer must use one function for both the shader and hit testing.
AV-26 Visual glitch schedule (P2)
Source: renderer/glitch-settings.mjs, presence-model.mjs:152-200, signal-fx.mjs:254-270.
- Settings
glitchEnabled(true),glitchStrength0..100 (65),glitchIntervalSeconds10..120 (35),glitchEvents(true). - Event requests = max(presence
burstAt, time of last thinking/speaking/offline state change). A request newer than the last seen one fires an event only ifnow − eventAt ≥ 6000 ms(coalesced, never queued). Clicks, drags, zoom, history/settings never request bursts. - Envelope by age (ms): <0 or >820 → 0; <85 → 0.96; <170 → 0.22; <310 → 0.86; <430 → 0.08; else
0.48·(1 − (age−430)/390). Ambient bursts: one per interval cycle at offset(0.2 + 0.6·r)·intervalwithrfromsignalRandom(cycle + 2078), scaled 0.8. Strength = max(event, ambient)·strength/100. Offsetsx = (r−0.5)·22·s,y = (r−0.5)·5·s, seedfloor(now/56).signalRandom= LCGstate = state·1664525 + 1013904223 (u32), valuestate/2^32. - Disabled by reduced motion and during the startup intro. Settings preview applies for 900 ms and immediately fires one burst; the companion reports glitch frames to the Settings window for its preview (
capri:glitch-frame, timestamp must be within ±2000 ms).
AV-27 Floating idle motion of the panel (P2)
Source: renderer/motion-settings.mjs, presence-model.mjs:189-192, signal-fx.mjs:200-253.
- Settings
floatEnabled(false),floatAmplitude0..24 px (6),floatPeriodSeconds4..30 (10). TargetA·(0.75·sin φ + 0.25·sin(0.53φ + 1.4)),φ = 2π·t/period; clamped tofloatLimits(keep all visible UI rects ≥4 px inside the window); easedy += (target − y)·0.065per frame; frozen while the pointer is over the window or a text field has content; off in reduced motion. The float offset is removed when computing hit regions/footprint (re-published at most every 90 ms when moved > 0.08 px).
AV-28 Window dimming backdrop (P1)
Source: renderer/dimming-settings.mjs, renderer/dimming-mask.mjs, main.mjs:446-455, 3293-3308.
- A dark shade behind the panel UI to improve legibility: settings
{enabled (true), level 0..85 % (35), softness 0..320 px (140)}; persisteddimming.json(debounce 200 ms). Shade bounds: whole window, or in compact layouts the union of visible UI rects + 12 px (float offset removed). Edge alpha = separable Gaussian featherfeather(d, R) = (erf(6d/R − 3) − erf(−3)) / (erf(3) − erf(−3))withR = min(softness, w/2, h/2)(Abramowitz–Stegun erf approximation, lines 3-12), mask rasterised at ≤1024 px and stretched; colour/strength--shade-strength = level/100.
AV-29 Tray icon and menu (P0)
Source: main.mjs:3466-3662, 3708-3716, 6769-6779, 2238-2257.
- Icon
assets/default/icon-source.png(Linux), tooltipCapri — <Microphone (<lang>)>, <App awareness active; no screen capture>orCapri desktop companionwhen neither is active. Left click → Show Capri; right click → menu. - Menu items in order (labels localized via the UI catalogue; Initiative and Screen snapshot get " (BETA)"): Show Capri · Settings · Teleport Capri (only when teleport possible and attached or detached-available) · Return to frame (only when detached) · Focus mode (checkbox) · Reset to bottom-right corner · Reset Capri position and zoom · Window dimming… · Voice (checkbox) · Voice effects… · Qwen model… · Languages… · File access… · Timers and reminders… · Application access… · Initiative… · Screen snapshot… · Open screenshots folder · Stop screen observation (enabled while watching) · Microphone () (checkbox, enabled when ASR installed and backend ready/asleep) · Microphone input ▸ (device radio list) · Microphone settings… · Always on top (checkbox) · — · Updates… · Reconnect (disabled while connecting/shutting down) · Hide to tray · — · Quit and unload models. Items that open a panel first restore the companion.
- The same menu is shown by the in-panel menu button (
capri:menu).
AV-30 Hide, focus mode, avatar-only, restore paths (P0)
Source: main.mjs:2577-2677, 3166-3173, 4571-4609, 6776-6795, 6994-7012.
- Hide to tray: hide the window; if already hidden, stop background companion activity (
stopHiddenCompanion: clear perch, cancel taps, reset detached avatar, hide Settings, stop CPU/load samplers, discard screens, stop initiative/observer); then show the minimized chip if enabled and not in focus mode/locked/quitting. - Collapse (hide button): attached → hide to tray; detached → avatar-only mode: the panel hides, the detached avatar stays (perch released first if it follows the Settings window).
- Restore (
restoreCompanion): leave focus mode and avatar-only, hide chip, show (focus + emitfocus-inputwhen requested, else show inactive), recover a crashed renderer. - Focus mode: hides chip, Settings and companion; wake word/replies do not reveal it; leave via tray click, "Show Capri", global shortcut or second launch.
- Global shortcut Ctrl+Shift+Space: if visible and focused → hide to tray, else restore.
- Second instance → restore. File signals polled every 400 ms:
data/run/desktop.stop→ delete and quit;data/run/desktop.show(JSON{show:true, launchNonce}) → delete, restore, publish launch receipt. - Wake restore: a non-manual, non-follow-up wake word while hidden shows the companion if
restoreFromTrayOnWake(not in focus mode/avatar-only). - Window actions accepted from the UI/Settings (
capri:window-action):leave-frame,return-to-frame,always-on-top <bool>,reset-position,reset-avatar,reconnect,hide,focus-mode [bool],portrait [bool],microphone,quit,sleep(asks confirmation "Unload models and sleep?").
AV-31 Minimized restore chip (P1)
Source: main/minimized-chip.mjs, renderer/minimized-chip.*, minimized-chip-preload.cjs.
- 52×52 transparent frameless always-on-top skip-taskbar window, shown inactive at the bottom-right of the primary work area (16 px margins) or at its remembered position (session-only, clamped to the work area of the display under its centre). A cut-corner SVG badge with the brand symbol, accent/background colours from the theme, localized title "Show Capri", 650 ms glint animation, reduced-motion aware.
- Click (pointer: only if no drag happened) or keyboard activation → hide chip + restore companion. Drag: start/move/end/cancel actions; movement threshold 4 px; window follows the cursor delta clamped to the work area of the display under the cursor; gesture timeout 30 s; Escape, blur, hide, pointer capture loss cancel. Display add/remove/metric change cancels and re-clamps. Renderer crash destroys it; load failure → hidden and
onUnavailable. - Only the chip's own page may call its two actions (sender identity check).
AV-32 Recording indicator chip (P2)
Same class with url recording-indicator.html, channel capri:recording-stop, 260×40, top-right (12 px from top, 16 px from right), not draggable, label RECORDING ACTIONS · ESC, title "Stop recording", RTL for ar/he/fa/ur/ps. Clicking stops workflow recording; closing/unavailability also stops it. Hidden on lock/suspend. (Workflow recording itself belongs to the workflows spec.)
AV-33 Layering and taskbar policy (P0)
Source: main/window-topmost.mjs, main/tray-only-windows.mjs, main/control-window-layer.mjs.
- Every app window is kept off the taskbar (re-applied on show/hide/minimize/restore).
- Companion "Always on top" preference (default true; Settings preview possible).
ControlWindowLayer: while computer control drives the desktop, temporarily drop always-on-top and push the companion to the bottom without changing focus or the saved preference; restore the latest preference afterwards (also on failure). - Detached avatar overlays and the mini composer use the highest level ("screen-saver") and are re-raised every 750 ms and on every show/app focus change, without stealing focus.
AV-34 Satellite windows: geometry and flags (P1)
- Settings window (
main/settings-window.mjs:5-16, 325-460): frameless, opaque#07131c, min 400×400, skip taskbar, always-on-top mirrors the companion, created with opacity 0 and shown only after first paint. Docked bounds:width = min(680, area.w − 24),height = min(max(400, owner.h), area.h − 24),x = owner.x − width − 12(orowner.x + owner.w + 12if that leaves the work area), clamped with 12 px margins; follows the companion while docked; any user move/resize >1 px undocks. Hidden with the owner. Help popover: 210..344 px wide beside Settings within 96 px. Opening Settings consumes/skips a pending startup intro. - Attachment viewer (
main/attachment-viewer.mjs): fullscreen on the companion's display, opaque, always-on-top if the companion is; Escape closes; no reload. - Computer-control border (
main/control-overlay.mjs): one fullscreen, transparent, click-through, non-focusable, top-level window per display (parent = companion), cursor relayed every 33 ms; must cover the display exactly (Linux tolerance ±2 px for XWayland 1-px shortfall). Behaviour belongs to the computer-control spec.
2.E Leaving the frame: detached avatar, teleport, docking
AV-35 Detach lifecycle and state machine (P0 for the "desktop companion" experience)
Source: main/avatar-detach.mjs:203-1502; wiring main.mjs:2679-2775, 6512-6578; renderer renderer/avatar-detach.mjs.
- Phases:
attached → leaving → detached ⇄ teleporting → returning → attached;reset()returns toattachedfrom anywhere (destroys all overlays, clears reply/status/mouth).available⇔ phasedetachedand no operation/relocation in flight. Every phase change is emitted to the UI (avatar.detach {phase}); onattachedthe avatar-only mode ends and the perch is cleared; the home UI shows/hides the portrait accordingly (CSS: frame leave animation 210 msclip-path inset(47%)+fade; return arrival 210 ms reopening mask; portrait hidden while detached/teleporting/returning; the panel switches to the compact dock layout). - Preconditions (
canTeleport): animated catalog, not locked/shutting down/quitting, no computer-control border, companion window exists and is visible or avatar-only. - Leave (button "Leave frame", tray "Teleport Capri", drag-out, perch, command): the UI supplies departure geometry
{frameId, rect (square sprite rect, window-local), clip (visible part)}(capriAvatarDepartureGeometry; reveals the portrait if collapsed). Validation: rect square within 1 px,rect.w ≤ 3·max(window w,h), visible clip ≥ 12×12. Work area of the companion's display must be ≥100×100. Scale (sprite square size) =min(240, max(108, portraitScale), 0.42·area.w, 0.48·area.h). Destination: the cursor/drop point (AV-39), a dock seat (AV-41), or a random landing: insetmin(18, 4% w, 4% h), 24 random top-left candidates + 4 corners, accept the first that does not intersect the companion window and is ≥gap = min(180, 0.29·diag)from the origin, else the best bydistance + (clear ? gap : 0); already used keys are skipped (sessionseenset). - Hop (tray "Teleport Capri" while detached, or drag/drop): from the current point to a cursor destination or a fresh random landing.
- Return (button "Return to frame", tray, command, drop onto the companion): ask the UI for return geometry (
capriAvatarReturnGeometry, which measures the expanded portrait with a face-centred layout, optionally aligned to the drop point and grab offset) within 5 s; fly back; after the animation commit the measured layout (saved) andreset(). If the portrait is not visible on the home display → immediate reset. - Travel (
travel, lines 1391-1502): a full-display transparent overlay per involved display (work-area sized), load +prepare(timeout 5000 ms each), show inactive and verify the overlay covers exactly the work area (else fail), set phase,play(both displays start at now+48 ms when crossing), wait (5000 ms), then commit: crossing → retire the source overlay after its effects settle (≤5000 ms) and adopt the target; record the new point; phasedetached; restart pointer tracking; re-send reply/status/mouth/music. Any error →reset()(avatar back in the frame) and the error is reported ("Could not teleport Capri."). - Sprite scale is clamped again per target display (
min(scale, 0.42·w, 0.48·h)). Positions: free landings keep the whole sprite square inside the work area (cursorLanding); docked poses keep the pose's visible bounds inside (anchoredPoint); reviewed/music poses carry afocuspoint = centre of visible bounds (used as bolt endpoint and HUD anchor). - While detached the current animation frame chosen by the director is mirrored onto the parked sprite (
updateFrame): pure placement changes stream positions (latest wins, one in flight, settle after 120 ms); anchor or sprite changes swap the image and re-anchor so the contact point stays put; a pose change flashesbrightness(1.27) saturate(1.1)→ none over 145 ms (not in reduced motion).
AV-36 Teleport lightning choreography (P1)
Source: renderer/avatar-teleport-motion.mjs, renderer/avatar-detach.mjs:1064-1172.
- 24 fps timeline, 28 frames (≈1.17 s):
departureframes 0–5,transit6–14,arrival15–26,idle≥27. A crossing source overlay (no parked arrival) stops afterboltOnlyFrames = 21. - Profile from settings (0..100 → 0..1): intensity (default 0.75), jaggedness (0.78), branches (0.75),
reducedFlash.travelStrength = min(1, distance/(2·scale)),energy = 0.38 + 0.88·intensity,boltScale = scale·travelStrength·energy, route amplitudemin(0.53·scale, 0.31·distance)·travelStrength·(0.18 + 1.13·jaggedness). Route: 7 seeded corners at t ≈ 0.15, 0.29, 0.40, 0.56, 0.69, 0.79, 0.90 with lateral offsets (−0.28, 0.62, −0.59, 0.76, 0.24, −0.7, 0.15)·amplitude (random mirror, jitter), each skipped below a jaggedness minimum, plus "elbow" cracks when jaggedness > 0.55; points clamped 12 px inside the display unless crossing displays. Bolt start/end = sprite focus (or anchor − 0.52·scale vertically). - Departure: the sprite is revealed through a shrinking jagged aperture
[1,1,1,0.74,0.37,0], tinted red (#ff003d,source-intint image)[0,0,0.13,0.57,0.93,1](×0.5 with reduced flash), shards/"break" strength[0,0.25,0.37,0.7,0.87,1,0]; the bolt head starts at frame 4. Transit: bolt head at[0.11,0.19,0.30,0.42,0.55,0.67,0.79,0.90,1]per frame, tail = head − 0.61 (0.44 reduced flash), branches grow along it. Arrival: the bolt tail retracts through cut stages; the destination sprite assembles in 4 horizontal bands with jagged plates (aperture[0,0.21,0.42,0.66,0.85,1]staggered by band) and red seams; an arrival strike slash of reach[0.15,0.34,0.26,0.19,0.11,0.055]·scale. - Ink colours: red
#ff003d, filament#cc123c. Geometry helpers (ribbonwith asymmetric edges and notches,drop,drawBranches,drawBreak,retractBolt,assemble,arrivalStrike) are fully deterministic fromseed(u32 fromrandomInt(2^32)) — port the drawing code literally (lines 1-619) onto a 2D vector rasterizer. - Effect canvas covers only
teleportViewport(union of route points and both sprite boxes, padded14 + 0.85·max(scale)), device ratiomin(dpr, 2, sqrt(8 294 400 / area)). - Interactive arrival: once past frame 15 and the destination sprite has been drawn, the travel promise resolves so the user can grab Capri while the remaining effects finish; the first grab calls
finishArrival. - Reduced motion (OS preference) or
dialoguepresentation → no animation, instant relocation.
AV-37 Teleport sound (P2)
Source: renderer/avatar-teleport-sound.mjs, app.js:2077-2094.
- Played on phase
leaving,teleporting,returningunless presetoffor presentationdialogue. Presets (teleportSound):spark0.16 s triangle 1900→630 Hz + high-passed (1900 Hz) noise;thunder0.37 s sine 132→45 Hz + low-passed (420 Hz) noise;pulse0.26 s sine 360→920 Hz, no noise. Envelope from 0.0001 exponential to peak (0.14 thunder, 0.085 others) in 25 ms, exponential to 0.0001 at the end; frequency sweep reaches its target at 70 % of the duration; noise = uniform ±0.6. Start 7 ms after scheduling. Failure to open audio is silent.
AV-38 Drag lightning tether (P1)
Source: renderer/avatar-drag-tether.mjs, main/avatar-detach.mjs:123-155, 944-1080.
- Shown while a sprite drag (attached or detached) is beyond the dead zone and
avatarDragTetheris on (and presentation ischaracter), intensity > 0. Endpoints: press point → current cursor. Repainted at most every 20 ms and only when the cursor moved; animated at display rate (Date.now()clock shared by all displays so slices align). - Geometry (
dragLightningGeometry):pieces = clamp(ceil(d/24), 4, 42);spread = min(19, 0.14·d)·mix(0.15, 1, chaos); node bend(noise·1.6 − 0.8 + 0.23·sin(11t + 1.92i))·spread·sin(πt)(no wobble in reduced motion); branchesmin(19, ceil((1 + d/115)·density·(reduced ? 1 : 2))); sparksmin(72, ceil((6 + d/12)·density·(reduced ? 0.3 : 1))), every 4th is a bright spark, others embers.noise(seed,i):m = imul(seed ^ imul(i, 0x9e3779b1), 0x85ebca6b); ((m ^ (m>>>13))>>>0)/2^32; seed = press start time (u32). - Stroke stack (colour, width, opacity): bolt
#ff164b8 0.13 · bolt#fa174a4 0.29 · branches#ff19461.0 0.64 · bolt#ff3e5c1.45 0.98 · embers#fa234b1.5 0.63 · sparks#ff75871.7 0.95; bevel joins, round caps. - Multi-display: one transparent click-through layer per display whose work area (±55 px) the segment crosses; while attached, the companion window rectangle is excluded by an even-odd clip. Layers are destroyed when no longer crossed and on release.
AV-39 Detached avatar pointer interaction (P0)
Source: main/avatar-detach.mjs:816-972, 1135-1208; main.mjs:2726-2775, 6420-6461.
- Pointer tracking every 16 ms (33 ms in
dialogue) while detached and visible: interactive = active press || reply-control press ||canGrab(padded visible box, or HUD box in dialogue) || reply tab/arrow hit; toggles click-through only on change (forced re-apply after restacking). Collapsed-reply tab reveal: cursor within 42 px of the body's visible bounds or 26 px of the tab (unless the user just collapsed it there). - Press (left button): reply tab/arrows take precedence (toggle/step on release if same target and same turn); else a grab records
{point, time, part, grabOffset = (anchorPoint − cursor)/scale}and finishes a pending arrival. - Release: >30 s → ignored. Moved (≥5 px) and beyond the dead zone (
avatarDragCanTeleport: distance ≥ 5 and >avatarDragTetherDeadZone(default 30, clamp 0..120) + 1e-6, measured on the final cursor vector in logical px) →teleportToCursor(cursor, grabOffset): if the cursor is over the visible companion footprint → return to frame with the grab alignment; else try docking (AV-41); else hop so the grabbed sprite point lands under the cursor (cursorDestination); a previous perch is released and the arrival uses the current standing frame. Not moved, < 800 ms and same part under the release → head: headpat (unless sleeping) + tap record; other part: pulse at the tap point + tap record (AV-13, AV-17). Dragging never counts as a tap. - Attached drag-out (
capri:avatar-drag-end): if the press moved beyond the dead zone and the release point is outside the window by more than 24 px (avatarDropOutside), target = window origin + release point, grab point = normalized sprite point under the press (spriteGrabPoint) → try dock, else leave the frame to that point. Releases inside are just a pan. - Release beyond a non-focusable overlay (cursor left the overlay before release) must still be delivered (Windows: native mouse hook; see §8.5 for Linux).
AV-40 Detached HUD: status badge, floating reply, dialogue presentation (P1)
Source: renderer avatar-detach.mjs:745-1010, renderer/detached-reply-layout.mjs; main validation main/avatar-detach.mjs:300-475, main.mjs:6304-6368.
- Inputs: status
{text ≤100 (localized presence label), color #rrggbb}plussleepingand localized labels (Show reply, Hide reply, Previous part of this reply, Next part of this reply, Subtitle playback); reply{text ≤512, turnId ≤128, fullText ≤16000, autoCollapsed}with a bounded history for paging. Ignored while attached. - Layout (
detachedReplyLayout): margin 8, gap 24; badge above the crown (crownY − 16 − h) centred on the face x; bubble side:belowif the pose is inverted (upside-down) and it fits, elseaboveif it fits, elseleft/rightif ≥ min(144, width) available (wider side), elsebelow. Tab 28×20 above/below or 24×(20..32) on the side, sharing the badge border; HUD = union(badge, tab, bubble unless collapsed). Reply width ≤ min(344, viewport − 16); pages fitfloor((min(150, innerHeight−88) − 18)/lineHeight)lines; arrows only if >1 page; bubble tail 16 px toward the face (0 in dialogue). The HUD moves with the avatar (clamped 8 px). - Hovering the expanded HUD holds the subtitle auto-hide (
avatar.reply-hover). - Dialogue presentation (
detachedStyle = "dialogue"): the character is hidden; only a green dialogue box (#092316f5, line#59ed91) floats; it is the grab handle; no lightning, sound, music or mouth animation; teleports are instant.
AV-41 Docking / perching on windows and display edges (P1)
Source: avatar-docking.mjs, main.mjs:2776-2985, 3035-3160, main/avatar-settings-window.mjs, Linux bridge capri_linux/main.py:739-796.
- Triggers: drop after a drag (attached drag-out or detached drop), the "sit on window" command (AV-43), roaming (AV-44).
tryAvatarDock(point): display nearest the point;reserved= point inside the display but outside its work area (panel strip); radius =avatarSnapRadius(default 36, 12..100 logical px). Screen dock (nearestDisplayAvatarDock) wins immediately when the point is in a reserved strip or withinmin(12, radius)of an edge; in a reserved strip with no screen dock → no dock. Otherwise ask the native bridge for the nearest non-Capri window edge withinmin(400, round(radius·scale))native px; if its contact point is visible in the work area → perch on that window; else fall back to the screen dock; else none (caller teleports freely).- Edge selection (
nearestAvatarDock): along-edge fraction must be within [0.04, 0.96]. Windows: top edge →seat(sit on the title bar), bottom edge →ceiling(hang below), left/right → side grips. Displays: top →ceiling(upside-down hang), left/right grips, floor (work-area bottom, sits above a bottom panel; may also capture a drop inside a bottom reserved strip). Ties: nearest distance. A dock is invisible (rejected/hidden) if the contact lies outside the work area ±1 px, or for a window underside coinciding with the work-area bottom (contact.y ≥ bottom − 2). - Pose per dock: floor→
pose-sit-floor, seat→pose-sit-edge, display ceiling→pose-ceiling-upside-down, window underside→pose-ceiling, side→pose-dock-leftwhen the sprite is on the right of the contact (window right edge, display left edge) elsepose-dock-right. Contact = pose anchor. - Default seat when perching by command/roam:
{kind:'seat', edge:'top', fraction:0.66}. - Window qualification (Linux bridge
avatar_window): current desktop/visible workspace only, not minimized, PID ≠ Capri (except the explicitly allowed own Settings window id), PID owned by the same user and not a Capri executable, size ≥ 160×100, non-empty title, optional title/process-name substring match (case-insensitive), optional identitywindowId/processId/startedAtTicksequality. "Near" query: inner span excludesw/25,h/25at the ends; nearest edge distance ≤ radius (1..400); ties → first in stacking order; distance 0 short-circuits. Without "near": the focused window if it qualifies, else the topmost qualifying one. - Perch tracking: own Settings window → local window events (move/resize/show/focus/hide/minimize/restore/closed; minimized → hidden); external windows → native follow events (Windows) or 1800 ms polling (current Linux). Updates:
closed→ stop perching (stay on the desktop, standing frame);hiddenor contact outside the work area → hide the parked avatar and keep watching; visible → move with the window (same display: placement update; other display: rebuild overlay there, no teleport). While the user holds the avatar, position updates are deferred. Music readiness switches seat/ground perches tomusic-window/music-floor.
AV-42 Detached mini composer (P1)
Source: main/avatar-composer.mjs, main/avatar-composer-bridge.mjs, renderer/avatar-composer.*, main.mjs:2501-2567, 4214-4346.
- A small focusable transparent always-on-top (top level) window shown only while the avatar is detached and available, the companion is present, not focus mode, not locked, not shutting down, and not dismissed by the user (Escape/close/minimize dismiss until the next phase change or window show).
- Modes:
compact(124×44, mic/keyboard/menu buttons),text(344 wide, height 60 grows with content up to 240),expanded(after "menu" restored the panel). Keyboard button toggles compact↔text and focuses the text field; menu button toggles the main panel (collapse to avatar-only ↔ restore). - Placement (
avatarComposerBounds): centred under the body (gap 8) — body = sprite visible bounds in desktop coordinates (or the HUD in dialogue); if it does not fit below: beside right, beside left (bottom-aligned), else above; clamp to the work area; if it overlaps the HUD, recompute around the union of body+HUD, then try below/above/right/left of the HUD. Cached work area per display, refreshed on display events. - Visibility: shown when pinned (focused, has draft, attachments, mic listening/loading, file picker open, pending action) or the pointer is within 90 px of its rectangle; otherwise fades out after 180 ms and becomes click-through immediately. Re-raised every 750 ms while visible.
- Actions (strictly validated, §5.6):
edit {draft ≤8000, revision},submit,attach(native file dialog; ≤4 files; 8 MiB each, 32 MiB for mp4/webm; unsupported extensions forwarded empty so the owner explains),remove {id},microphone,keyboard,menu,thinking {enabled},internet {enabled},paste-files {files[≤4] {name, bytes}, overflow}. All are forwarded to the main companion UI which owns drafts, attachments and sending (10 s ack timeout, ≤32 pending). State pushed to the composer is sanitized (strings bounded, theme colours regex-checked).
AV-43 Movement commands (P1)
Source: desktop-avatar-commands.mjs:15-49, main.mjs:1154-1158, 2986-3033.
- Checked before any inference on every typed/spoken message (after NFKC, trimming trailing
.!?…, a leading "Capri"/"Капри" vocative, "please"/"пожалуйста"). Patterns (§6.5): return/go back/come back/teleport back to your/the frame/window/home (and Russian equivalents) →return; "sit/perch on (top of) (the) (active/current) window [title]" or "sit/perch on (top of) (the)