770 lines
138 KiB
Markdown
770 lines
138 KiB
Markdown
# 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 fallback `assets/default/sprite-set.json` (schema 1). Reject if file > 512 KiB; strip UTF-8 BOM before JSON parse.
|
||
- Top-level checks: `schemaVersion ∈ {1,2}`; `sprites` non-empty array, ≤128 entries (schema 2) / ≤64 (schema 1); `canvas.width/height` integers in 1..4096.
|
||
- Per sprite: `id`, `pose`, `expression` match `^[a-z][a-z0-9_-]{0,39}$`; `id` unique; for persistable sprites (`canPersist !== false`) the pair `pose/expression` is unique; `file` matches `^[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 signature `89 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"` or `pose` starting with `walk`; `kind` ∈ {expression, pose_master, pose_expression, effect, reaction_frame, gesture_frame, micro_frame, gaze_frame, reaction_expression, transition_frame}; `canPersist` boolean and only true for {expression, pose_master, pose_expression}; `label` string ≤ 100; `anchor.name ∈ {ground, seat, center}`, anchor inside canvas; `visibleBounds` finite, positive, inside canvas.
|
||
- `sha256` optional 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-in `EXPRESSIONS` table (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 absolute `file` path 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 kind `effect`, `ms` integer 50..30000; total ≤ 120000 ms. Optional `effect {id, onFrame, width}`: id must be an `effect` frame, `onFrame` must be one of the clip frames, `width === 64`.
|
||
- Actions (schema 2): array ≤ 32; each `id` NAME, not colliding with sprite ids, `animation` = an existing clip id, `frame` and `returnTo` must 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 booleans `enabled`, `startExpanded` and integers `firstActivityMs`, `activityGapMs` in 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 is `ground`. 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 clips `blink, speech, wink, laugh, excited`. Clips `air_kiss, heart_hands, wave, floor_sit, floor_stand, edge_sit, shrug, point_left, point_right` and actions `wave, air_kiss, heart_hands, shrug, point_left, point_right` are validated but inactive (kept for future rework). `catalog.frames.length` from the bare v1 manifest = 68, choices = 17, portrait frames = 28 (test `tests/desktop-animation.test.mjs:28`).
|
||
- Public snapshots (what the UI layer may see): `publicSprites()` = choices without `file`; `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-">.png` inside `PNG/`; the `PNG` folder 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); `sha256` mandatory and must match. `pose` NAME regex, description ≤240, bounds validated with `typeInvalid` (anchor name temporarily treated as `ground`).
|
||
- 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.json` must 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: ids `music-window` (file `capri-music-window.png`, anchor `seat`) and `music-floor` (`capri-music-floor.png`, anchor `ground`), exact key set `{id,file,pose,label,description,anchor,visibleBounds,face,mouth,emitters,sha256}`, `pose` matches `^music_(?:seat|ground)$`, `mouth` = `[x,y,angleRad (|a|≤π), width 20..60]`, 2 emitters, all coordinates in 0..1254. Notes: exactly `01-eighth-cyan.png, 02-beamed-lime.png, 03-quarter-pink.png, 04-sixteenth-violet.png` in 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 code `CAPRI_ARTWORK_INVALID` (or `CAPRI_ARTWORK_SOURCE_INVALID` for 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 returns `diagnostics {mode:"fallback", manifest:"assets/default/sprite-set.json", expectedManifest, animated:false, frames:1, failure:{code,message}}` and `warning = AVATAR_REPAIR_MESSAGE` which 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`, pose `idle`, expression `neutral_small_smile`, description "Original digital companion symbol.". Non-animated mode: no director, no detach/teleport (`canTeleport` requires `catalog.animated`), taps report part `body` only (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 uses `sprites[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;listen` split on `;`: valid only if not a closing marker, `]` within 128 chars, at most 2 parts, second part (if any) exactly `listen`, identity matches `^[a-z][a-z0-9_-]{0,39}(?:\/[a-z][a-z0-9_-]{0,39})?$`. Lookup by id, or by `pose/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.
|
||
- `;listen` suffix guard on prose: when emitting text, any `;` whose tail (≤128 chars) is a prefix of `;listen` or matches `^;listen\]?\s*$` is held; on divergence (e.g. ";listen carefully") it is released; at `finish()` a complete `;listen` tail is dropped, an incomplete one is emitted. `finish()` drops an unfinished marker buffer.
|
||
- Invariant: markers, closing tags and the `;listen` flag never reach subtitles, TTS or history (tests `tests/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 increasing `revision`. Restored id from `data/desktop/avatar.json` is 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 emits `avatar.selection` for the UI.
|
||
- `acknowledge({id,revision})` (UI reports image decoded): only if revision and id match the pending one; then `currentId = choice.canPersist === false ? (choice.returnTo ?? currentId) : pendingId`; persist `{schemaVersion:1,id}` only when currentId changed.
|
||
- `invalidatePending()`: pending = current, `revision++`, emit snapshot. Called at every `turn.started`, `turn.cancelled`, `turn.failed`, cancel, and on `avatar-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 keeps `avatarRevision` and 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}` or `null` before the first `select`.
|
||
- `select(id, revision, now)`: ignore unknown id or `revision < this.revision`; set semantic choice, `base = returnTo ?? id`, clear sequence; if the choice has an animation, start that clip as a `reaction`; `attend(now)`; next blink at `now + 3000 + rand·3000`.
|
||
- `attend(now, interrupt)`: `nextActivity = now + autonomy.firstActivityMs` (18000); an `ambient` sequence (or any sequence when `interrupt`) is cancelled.
|
||
- Suspension compensation: if the gap since last tick > 1000 ms, shift sequence start, `nextActivity`, `nextBlink` by the gap (no burst of missed animation). `dt = min(1000, gap)`.
|
||
- Priority order inside `tick`:
|
||
1. `sleeping` → clear sequence, push `nextActivity`, `nextBlink = now+3000`, return frame `idle-blink_closed` (eyes closed) with activity `sleep`.
|
||
2. not `expanded` (core/collapsed) → freeze sequence clock (`start += dt`), push `nextActivity`, return base frame.
|
||
3. `dragging` → freeze sequence clock and push `nextActivity` (continue).
|
||
4. `active || typing || speaking` → `attend(now)` (cancels ambient activity).
|
||
5. `reduced` → clear sequence, return base frame (stable pose).
|
||
6. Ambient activity starts when: no sequence, `autonomy.enabled`, base is `neutral`, `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).
|
||
7. Playing a sequence: walk keyframes by age; the clip `effect` is reported with `progress = age/frame.ms` while on `effect.onFrame`. At the end: clear and `nextActivity = now + activityGapMs (12000) + rand·6000`.
|
||
8. Blink (base `neutral` and not speaking): when `now ≥ nextBlink`, age < 280 ms → `idle-blink_half` for age <80 or >190, else `idle-blink_closed`; afterwards `nextBlink = now + 3000 + rand·4500`.
|
||
9. Base `surprised`: `idle-surprised_closed` while `now % 4600 < 220`.
|
||
10. Otherwise the base frame (activity `dialogue`).
|
||
- Note: the manifest `speech` clip 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-floor` when 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 `pose` field) in the attached portrait, the layout is shifted so the authored face point stays fixed (`moveAvatar` by 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.mjs` renderer `loadFrame` 277-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; `visibleBounds` from the manifest or computed (alpha ≥16). Rust: decode PNG once per frame into an `Arc<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 → `closed` and reset. Otherwise hold the current shape for 90 ms; then `level = 0.25·level + 0.75·amplitude`; shapes `closed < small < round < wide` with hysteresis: `wide` if level > (0.055 when already wide else 0.075); else `round` if level > (0.022 when already round else 0.03); else `small`. `speaking` is `presence.speaking && !presence.sleeping`.
|
||
- Attached: `AvatarMouthLayer.update(image, shape, frameId)`; detached: main forwards `avatar-mouth` shape only when it changes (`app.js:1494-1500`, `main.mjs:6332-6341`, overlay `setMouth`).
|
||
- 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, then `source-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 `#f9faff` where `o = {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), draw `drawPoseMouth` (translate, rotate `angle`, scale `width/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)`), then `destination-in` with 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; tones `blink`/`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-window` anchor (628,771) emitters (533,402),(764,365); `music-floor` anchor (641,1164) emitters (522,642),(775,591). Attached portrait uses `music-floor`; perched seat uses `music-window`, ground perch uses `music-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 `reduced` toggles.
|
||
- Envelope `amount` → 1/0 with time constant 180 ms (on) / 210 ms (off), dt capped at 250 ms; fully reset when `amount < 0.003` and inactive.
|
||
- Legacy mode (`autoBpm === false` or tempo undefined): fixed 110 BPM. Measured mode requires tempo 40..240 and confidence > 0. `rhythmAmount` follows `legacy ? 1 : confidence` with τ = 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·confidence` beats/s then exponential with τ = 0.9 s (`correctPhase`). New anchor key `beatAt:bpm` triggers 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 with `sway = sin(2πb)·0.85 + sin(πb)·0.22` (legacy) or `sin(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): life `2.5 + 0.65·noise(n,1)` s, alternate emitter by `n % 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, alpha `smoothstep(0,0.16,p)·(1−smoothstep(0.68,1,p))·amount`, rotation `dir·((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}`.
|
||
- Settings `notes` and `motion` independently disable particles / rotation. The detached overlay accepts only an allow-listed music state (AV-35, validation `main/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 `dialogue` presentation.
|
||
|
||
#### 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 ms `cubic-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 (`showFace` true except on music/perch-seat poses): on portrait frames draw `assets/default/capri-headpat.png` (resource `headpat-face.png`, 1254²) clipped to `faceOutline` polygon (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) (`headpatFaceTransform` 28-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 ms `steps(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 `spriteReaction` frame 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)·amplitude` with `frame = 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 with `swing:[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 at `floor(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`, else `neutral`.
|
||
- Algorithm `avatarBodyPartAt(u,v,opaque,{dock,poseId,now,reducedMotion})`:
|
||
1. 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 → `reviewedPart` on 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). Else `reviewedPart(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).
|
||
2. Grip rig dock (`dock-left`, `dock-right`, `ceiling` without 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.clip` polygon, mapped by `(x−head.x)/head.scale`) → `head`/`hair`; else behind-head layers.
|
||
3. 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.
|
||
4. 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.
|
||
- `spritePressKind(point, rect, mask, headpat)` returns the part, or `body` when 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 part `head`; unknown part rejected. A press continues the previous sequence (count+1, capped at 11) iff: same sleeping state, (sleeping or same part), and `now − previous.at ≤ avatarTapGapSeconds·1000` (default 10 s); otherwise count = 1.
|
||
- While awake each press calls `onPress({part,tone,count})` → main emits `avatar.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 set `nextCueAt = 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, or `now ≥ nextAt` and `now ≥ nextAtByPart[part]`) → `react(sequence, until = now+2000)`. If not allowed yet, retry every 100 ms until `until`, then drop. On start: global cooldown `nextAt = now + 8500 ms`, per-part cooldown 10625 ms (not for `body`); deadline `timeoutMs` (= first-text timeout of the response timing profile) or `wakeTimeoutMs` (= full response timeout) while waking; `variation` cycles 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 if `done_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 normal `turn.started` (source `avatar-click`) / `turn.delta` / `turn.completed` triple so it is subtitled and spoken. Packet origin label shows `CAPRI`.
|
||
- **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 tone `boundary`, and main forces expression `annoyed`.
|
||
- **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 is `sleeping`; 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. Plus `backend.phase == ready && !avatarSleeping` for 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, title `Capri`, icon `assets/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, `placeVisibleInWorkArea` keeps 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 marked `data-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 + `source` crop (normalized) + `lens {x,y,w,h,curve:0.036}` when the CRT shader is active, and `enabled = 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); sprite `enabled` boolean; 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 (Electron `setIgnoreMouseEvents(ignore, {forward:true})`).
|
||
- `spriteDragHit`: inverse lens; then the frame's `visibleBounds` box (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, update `compactPlacement` if 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 in `avatar-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) or `min(430, w, 2h)`, `centerFaces: true`.
|
||
- `panBounds(viewport, zoom)`: `size = base·zoom`; per axis `space = 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}`; `registeredAvatarRect` shifts by anchor: `x += (627 − anchor.x)/W·size`, `y += (refY − anchor.y − 75)/H·size` with `refY = 807` for 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 calls `beginAvatar`; 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: `centerAvatarFace` moves 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 flips `pinned` (persisted `presence.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 call `replyAttention` (reveal if `expandOnReply`); `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 pack `autonomous = true` and `startExpanded = 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: `--reveal` 0→1 over 360 ms after expansion (1 immediately in reduced motion); viewport opacity `0.15 + 0.85·reveal`.
|
||
- Core orb (`drawCore`, lines 316-389, scale = min(w,h)/144): rings r=49 (α0.3), dashed r=40 rotating `0.2·t`, three arcs r=51 length 0.34 rad rotating `0.25·t`, 7 shard polygons (`shardPoints`, presence-model 203-213) coloured `#ff315c`/`#eeef77`/`#79f9cd`, rotated diamond 24 px `#071019`, glow ring r=11 `#88f6ff` blur 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 follow `min(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 wave `motion·sin(83·st.y + 1.3t)·0.32`; RGB split `0.48 + glitch·(1.4 + 6·damaged)` px; scanline `0.86 + 0.14·cos(2.094·y)`; phosphor triad `1 − 0.065·sin(2.094·x + {0, 2.09, 4.18})`; vignette `1 − 0.14|q|²`; gain 1.13; flicker `1 + motion·0.009·sin(8.2t)`; additive noise `(0.02,0.035,0.03)·noise`. `time = 0` and `motion = 0` in 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 → `fallback` mode: 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), `glitchStrength` 0..100 (65), `glitchIntervalSeconds` 10..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 if `now − 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)·interval` with `r` from `signalRandom(cycle + 2078)`, scaled 0.8. Strength = max(event, ambient)·strength/100. Offsets `x = (r−0.5)·22·s`, `y = (r−0.5)·5·s`, seed `floor(now/56)`. `signalRandom` = LCG `state = state·1664525 + 1013904223 (u32)`, value `state/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), `floatAmplitude` 0..24 px (6), `floatPeriodSeconds` 4..30 (10). Target `A·(0.75·sin φ + 0.25·sin(0.53φ + 1.4))`, `φ = 2π·t/period`; clamped to `floatLimits` (keep all visible UI rects ≥4 px inside the window); eased `y += (target − y)·0.065` per 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)}`; persisted `dimming.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 feather `feather(d, R) = (erf(6d/R − 3) − erf(−3)) / (erf(3) − erf(−3))` with `R = 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), tooltip `Capri — <Microphone (<lang>)>, <App awareness active; no screen capture>` or `Capri desktop companion` when 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 (<lang>) (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 + emit `focus-input` when 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` (or `owner.x + owner.w + 12` if 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 to `attached` from anywhere (destroys all overlays, clears reply/status/mouth). `available` ⇔ phase `detached` and no operation/relocation in flight. Every phase change is emitted to the UI (`avatar.detach {phase}`); on `attached` the avatar-only mode ends and the perch is cleared; the home UI shows/hides the portrait accordingly (CSS: frame leave animation 210 ms `clip-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: inset `min(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 by `distance + (clear ? gap : 0)`; already used keys are skipped (session `seen` set).
|
||
- **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) and `reset()`. 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; phase `detached`; 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 a `focus` point = 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 flashes `brightness(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): `departure` frames 0–5, `transit` 6–14, `arrival` 15–26, `idle` ≥27. A crossing source overlay (no parked arrival) stops after `boltOnlyFrames = 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 amplitude `min(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-in` tint 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 (`ribbon` with asymmetric edges and notches, `drop`, `drawBranches`, `drawBreak`, `retractBolt`, `assemble`, `arrivalStrike`) are fully deterministic from `seed` (u32 from `randomInt(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, padded `14 + 0.85·max(scale)`), device ratio `min(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 `dialogue` presentation → no animation, instant relocation.
|
||
|
||
#### AV-37 Teleport sound (P2)
|
||
Source: `renderer/avatar-teleport-sound.mjs`, `app.js:2077-2094`.
|
||
- Played on phase `leaving`, `teleporting`, `returning` unless preset `off` or presentation `dialogue`. Presets (`teleportSound`): `spark` 0.16 s triangle 1900→630 Hz + high-passed (1900 Hz) noise; `thunder` 0.37 s sine 132→45 Hz + low-passed (420 Hz) noise; `pulse` 0.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 `avatarDragTether` is on (and presentation is `character`), 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); branches `min(19, ceil((1 + d/115)·density·(reduced ? 1 : 2)))`; sparks `min(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 `#ff164b` 8 0.13 · bolt `#fa174a` 4 0.29 · branches `#ff1946` 1.0 0.64 · bolt `#ff3e5c` 1.45 0.98 · embers `#fa234b` 1.5 0.63 · sparks `#ff7587` 1.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}` plus `sleeping` and 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: `below` if the pose is inverted (upside-down) and it fits, else `above` if it fits, else `left/right` if ≥ min(144, width) available (wider side), else `below`. 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 fit `floor((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 within `min(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 within `min(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-left` when the sprite is on the right of the contact (window right edge, display left edge) else `pose-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 identity `windowId/processId/startedAtTicks` equality. "Near" query: inner span excludes `w/25`, `h/25` at 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); `hidden` or 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 to `music-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) <title> window" (and Russian "сядь/присядь/посиди на (край/верх) (активное/текущее) окно [title]") → `perch {title ≤160}`; Russian app aliases: хром(а)/гугл хром → chrome, блокнот(а) → notepad, дискорд(а) → discord, проводник(а) → explorer. Questions or quoted text do not match (anchored regexes).
|
||
- Execution (refused while another reply runs): return → `returnAvatar()`; perch → `avatarWindow({title})` then `perchOn`. Both user and assistant messages are stored and emitted as a normal turn with fixed replies (English/Russian by conversation language, §6.5). Roaming is suppressed for 90 s afterwards.
|
||
- Own Settings window: titles "Settings", "Capri Settings", "the/your/her/Capri's settings", "settings capri" and Russian forms, plus localized UI titles, resolve to the Settings window id (only when it is visible).
|
||
|
||
#### AV-44 Desktop roaming while screen-watch is active (P2)
|
||
Source: `main.mjs:3035-3152`, `desktop-avatar-commands.mjs:51-67`.
|
||
- Only while screen observation runs in `watch` mode and its capture is active, and only when idle (no draft, interface busy, chat task, reply, computer control, playback, voice generation, recent speech (<5 s), sleep, analysis, or verification). First roam ≥20 s after watch starts; then every 45–80 s (`45000 + rand·35000`). Suppressed 60 s after a manual teleport and 90 s after a command or return.
|
||
- If the watch lease targets a window (`window:<id>`): perch on that window. Otherwise pick a random approved display; with 35 % probability perch on the active window if it is on that display; else teleport to `randomAvatarDestination`: up to 12 attempts of `x = area.x + w·(0.13 + 0.74·r)`, `y = area.y + h·(0.34 + 0.55·r)`, rejecting points within the companion window (+40 px left/right/bottom) or < 140 px from the previous position.
|
||
- Leased perches end when the lease changes or the display leaves the lease.
|
||
|
||
#### AV-45 Desktop "Teleport Capri" shell verb (Windows-only, P2)
|
||
Source: `main/desktop-teleport-menu.mjs`, `packages/installer/windows/desktop-teleport.cs`.
|
||
- Windows registers `HKCU\Software\Classes\DesktopBackground\shell\Capri.Teleport` while the companion is shown; a helper with low-level mouse/keyboard hooks remembers the right-click origin on the desktop and, when the verb runs (named-pipe connection), prints `x y`; the app teleports there. The same helper reports releases outside overlays (`release <id> x y`) and follows a perched window (`anchor <id> hidden|closed|visible x y w h`, WinEvent hooks + 500 ms poll, identity = HWND+PID+process creation ticks). Not active on Linux (`desktopTeleportMenu` is null). Linux replacement: §8.6.
|
||
|
||
#### AV-46 Overlay stacking and display changes (P0)
|
||
- Overlays are re-raised every 750 ms, on show, and whenever another app window of Capri gains focus (never stealing focus). Raising also re-applies the click-through state.
|
||
- The detached avatar is reset (back into the frame) when: the companion window moves to another display or changes bounds during an operation (`checkDisplay`), a display is removed, display metrics change, the companion window closes, a renderer/overlay is lost, or a session lock/suspend happens.
|
||
|
||
#### AV-47 Lock, suspend and shutdown hygiene (P0)
|
||
Source: `main.mjs:6955-6993, 6795-6860`.
|
||
- Lock: hide recording chip and minimized chip, stop music, stop computer control, mark locked (blocks teleport, reactions, composer, intro), cancel taps, reset detached avatar. Suspend: same plus visual cancellation. Unlock clears the lock flag. Quit: destroy chips, composer, overlays, save window/avatar layout/dimming, unregister shortcuts, destroy tray.
|
||
|
||
#### AV-48 Avatar-only mode (P1)
|
||
- When detached, hiding the panel leaves only the desktop avatar (+ composer). The composer's menu button or the tray restores the panel. If the avatar returns to the frame while the panel is hidden, the hidden-companion cleanup runs.
|
||
|
||
### 2.F Startup, sleep, HUDs and miscellany
|
||
|
||
#### AV-49 Startup intro (P2)
|
||
Source: `startup-intro-assets.mjs`, `main/startup-intro.mjs`, `renderer/startup-intro.mjs`, `renderer/startup-intro-motion.mjs`, `main.mjs:410-428, 4401-4404, 5690-5693`.
|
||
- Pack `assets/capri/intro-v1/runtime-intro.json` (≤16 KiB; exact keys `schemaVersion:1, canvas 1254², anchor {ground,627,1166}, fps:24, frames[7]`). Frames in exact order `01-signal, 02-gaze, 03-arrival, 04-landing, 05-greeting, 06-wink, 07-ready`, file `PNG/<id>.png`, `ms` integer 80..1000, integer visible bounds inside the canvas, mandatory SHA-256; PNG ≤4 MiB with `IHDR` tag, 1254², bit depth 8, colour type 6. Total duration must be exactly **3000 ms** (167+208+292+417+750+583+583) and the last frame's hash must equal the hash of `assets/capri/sprites/v1/capri-neutral.png` (the intro ends on the exact main sprite). File reads: no symlink in any path segment, `nlink == 1`, opened with `O_NOFOLLOW`, fstat dev/ino equal to lstat, size/mtime unchanged after read. Any failure → intro silently disabled (`null`).
|
||
- Gate (`StartupIntroGate`): one presentation per process. `claim('skip')` consumes; `claim('play')` returns `play` (consumes) only if `available()` — window visible, not minimized, renderer on the companion page, not locked/shutting down/quitting/focus mode/avatar-only, Settings not visible — else `wait` (not consumed). Opening Settings consumes it (skip).
|
||
- Playback: eligible when the UI is ready, portrait expanded and attached, not arriving, the director shows its base frame and the sprite is decoded. Poll every 120 ms while waiting; decode all 7 frames within 2200 ms (else skip); any pointerdown/keydown/wheel, hidden window, reduced motion, an active turn, voice, sleeping, speaking, draft or ASR text, or leaving the frame cancels (skip claimed). Canvas texture side `min(768, max(256, ceil(width·min(dpr,1.5))))`. Frame 7 is replaced by the live composed ready image so the hand-off is seamless.
|
||
- Motion (`startupIntroSample`): phase boundaries [0,167,375,667,1083,1833,2417,3000] → signal, gaze, arrival, landing, greeting, wink, ready; poses held at 24 fps exposure; arrival drops in `poseY = −0.027·(1−p)²`, landing bounce `[0,−0.003,−0.006,−0.003,0]` for the first 5 exposures; signal frame wiped in left→right over 115 ms; red ink effects (`#ff003d`, pale `#ff3765`, dark `#9d0739`): signal ribbon path drawn 0–590 ms, spark bursts at 0/330/667/1083/1833/2417 ms (counts 6/8/12/5/3/4, seeds `0x43415052 ^ {0x181,0x237,0x349,0x453,0x569,0x671}`), impact trails 667–1067 ms, cut slashes within ±38 ms of each boundary; effects stop at 2860 ms. Copy `startup-intro-motion.mjs` literally.
|
||
- While pending, the sprite and effects are hidden; glitch is suppressed while the intro plays.
|
||
|
||
#### AV-50 Startup progress with learned ETA (P2)
|
||
Source: `startup-progress.mjs`, `main.mjs:791, 7020-7060`.
|
||
- Stages `core`, `models` (if preloading), `recognition` (if mic armed), `voice` (if voice enabled). Each stage `{state: waiting|running|ready|failed, estimate s, started}`; default estimates core 15, models 12, recognition 8, voice 25 s; learned estimate = last successful duration in seconds (clamped 1..600) from `startup-times.json`. Emits `startup.progress {started, stages[], finished}` on every change; history written atomically at finish (errors ignored).
|
||
|
||
#### AV-51 Sleep visuals, tap gating and sleep command (P1)
|
||
Source: `sleep-service.mjs`, `app.js:384-395, 1505-1512`, `main.mjs:1241-1275, 2343-2400`.
|
||
- `visuallySleeping(power, connection)`: false while power is `notifying` or `voice-awake`; true when power ∈ {sleeping, asleep} or backend ∈ {offline, stopping}. `avatarTapsSleeping` additionally true while power `waking` or backend ∈ {sleeping, asleep}.
|
||
- Visuals: director returns `idle-blink_closed` (eyes closed); a `Zzz.` caption at ~(sprite x + 0.7w, sprite y + 0.12h) clamped to [16, innerWidth−95] × ≥92 px; caption text `sleepCaption(elapsed)` changes every 500 ms: `tick = floor(elapsed/500)`, `mask = floor(tick/3) % 8`, letters for bits 0..2 are `Z` if set else `z`, followed by `(tick % 3) + 1` dots (reduced motion: fixed at 1500 ms → "Zzz.."). Entering sleep reveals the portrait once; waking re-attends the director and reveals if `expandOnReply`. Headpat/expression plates and tap sparks are cleared while sleeping.
|
||
- `isSleepCommand(text)`: NFKC, lowercase, curly quotes normalized, outer punctuation stripped, optional "hey/эй" + "capri/капри" vocative and "please/пожалуйста" removed; then exact match of: sleep · go to sleep · you can (go to) sleep · (it's/it is) time to (go to) sleep · take a nap · get some rest · иди спать · иди поспи · ложись спать · (тебе) пора спать · можешь (идти спать|поспать|отдохнуть) · отдыхай. On match (and no reply in progress) the sleep service unloads models and a silent turn records the reply "Going to sleep. Your next message will wake me." / «Ушла спать. Разбуди меня следующим сообщением.».
|
||
- `SleepService` state machine (phases `awake, sleeping, asleep, waking, notifying, voice-awake`): `sleep()` — closed → throw; asleep → no-op; sleeping → join; waking/notifying → wait then retry; else `sleeping` → unload → `asleep` (failure → `awake`, rethrow). `wake()` — awake → no-op; waking → join; notifying/sleeping → wait then retry; else `waking` → reload → `awake` (failure → `asleep`). `wakeForReminder(prepare)` — waits for transitions; awake/voice-awake → run prepare; else `notifying` → prepare → `voice-awake` (failure → `asleep`). `close()` blocks further transitions. Every change emits `power.state {phase}`. (Unload/reload bodies belong to the runtime spec.)
|
||
|
||
#### AV-52 Wake feedback (P1)
|
||
Source: `renderer/wake-feedback.mjs:1-168`, `main/companion-ipc.mjs:63-157`.
|
||
- Visual: while the microphone is enabled and listening and not waiting for the wake word, show "I'M LISTENING" / "SPEAK NOW"; after activation keep "HEARD YOU" / "REQUEST RECEIVED" for 900 ms; body flag `wakeBurst` for 700 ms (portrait border pulse).
|
||
- Sound per `wakeSound`: `tone` → two sine blips (740 Hz for 115 ms, then +85 ms 1110 Hz for 140 ms), each gliding +8 % in pitch, 8 ms linear attack, exponential decay to 0.001, bus gain `0.085·wakeVolume`; `off` → silent; `file` → user audio (≤4 MiB import, ≤10 s decoded, stored as `data/desktop/wake-audio`); `voice` → cached TTS of the wake phrase (24 kHz mono float32 PCM, ≤10 s, file `wake-voice-<sha256(lang,phrase,text,identity)[0..20]>.pcm`). A selected file/voice that is unavailable never falls back to the tone (visual only). Voice playback reports `speaking` for mouth sync and subtitle text.
|
||
|
||
#### AV-53 Stopwatch HUD (P2)
|
||
Source: `renderer/stopwatch-hud.mjs`.
|
||
- Shows the selected running/paused stopwatch as `HH:MM:SS` (interpolated locally every 250 ms from the last status; refresh from the time service every 10 s and on visibility). Selection persisted in UI-local storage key `capri.stopwatch.selected` (Rust: in the UI state file). Popover with Pause/Resume, Stop (cancel), Reset (requires confirmation "Reset stopwatch?" / "Elapsed time will return to zero."), "All timers" (opens Settings → time). Title `<title or Stopwatch> · Running|Paused (+N)`. Closes on outside pointerdown or Escape. (Timer logic belongs to the timers spec.)
|
||
|
||
#### AV-54 Screenshot shutter sound (P2)
|
||
Source: `renderer/wake-feedback.mjs:42-71`. 170 ms procedural click: LCG noise (seed 2078) high-passed `(n − 0.7·prev)·0.1` + 1700 Hz sine ·0.025, shaped by two pulses at 0 and 65 ms (1.5 ms attack, τ 13 ms decay, second ×0.8). Used by screen clips (other spec).
|
||
|
||
#### AV-55 Global cursor on KDE Wayland (P0 on KDE)
|
||
Source: `main/linux-cursor.mjs`, `capri_linux/cursor.py`. Only when `WAYLAND_DISPLAY` set and `XDG_CURRENT_DESKTOP` contains KDE. Spawns `/usr/bin/python3 -I capri-cursor` with a minimal environment; the helper loads a persistent KWin script that reports `workspace.cursorPos` on `cursorPosChanged` (throttled to one call per 4 ms) through `callDBus` to a per-PID D-Bus name; it prints `x,y` lines; the app keeps the last valid integer pair and falls back to the X11 position when unknown; the helper is restarted up to 5 times (2 s delay) and killed at exit; it unloads the script when stdin closes. See §5.3 and §8.3.
|
||
|
||
#### AV-56 Capability boundary between UI and host (P0, security)
|
||
Source: `preload.cjs`, other preloads, `main/ipc.mjs`, `main/protocol.mjs`, `main/resources.mjs`.
|
||
- The UI process never sees file paths, tokens or arbitrary IPC: one narrow method per capability; event callbacks receive plain payloads only. Each IPC channel matches `^capri:[a-z-]+$` and is accepted only from the expected window's main frame at the exact expected URL; the Settings window may use only an allow-list of channels (`main/settings-channels.mjs`), and four settings channels require an optimistic-concurrency revision (`sha256(JSON(settings))`). Mini composer and chips have their own sender checks.
|
||
- Resources: only a fixed table of files is served (`capri://desktop/...`), GET only, no query/hash/credentials/port; CSP `default-src 'none'; script-src 'self'; …; img-src 'self' blob:; media-src blob:`; `nosniff`, `no-store`. Sprite/pose/music/intro PNGs are served by id from validated catalogs only.
|
||
- Rust: there is no renderer process; keep the *data* invariants (AV-01 validation before use, ids instead of paths in any UI-facing or LLM-facing structure, single-owner state changes) — see §7.
|
||
|
||
#### AV-57 Credits / Hall of Fame callsigns (P2)
|
||
Source: `credits-epithets.mjs`, consumer `renderer/credits-panel.mjs:1-140`, data `config/hall-of-fame.json`.
|
||
- Callsign = `"<Adjective> <Noun>"` from two fixed 80-word lists (capacity 6400). `validateEpithet` requires exactly two words from the lists. `assignEpithets(names, previous, randomIndex, displayNames)` (maintainer tool `tools/community/update-hall-of-fame.mjs`): identities = lowercase GitHub logins (`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$`) or curated display names (≤80 chars, no control chars, unique case-insensitively, ≤1000); saved mappings are preserved and must be valid, lowercase keys, unique combinations; new identities draw uniformly from unused combinations with a rejection-sampled CSPRNG (≤64 attempts, else error); exhaustion fails before drawing.
|
||
- Credits panel (Settings): validates the registry (`schemaVersion 1`, team exactly Overyx/Developer, v1rch/Discord developer, Leberrr/Discord moderator, supporters ≤50 000 GitHub logins deduplicated, major supporters and community helpers via `normalizeCreditNames`, `epithets` must cover every name exactly once), renders names with a stable FNV-1a-derived tone/drift (6 tones, drift 5–8.0 s, delay −0–5.2 s, rise 2–4 px, gradient 8–11 s).
|
||
|
||
#### AV-58 Community links (P2)
|
||
Source: `community-links.mjs`. Fixed ids → HTTPS URLs (boosty, tiktok, discord, github, website, issues; §6.6). `config/community.json` may override a URL only with HTTPS, no credentials, same origin as the default; any invalid entry → all defaults; an expired Discord invite path `/ETMtqsGaZN` and old `/CapriChooms/Capri` repository paths are migrated to the defaults. The UI requests ids, never URLs; opening uses the system browser (`xdg-open` / portal OpenURI in Rust).
|
||
|
||
#### AV-59 Edgerunners teaser workflow (P2, belongs to computer control)
|
||
Source: `edgerunners-teaser.mjs`. A recognised owner request (≤500 chars, English/Russian regex chaining "open Chrome → find the official Cyberpunk: Edgerunners 2 site → watch on Netflix → (scroll) → play the teaser") runs a scripted browser sequence through the computer-control observe/input primitives: navigate `https://www.cyberpunk.net/en/edgerunners2`, then `https://www.netflix.com/title/81054853`, each verified by title/labels (24 polls × 550 ms); up to 4 PAGEDOWN scrolls looking for exactly one teaser control (buttons/links preferred); refuse if ambiguous or already playing; after click require a visible Pause button twice in a row (16 polls). Stage/status replies in §6.7. Port with the computer-control subsystem; listed here only because the file is in this ownership set.
|
||
|
||
## 3. Data and persistence
|
||
|
||
### 3.1 Read-only artwork and configuration (install root)
|
||
|
||
| Path | Format | Notes |
|
||
|---|---|---|
|
||
| `assets/capri/sprites/v1/runtime-sprite-set.json` + 68 PNGs | JSON schema 2 (≤512 KiB), PNG 1254² RGBA | Main catalog; keys `schemaVersion, character, defaultSprite, canvas, canonicalAnchor {627,1166}, sprites[], actions[], clips[], autonomy {enabled, startExpanded, firstActivityMs 18000, activityGapMs 12000}, excluded {kinds, poses, reason}` (`excluded` is informational). |
|
||
| `assets/capri/sprites/poses-v2/runtime-poses.json` + `PNG/capri-*.png` (7) | JSON schema 1 (≤16 KiB) | Reviewed desktop poses (AV-02). |
|
||
| `assets/default/capri-music-v1/runtime-music.json` + 2 masters + 4 notes | JSON schema 1 (≤16 KiB) | AV-03. |
|
||
| `assets/capri/intro-v1/runtime-intro.json` + `PNG/01..07-*.png` | JSON schema 1 (≤16 KiB) | AV-49. |
|
||
| `assets/default/sprite-set.json` + `avatar.png` | JSON schema 1, PNG 1536² | Fallback (AV-04/05). |
|
||
| `assets/default/capri-headpat.png` | PNG 1254² | Headpat face plate (AV-12). |
|
||
| `assets/default/icon-source.png` (512²), `app.ico` | PNG/ICO | Tray/window icon. |
|
||
| `assets/default/brand/{capricore,boosty,discord,github}.svg` | SVG | Chip core symbol, support buttons. |
|
||
| `assets/fonts/exo2/Exo2-Variable.ttf` | TTF (OFL) | UI font (overlay HUD, panel). |
|
||
| `config/community.json` | JSON object `{boosty?, tiktok?, discord?, github?, website?, issues?}` | AV-58. |
|
||
| `config/hall-of-fame.json` | `{schemaVersion:1, team[{name,role}], majorSupporters[], communityHelpers[], supporters[], epithets{lowername: "Adj Noun"}, snapshotDate, source}` | AV-57 (public data). |
|
||
|
||
Synthetic sprite entry example (schema 2):
|
||
```json
|
||
{"id":"happy","pose":"idle","expression":"happy","file":"capri-idle-happy.png","kind":"expression",
|
||
"canPersist":true,"label":"Standing · Happy","description":"Standing; happy.",
|
||
"anchor":{"name":"ground","x":627,"y":1166},
|
||
"visibleBounds":{"x":202,"y":113,"width":881,"height":1055},
|
||
"sha256":"<64 lowercase hex>"}
|
||
```
|
||
Clip example: `{"id":"wink","frames":[{"id":"flirty","ms":350},{"id":"idle-wink_half","ms":90},{"id":"idle-wink_closed","ms":160},{"id":"idle-wink_half","ms":90},{"id":"flirty","ms":600}]}`. Action example: `{"id":"laugh","animation":"laugh","frame":"smirk","returnTo":"happy","label":"laugh","description":"A brief laugh for something genuinely funny."}`.
|
||
|
||
### 3.2 Mutable state (`data/desktop/`, created 0700 recommended; files 0600)
|
||
|
||
| File | Schema (synthetic example) | Written | Read rules |
|
||
|---|---|---|---|
|
||
| `avatar.json` | `{"schemaVersion":1,"id":"smirk"}` | On committed expression change (AV-07) | ≤4096 B, schema 1, id must be a persistable choice else default |
|
||
| `avatar-layout.json` | `{"schemaVersion":1,"x":0.5,"y":0.82,"zoom":1.15}` | 250 ms after the last pan/zoom; on reset; after return-to-frame; on quit | ≤4096 B, schema 1, `validateAvatarLayout` else default |
|
||
| `dimming.json` | `{"schemaVersion":1,"enabled":true,"level":35,"softness":140}` | 200 ms after change; on quit | ≤4096 B, schema 1, `validateDimming` else default |
|
||
| `presence.json` | `{"schemaVersion":1,"pinned":false}` | On toggle | ≤4096 B, `pinned === true` else false |
|
||
| `window.json` | `{"schemaVersion":3,"x":1424,"y":402,"footprint":{"x":0,"y":312,"width":480,"height":348},"compactPlacement":{"x":1424,"y":714,"width":480,"height":348},"alwaysOnTop":true}` (`footprint`/`compactPlacement` omitted when undefined) | 350 ms after a move, on drag end, on always-on-top change, reset, quit | Any parse error → defaults; schema 1/2 coordinate migration (AV-18); footprint/compactPlacement validated against 480×660 |
|
||
| `companion.json` | `{"schemaVersion":1,"settings":{…§4…}}` | On save from Settings | ≤16 KiB, schema 1, full validation else defaults + warning "Saved settings could not be restored. Defaults are in use." (file left intact) |
|
||
| `startup-times.json` | `{"core":14.2,"models":9.8}` (seconds) | At startup finish | Any error → empty history |
|
||
| `wake-audio` | raw user audio (wav/mp3/ogg/flac/m4a) ≤4 MiB | Import | Plays only if present and ≤4 MiB |
|
||
| `wake-voice-<20 hex>.pcm` | f32 LE mono 24 kHz, size >0, ≤960 000 B, multiple of 4 | Wake-voice preparation (temp file + rename) | Regular non-symlink file |
|
||
| `transcript.json` | owned by chat spec; avatar-click and movement-command messages are appended there | — | — |
|
||
| UI-local store (`profile/` Chromium localStorage today) | `capri.stopwatch.selected` = stopwatch id | On selection | Optional |
|
||
|
||
`data/run/desktop.show` (`{"show":true,"launchNonce":"<nonce|null>"}`) and `data/run/desktop.stop` (any content) are one-shot control files written by the launcher/CLI and deleted by the app (polled every 400 ms).
|
||
|
||
### 3.3 Atomicity and concurrency rules
|
||
- All JSON writes use `writeJsonAtomic`: `mkdir -p`, create `<file>.<pid>.<uuid>.tmp` with `O_CREAT|O_EXCL` mode 0600, write `JSON.stringify(value, null, 2) + "\n"`, `fsync`, close, `rename` over the target, unlink the temp on any failure. Rust: same (use `tempfile::NamedTempFile::new_in(dir)` + `persist`, plus `File::sync_all`).
|
||
- Single writer: the app holds a single-instance lock; a second launch only signals "show". Rust must keep this (e.g. `flock` on `data/run/desktop.lock` + a Unix socket for "show"), otherwise two instances would race on these files.
|
||
- Write failures are logged ("Could not save avatar selection", "Could not save Capri’s placement", "Could not save companion position", "Could not save screen dimming") and never crash.
|
||
- No retention limits apply to these files (each is a single small document). Mask/image caches are in memory only.
|
||
|
||
## 4. Settings read by this subsystem
|
||
|
||
`companion.json → settings` (validated by `companion-settings.mjs:39-99` plus glitch/motion/theme validators). Unknown keys reject the whole object.
|
||
|
||
| Key | Type / allowed | Default | Effect |
|
||
|---|---|---|---|
|
||
| `glitchEnabled` | bool | true | Glitch bursts on/off (AV-26) |
|
||
| `glitchStrength` | int 0..100 | 65 | Burst amplitude |
|
||
| `glitchIntervalSeconds` | int 10..120 | 35 | Ambient burst cycle |
|
||
| `glitchEvents` | bool | true | Speech/pose/state bursts |
|
||
| `floatEnabled` | bool | false | Panel float (AV-27) |
|
||
| `floatAmplitude` | int 0..24 (px) | 6 | Float amplitude |
|
||
| `floatPeriodSeconds` | int 4..30 | 10 | Float period |
|
||
| `expandOnReply` | bool | true | Reveal portrait on reply text/speech (AV-23) |
|
||
| `replyAutoHide`, `replyAutoHideSeconds` | bool, int 2..60 | true, 8 | Consumed for detached HUD `autoCollapsed` (subtitles spec) |
|
||
| `detachedStyle` | `character` \| `dialogue` | `character` | Detached presentation (AV-40) |
|
||
| `minimizedChip` | bool | true | Show restore chip on hide (AV-31) |
|
||
| `restoreFromTrayOnWake` | bool | true | Wake word reveals hidden panel (AV-30) |
|
||
| `wakeSound` | `tone`\|`file`\|`voice`\|`off` | `tone` | AV-52 |
|
||
| `wakePhrase` | `Listening.`\|`Yes, choom.`\|`Mhm?` | `Listening.` | Voice acknowledgement text (localized) |
|
||
| `wakeVolume` | number 0..1 | 0.7 | Acknowledgement gain |
|
||
| `buttonFeedback` | bool | true | Button press pulse (UI) |
|
||
| `teleportIntensity` | int 0..100 | 75 | AV-36 |
|
||
| `teleportJaggedness` | int 0..100 | 78 | AV-36 |
|
||
| `teleportBranches` | int 0..100 | 75 | AV-36 |
|
||
| `teleportReducedFlash` | bool | false | Softer flashes/narrower ink |
|
||
| `teleportSound` | `off`\|`spark`\|`thunder`\|`pulse` | `spark` | AV-37 |
|
||
| `avatarTapGapSeconds` | int 1..15 | 10 | Max gap between taps of a sequence (AV-17) |
|
||
| `avatarSnapRadius` | int 12..100 (logical px) | 36 | Dock capture radius (AV-41) |
|
||
| `avatarDragTether` | bool | true | Drag lightning (AV-38) |
|
||
| `avatarDragTetherIntensity` | int 0..100 | 45 | Tether density |
|
||
| `avatarDragTetherChaos` | int 0..100 | 55 | Tether spread/branch width |
|
||
| `avatarDragTetherDeadZone` | int 0..120 (logical px) | 30 | Release dead zone for teleport/return (always applies, even with tether off) |
|
||
| `interfaceTheme` | `{preset: capri\|blackwall\|amethyst\|overdrive\|custom, hue, saturation, backgroundHue, backgroundSaturation}` | `{capri,174,84,174,40}` | Accent/background colours for overlays, chip, composer, FX |
|
||
| (others in the same file: `followUp*`, `wakeOnReminder`, `memory*`, `processGraphs`) | — | — | Owned by other specs |
|
||
|
||
Other inputs: `window.json.alwaysOnTop` (default true), `presence.json.pinned`, `dimming.json`, `avatar-layout.json`; music listening settings `{enabled:false, notes:true, motion:true, autoBpm:true}` (music spec; `notes`/`motion`/`autoBpm` affect AV-11); conversation/interface language (command replies, localized labels, spoken cue language = TTS voice language); OS *reduced motion* preference (disables pose swing, blink plates, music motion, glitch, float, teleport animation, intro, reveal animation, retrace; Linux source in §8.7).
|
||
Settings preview (`updateSettingsPreview`, `main.mjs:3203-3282`): while Settings is open it may temporarily override `companion`, `dimming`, `zoom`, `alwaysOnTop`, `portrait`, `interface`, … without saving; the preview is cleared when Settings becomes idle.
|
||
|
||
## 5. External protocols
|
||
|
||
### 5.1 Tap-reaction inference (Ollama-compatible `/api/chat`, loopback only)
|
||
`avatar-click-reactions.mjs:110-181`. URL = `<inferenceUrl>/api/chat` where `inferenceUrl` must be `http://127.0.0.1:<port>` without credentials (Ollama, or Capri's loopback API proxy when an external provider is active — defined by the inference spec); `redirect: error`. Request (synthetic):
|
||
```json
|
||
{"model":"<configured model>","stream":false,"think":false,
|
||
"shift":false,"truncate":false,"keep_alive":-1,
|
||
"options":{"num_ctx":8192,"num_thread":8,"temperature":0.8,"num_predict":72},
|
||
"tools":[],
|
||
"messages":[{"role":"system","content":"You are Capri, a witty, feminine cyberpunk companion. … COMMUNICATION STYLE: neutral … CURRENT CONVERSATION LANGUAGE: …"},
|
||
{"role":"user","content":"The user tapped your left hand many times in rapid succession."}]}
|
||
```
|
||
- `think:false` is sent when model capabilities are unknown or include `thinking`. `shift/truncate/keep_alive` = `LOCAL_RUNNER_POLICY` (must equal the main chat runner options so Ollama does not reload the model). `options` = auxiliary runner params (`num_ctx`, `num_gpu:0` for CPU, `num_thread`) + generation params + `num_predict:72`.
|
||
- Response: read ≤16 384 bytes, parse JSON, use `message.content`; reject `done_reason == "length"` or any `message.tool_calls`; apply the output filter (AV-17). Aborted by the reaction deadline, by `cancel()`, or by sleep.
|
||
|
||
### 5.2 Window query for docking (`avatar_window`) — current Linux helper
|
||
Process: `integrations/desktop-actions/native/linux/capri-desktop-actions` (Python, `-I`), spawned per request (`integrations/desktop-actions/service.mjs:132-200`), environment allow-list (`HOME, USER, LOGNAME, LANG, LC_*, DISPLAY, WAYLAND_DISPLAY, XAUTHORITY, XDG_RUNTIME_DIR, DBUS_SESSION_BUS_ADDRESS, XDG_SESSION_TYPE, XDG_CURRENT_DESKTOP, DESKTOP_SESSION, XDG_DATA_DIRS, XDG_DATA_HOME, XDG_CONFIG_HOME, I3SOCK`, `PATH=/usr/local/bin:/usr/bin:/bin`, `TMPDIR=<root>/.runtime/tmp`, `CAPRI_ROOT`), one JSON line (≤16 KiB) on stdin, one JSON line on stdout (≤64 KiB), stderr ≤8 KiB, 12 s timeout, kill on abort.
|
||
Requests (all values strings):
|
||
```json
|
||
{"action":"avatar_window","nearX":"1830","nearY":"412","nearRadius":"36","ignoreProcessId":"4242","allowedWindowId":""}
|
||
{"action":"avatar_window","title":"notepad","ignoreProcessId":"4242","allowedWindowId":""}
|
||
{"action":"avatar_window","windowId":"9031","processId":"5150","startedAtTicks":"812345","ignoreProcessId":"4242","allowedWindowId":"77"}
|
||
```
|
||
Responses: `{"ok":true,"windowId":"9031","processId":"5150","startedAtTicks":"812345","x":120,"y":64,"width":1100,"height":780}` · `{"ok":true,"windowId":null}` · `{"ok":false,"error":"KWin is unavailable: …"}`. Limits: title ≤160, windowId ≤24, processId ≤12, startedAtTicks ≤24 chars, `allowedWindowId ^[1-9]\d{0,19}$`, `|near| ≤ 100000`, `1 ≤ radius ≤ 400`. Main re-validates: all ids decimal strings, geometry safe integers, own PID only for the exact visible Settings window. `startedAtTicks` = field 22 of `/proc/<pid>/stat` (process start in clock ticks) — the identity triple `(windowId, pid, startTicks)` defeats id/PID reuse. Backends: KWin script (`capri_linux/kwin.py`, frame geometry in KWin logical px, current desktop only) or i3 IPC tree (`capri_linux/x11.py`, container `rect` in root px, visible workspaces + focused, scratchpad excluded; stacking: fullscreen, floating, focused first).
|
||
|
||
### 5.3 KWin scripting over D-Bus (KDE Plasma 6.8, verified interface `org.kde.kwin.Scripting`)
|
||
- `org.kde.KWin /Scripting org.kde.kwin.Scripting.loadScript(s filePath, s pluginName) → i` (negative = refused), `unloadScript(s pluginName) → b`, `isScriptLoaded(s) → b`; `org.kde.KWin /Scripting/Script<id> org.kde.kwin.Script.run()`. Calls use a 3000 ms D-Bus timeout.
|
||
- Scripts report back with `callDBus("<our bus name>", "/", "org.capri.Report", "Report", "<string>")`; the app exports object `/` with interface `<node><interface name="org.capri.Report"><method name="Report"><arg type="s" direction="in"/></method></interface></node>` on a unique well-known name (`org.capri.cursor.p<pid>`, `org.capri.bridge.x<12 hex>`).
|
||
- Cursor script (persistent, plugin name `capri-cursor`; unload any stale copy first): `let last=0; function report(){const now=Date.now(); if(now-last<4)return; last=now; const p=workspace.cursorPos; callDBus(NAME,"/","org.capri.Report","Report", Math.round(p.x)+","+Math.round(p.y));} workspace.cursorPosChanged.connect(report); report();`
|
||
- One-shot window list script (`capri_linux/kwin.py:115-133`): iterates `workspace.stackingOrder` top-first, keeps `normalWindow || dialog` that are not desktop/dock/special, reports `{windows:[{id: internalId, caption, pid, cls: resourceClass, frame:[x,y,w,h], client:[…], active, minimized, fullScreen, modal, dialog, current (onAllDesktops or on currentDesktop), output}], outputs:[{name, rect}], cursor:[x,y]}`. Numeric window id = `int(first 15 hex digits of the UUID without braces/dashes, 16) or 1`.
|
||
- Rust proposal (to verify against the KWin 6.8 scripting API): a single persistent script `capri-shell` that pushes JSON events for cursor, `workspace.windowAdded/windowRemoved/windowActivated`, the watched window's `frameGeometryChanged/minimizedChanged/desktopsChanged`, `workspace.currentDesktopChanged`, `workspace.screensChanged`, and per-output work areas via `workspace.clientArea(KWin.PlacementArea, output, workspace.currentDesktop)`; commands from the app are delivered by reloading a tiny parameter script or via a script-side `callDBus` poll. This replaces both the per-request Python spawn and the 1800 ms perch poll.
|
||
|
||
### 5.4 i3 IPC (i3 4.25)
|
||
Socket from `$I3SOCK`, else X11 root property `I3_SOCKET_PATH`. Frame: `"i3-ipc"` + u32 LE payload length + u32 LE type + UTF-8 JSON. Types: 0 RUN_COMMAND, 1 GET_WORKSPACES, 2 SUBSCRIBE, 3 GET_OUTPUTS, 4 GET_TREE; events have bit 31 set (0 workspace, 1 output, 3 window, 6 shutdown). Use `GET_TREE` for window rects (`rect` incl. border/title; `window` = X11 id; `window_properties.class`; `fullscreen_mode`; floating via `floating_nodes`), `GET_WORKSPACES` `rect` of visible workspaces as the per-output work area (bar/dock excluded), `GET_OUTPUTS` (`active`, `rect`) for display bounds, `SUBSCRIBE ["window","workspace","output"]` to drive perch following and display changes. Window PID: XRes `QueryClientIds` (spec mask 2) on the window id, fallback `_NET_WM_PID`.
|
||
|
||
### 5.5 X11 / EWMH contract for Capri's own windows (both KDE-XWayland and i3)
|
||
| Window | Kind | Required properties |
|
||
|---|---|---|
|
||
| Companion panel (480×660) | managed, ARGB32 visual | `WM_CLASS="capri","Capri"`, `_NET_WM_NAME="Capri"`, `_NET_WM_PID`, `_MOTIF_WM_HINTS` decorations 0, `WM_NORMAL_HINTS` P/USPosition + fixed min=max size, `_NET_WM_WINDOW_TYPE_UTILITY` (i3 floats it), `_NET_WM_STATE_{SKIP_TASKBAR,SKIP_PAGER,STICKY}` + `_NET_WM_STATE_ABOVE` when "Always on top", `_NET_WM_ICON`; input shape = interactive rectangles (§8.2) |
|
||
| Detached avatar / teleport / tether layers (work-area sized, one per display) | override-redirect ARGB32 (never focused, exact position, top layer) | input shape empty except the grab box / HUD hit rects; raised (`ConfigureWindow stack_mode=Above`) every 750 ms and on our focus changes |
|
||
| Mini composer | managed ARGB32, focusable | as panel + `WM_TRANSIENT_FOR` none, `_NET_WM_WINDOW_TYPE_UTILITY`, ABOVE, SKIP_TASKBAR/PAGER, STICKY; input shape empty while faded |
|
||
| Minimized chip (52×52), recording chip (260×40) | override-redirect ARGB32 or managed UTILITY | click restores; drag moves (chip) |
|
||
| Settings, attachment viewer | managed, opaque | normal decorations off (frameless) for Settings, fullscreen for viewer |
|
||
| Computer-control border | override-redirect ARGB32 per display, input shape empty | (computer-control spec) |
|
||
Coordinates are X11 root pixels; logical = root px ÷ UI scale (§8.4).
|
||
|
||
### 5.6 Internal command/event vocabulary (replaces Electron IPC)
|
||
Events consumed by the shell (from other subsystems): `turn.started|delta|completed|cancelled|failed`, `turn.avatar {turnId, avatar{id}, source: model|fallback}`, `backend {phase,message}`, `power.state {phase}`, `voice.*` playback `{busy, speaking}` + RMS level, `microphone.*` (status, wake, partial, activity), `music.status {enabled, hearingMusic, energy, tempo, tempoConfidence, beatAt, settings{notes,motion,autoBpm}, phase}`, `companion.settings`, `languages`, `capture/screen-watch lease`, `startup.progress`.
|
||
Events emitted by the shell: `avatar.selection {selection, turnId?, source?}`, `avatar.tap {part, tone, count, pulse}`, `avatar.headpat {point}`, `avatar.detach {phase}`, `avatar.layout {layout}`, `avatar.reply-hover {hovered}`, `avatar.composer.action {id, action}` (ack `{id, accepted}` within 10 s), `window.focus-mode {active}`, `window.always-on-top {active, preview?}`, `window.portrait {active}`, `dimming {settings}`, `startup-intro.skip`, `glitch.preview {settings}`, `focus-input`, `open-*` panel requests.
|
||
Commands accepted from the UI layer (validated as in Electron handlers): `avatar_ready {id, revision}`, `avatar_frame_ready {id, revision, sequence}`, `avatar_failed {id, revision}`, `avatar_mouth closed|small|round|wide`, `avatar_reply {text≤512, turnId≤128, fullText≤16000?, autoCollapsed?}`, `avatar_status {text≤100, color #rrggbb}`, `regions {controls[≤32], sprite{…}, footprint?}`, `avatar_layout {x,y,zoom}`, `avatar_drag_start {frameId, sprite, point}`, `avatar_drag_end {click, point?, drop?}`, `drag_start`, `drag_end`, `window_action {action, value}` (AV-30 list), `presence_pinned bool`, `dimming {enabled, level, softness}`, `startup_intro play|skip → play|wait|skip`, `hide`, `menu`, composer `bootstrap|resize(44..240 int)|hide|action`, chip `restore|drag start|move|end|cancel`, recording `stop`.
|
||
|
||
### 5.7 Desktop integration services (Linux)
|
||
- Tray: StatusNotifierItem (`org.kde.StatusNotifierItem-<pid>-<n>`, `com.canonical.dbusmenu` menu) — Plasma native; on i3 requires an SNI host (this machine runs `snixembed --fork` + polybar tray).
|
||
- Global shortcut: KDE → `org.freedesktop.portal.GlobalShortcuts` (CreateSession, BindShortcuts id `toggle-companion`, preferred trigger `CTRL+SHIFT+space`, `Activated` signal); i3 → `XGrabKey` on the root window for Ctrl+Shift+space (with Lock/NumLock modifier variants) or a documented `bindsym ctrl+shift+space exec capri show --toggle`.
|
||
- URL opening: `org.freedesktop.portal.OpenURI` or `xdg-open` with the fixed community URLs only.
|
||
- File dialogs (composer attach, wake import): `org.freedesktop.portal.FileChooser` (KDE) / GTK or portal on i3.
|
||
|
||
### 5.8 Windows-only helper protocol (reference, not ported)
|
||
`CapriDesktopTeleport-<sha16>.exe --watch <token>` over stdio: prints `ready`; stdin lines `<hwnd> <id>` (watch release on that overlay, `0 0` = none) and `follow <id> <hwnd> <pid> <ticks>` / `follow 0 0 0 0`; stdout lines `x y` (teleport target), `release <id> x y`, `anchor <id> hidden|closed|visible [x y w h]` (physical px, DWM extended frame bounds). Registry verb `HKCU\Software\Classes\DesktopBackground\shell\Capri.Teleport` with values `CapriOwner` (sha256 of the lowercased Capri.exe path), `CapriRoot`, default label and command `"<helper>" --teleport <token>`; removed on hide only if the owner hash matches.
|
||
|
||
## 6. Text to reproduce
|
||
|
||
All English strings below are also *localization keys* (`uiText(key, language)`); translations live in the localization subsystem.
|
||
|
||
### 6.1 Avatar control instructions (system prompt fragment) — `avatar-protocol.mjs:11-17`, verbatim
|
||
`${options}` = one line per active choice `"<id>: <description>"`; `${first}` = first choice id (`neutral`). When `followUp` is false the LISTENING line is an **empty line** (keep it byte-exact).
|
||
```
|
||
AVATAR CONTROL:
|
||
Choose your facial expression or reaction from context. Begin your final user-facing answer with exactly one hidden marker [avatar:ID], then a newline and your English reply. When a tool is needed, call it first without an avatar marker or spoken preamble; choose the avatar only for your answer after the tool result. Use one listed ID:
|
||
${options}
|
||
LISTENING CONTROL: For a genuine follow-up question or explicit invitation to answer, use [avatar:ID;listen] as the opening control line instead of [avatar:ID]. The ;listen flag belongs ONLY inside that opening bracketed marker. Never put it in the spoken reply or at the end of the answer. For rhetorical questions, routine task confirmations and goodbyes use [avatar:ID]. This grants only a short continuation of an already-enabled microphone.
|
||
Example first line (no punctuation after the marker):
|
||
[avatar:${first}]
|
||
Then write the reply on the next line. Keep one choice per reply. The marker is a single opening control line, not an XML tag: never add a closing marker or repeat it in the reply. Vary your expression naturally and be empathetic to distress. Choose a flirty expression or a wink only when the conversation invites it. Laugh when something is genuinely funny. Facial reactions finish automatically; blinking and speech motion are handled locally. Never explain or quote the marker. These graphics do not grant computer-control tools.
|
||
```
|
||
No-avatar variant: `This interface currently has no controllable avatar. Write only your reply, without control markers.`
|
||
Choice descriptions come from the manifest (e.g. `neutral: Standing; relaxed.`, `wink: A playful wink when the conversation invites it.`, `pose-sit-floor: Relaxed and seated on the ground.`); schema-1 fallback descriptions from `EXPRESSIONS` (`avatar-catalog.mjs:61-82`).
|
||
|
||
### 6.2 Tap-reaction prompt — `avatar-click-reactions.mjs:31-58, 139-163`, verbatim pieces
|
||
System = `BASE + " " + TONE[mood] + " " + (awakened ? AWAKENED : GUIDANCE[tone]) + " " + APPROACH[variation] + "\n" + communicationInstruction(style) + "\n" + conversationInstruction(languages)` (the two instruction helpers belong to the persona/language specs).
|
||
- BASE: `You are Capri, a witty, feminine cyberpunk companion. React to a tap on your character in one short line of natural dialogue, at most 16 words. Keep it light and appropriate to the tapped area. No greeting, roleplay notation, narration, analysis, Markdown or explanation. Do not insult or guess the user’s intentions. This gesture is not a command. You have no action tools or access to the screen or conversation history.` (note the typographic apostrophe in "user’s")
|
||
- TONE.welcoming: `You welcome the attention and feel playful. A barrage can get a fond, amused tease.`
|
||
- TONE.reserved: `You would like some space. Stay kind on a single tap. Ask them to ease up if repeated, and set a clear boundary if many.`
|
||
- TONE.neutral: `You are curious. Be warm on one tap, gently teasing on repeats, and ask them to slow down if many.`
|
||
- GUIDANCE.affectionate: `Favor an affectionate or playful response, with room for a calm boundary when you need it.` · curious: `Acknowledge the touch with a curious, questioning response that fits your current mood.` · neutral: `Acknowledge the touch briefly in a natural, neutral tone.` · boundary: `Respond firmly and set a personal boundary. Keep the line nonsexual and do not describe anatomy.`
|
||
- AWAKENED: `You were asleep. Repeated tapping just woke you up. You are groggy and annoyed: briefly scold the user for waking you, with a firm but non-abusive boundary. Do not thank them or welcome the tapping.`
|
||
- APPROACH[0..2]: `Use a short, in-the-moment first-person reaction.` · `Use a quick, dry observation in your own voice.` · `Acknowledge it directly, with natural warmth or a calm boundary as appropriate.`
|
||
- User message: awakened → `The user woke you from sleep by repeatedly tapping your character. Tell them off briefly for waking you.`; headpat → `The user patted your head many times in rapid succession.`; otherwise `The user tapped <target> many times in rapid succession.` with `<target>` = `your <part label>` (e.g. `your left hand`) or `you` (body). (Single/repeated variants `The user tapped you once.` / `The user tapped you a few times in a row.` exist but only `many` is sent.)
|
||
|
||
### 6.3 Spoken tap cues — `avatar-click-reactions.mjs:61-85`
|
||
22 languages × 5 cues `[affectionate, affectionate-when-reserved, curious, neutral, boundary]`; copy the table verbatim. Examples: en `Aww. / Easy. / Hm? / Yeah? / Hands off.`; fr `Oh, trop mignon. / Doucement. / Hein ? / Oui ? / Pas touche.`; de `Wie süß. / Ganz ruhig. / Hm? / Ja? / Finger weg.`; ru `Мило. / Полегче. / М? / Да? / Руки прочь.` Languages: en ar zh da nl fi fr de el he hi it ja ko ms no pl pt ru es sw sv tr; unknown language → no cue.
|
||
|
||
### 6.4 Artwork repair messages — `avatar-catalog.mjs:9-12`, verbatim
|
||
- Installed: `Capri artwork is missing or damaged. Run Capri Setup again and select this installation folder to restore the avatar. Your history and settings will be preserved.`
|
||
- Source/setup: `The setup source is incomplete or damaged: Capri artwork is missing or damaged. Download CapriSetup from the GitHub Releases page, or extract a complete source archive with the Capri artwork manifests and PNG files. Your existing installation data is preserved.` (Rust: rephrase "Run Capri Setup" for the Arch package if the installer is not ported — open question.)
|
||
|
||
### 6.5 Fixed replies
|
||
- Movement commands (`main.mjs:3000-3015`): return ok `I’m back in my frame.` / `Я снова в рамке.`; return failed `I couldn’t get back to my frame.` / `Не получилось вернуться.`; perch ok `I’m perched on the window.` / `Я на краю окна.`; perch failed `I couldn’t find an open window to perch on.` / `Не нашла подходящего открытого окна.` (Russian when the conversation language is `ru`, else English.)
|
||
- Sleep command: `Going to sleep. Your next message will wake me.` / `Ушла спать. Разбуди меня следующим сообщением.`; backend message while asleep `Sleeping. Send a message to wake Capri.`; while unloading `Freeing model memory…`.
|
||
- Sleep confirmation: title `Unload models and sleep?`, detail `Models will be loaded again when you wake Capri.`, confirm `Unload models`.
|
||
- Teaser workflow replies: `edgerunners-teaser.mjs:61-86` (6 English/Russian pairs).
|
||
|
||
### 6.6 Community URLs — `community-links.mjs:7-14`
|
||
boosty `https://boosty.to/overyx/donate` · tiktok `https://www.tiktok.com/@overyx2` · discord `https://discord.gg/capricore` · github `https://github.com/CapriChooms/CapriCore` · website `https://capri-core.com/` · issues `https://github.com/CapriChooms/CapriCore/issues/new/choose`.
|
||
|
||
### 6.7 UI strings owned by the shell
|
||
- Presence/status labels and colours: AV-23 table. Wake HUD: `I'M LISTENING`, `SPEAK NOW`, `HEARD YOU`, `REQUEST RECEIVED`. Sleep caption pattern AV-51.
|
||
- Buttons/titles: `Keep Capri visible`, `Leave frame`, `Return to frame`, `Hide to tray`, `Hide Capri to tray`, `Hide interface`, `Quit and unload models`, `Return Capri to signal core`, `Show Capri`, `Bring Capri closer`, `Drag Capri · Scroll to zoom`, `Drag to move the whole window`, packet origins `CAPRI` / `YOU` / `CAPRI // INITIATIVE` / `YOU // SNAPSHOT`, prompts `Connection established.`, activity labels `Sleeping`, `Looking around`, `Music listening`.
|
||
- Notices: `Could not teleport Capri.`, `An expression could not be loaded. Keeping the current sprite.`, `An animation frame could not be loaded. Keeping the current pose.`, `Could not save Capri’s placement.`, `Could not save Capri’s presence setting.`, `Screen dimming could not be updated.`, `Capri could not start.` / `Your saved data has been preserved. Repair Capri with the installer and try again.` (fatal init dialog).
|
||
- Tray menu labels and tooltip: AV-29. Chip: `Show Capri`; recording chip: `RECORDING ACTIONS · ESC`, `Stop recording`.
|
||
- Detached HUD labels: `Show reply`, `Hide reply`, `Previous part of this reply`, `Next part of this reply`, `Subtitle playback`.
|
||
- Mini composer defaults (`renderer/avatar-composer.mjs:19-34`): message `Message Capri`, placeholder `Talk to Capri…`, attach `Attach files`, attachments `Attached files`, microphone `Enable microphone`, send `Send message`, sendHint `Send (Enter)`, remove `Remove attachment`, working `Capri is replying…`, microphoneLoading `Starting microphone…`, actionFailed `Could not complete this action. Please try again.`, unavailable `The input bar is unavailable. Open Capri to reconnect.`, keyboard `Message Capri`, menu `Show Capri`; thinking/internet fallbacks `Thinking mode: Off`, `Internet mode: Off`.
|
||
- Stopwatch: `Stopwatch`, `Running`, `Paused`, `Pause`, `Resume`, `Stopwatch controls`, confirm `Reset stopwatch?` / `Elapsed time will return to zero.` / `Reset`.
|
||
- Expression labels (portrait caption): manifest labels such as `Standing · Relaxed`, `Arms crossed · Focused`, `Perched on the frame · Playful`; reviewed poses `Sitting on the floor`, `Crouching`, …; music `Listening to music`. Caption = `Capri — <localized label>` for accessibility.
|
||
|
||
## 7. Security, privacy and permission invariants (must hold in Rust)
|
||
|
||
1. **Artwork is configuration, never model output.** Frames are loaded only from the validated manifests (§AV-01..03, AV-49): size caps, PNG signature/IHDR/colour checks, SHA-256 equality, path containment, no symlink escape (intro: no symlink in any segment, `nlink == 1`, `O_NOFOLLOW`, TOCTOU checks). Any failure fails closed: the Capri pack is rejected as a whole (fallback symbol + visible repair warning) — never a partially loaded pack, never a silent substitution; an invalid optional pack (music/intro) disables only that feature.
|
||
2. **The LLM can only pick an id.** Marker parsing accepts only listed ids or `pose/expression` pairs of active choices; intermediate frames (`idle-wink_half`, …), retired/inactive actions, paths and URLs are not selectable; markers, closing tags and `;listen` never reach TTS, subtitles or the transcript; only the first selection per reply counts; a selection is applied only to the currently active, non-aborted turn; the instruction states that graphics grant no tools.
|
||
3. **Tap reactions are not commands.** Tool-free (`tools: []`), loopback-only endpoint, no history/screen context, 72-token cap, bounded response, strict output filter (no markers/controls/HTML brackets), boundary tone for chest/pelvis ("nonsexual, do not describe anatomy"), cooldowns, cancelled by any foreground activity and by sleep; awake taps never interrupt a running reply, initiative, screen observation or playback; sleeping taps never wake Capri during a foreground task and only on the 10th tap.
|
||
4. **Window queries are minimal and identity-checked.** Only geometry of qualifying windows of the *same user* on the current desktop is used; Capri's own windows are excluded except the explicitly allowed visible Settings window; perch tracking verifies `(windowId, pid, process start ticks)`; window titles are untrusted, used only for in-helper matching and never stored or sent to the model by this subsystem; no window contents are read.
|
||
5. **Click-through is fail-safe toward the desktop.** Transparent pixels and hidden/disabled sprite regions must never intercept clicks; interactive regions must be validated to lie inside the window; a modal dialog makes the whole panel interactive; overlays never take keyboard focus and re-stacking must not steal focus.
|
||
6. **Mini composer forwards intent only.** Strict action schema (exact key sets, own data properties only), drafts ≤8000 chars, ≤4 files, 8/32 MiB caps, file bytes read only from paths returned by the native file dialog (absolute, no NUL, regular file, bounded streaming read), returned names are basenames, errors never echo paths; hidden in focus mode, on lock and shutdown; disabled when the avatar is not detached.
|
||
7. **Session lock / suspend / shutdown** reset every desktop layer, cancel reactions, hide chips, stop music and computer control (AV-47). Focus mode is not a privacy control (microphone/voice keep running) — keep the documentation honest.
|
||
8. **Persistence stores no conversation data** in shell files (only ids, geometry, booleans, numbers). Diagnostics may include `artwork` diagnostics (mode, manifest, frame count, failure code/message) but never images or window titles.
|
||
9. **External links** are fixed ids mapped to HTTPS URLs pinned to their default origin; the UI never supplies URLs.
|
||
10. **Single owner of state**: one process instance (lock), expression/state transitions only through the shell controller; Settings writes use an optimistic revision (`sha256` of the settings JSON) so a stale Settings draft cannot overwrite newer values.
|
||
11. **Credits** callsigns use a CSPRNG with rejection sampling; names are rendered as text (never HTML/markup).
|
||
12. **KDE cursor helper/script**: unique per-PID bus name, stale script unloaded before load, script unloaded on exit, minimal environment, bounded restarts (5). Do not expose the reporting D-Bus object methods beyond `Report(s)`; ignore malformed reports (must parse as two integers).
|
||
|
||
## 8. Windows-specific mechanisms and their Linux replacements
|
||
|
||
Strategy: **all Capri windows are X11 clients** on both targets (XWayland on KDE Plasma 6.8 Wayland, native Xorg on i3 4.25). This mirrors the existing bridge (`--ozone-platform=x11` in `packages/runtime/src/desktop-launcher.mjs:51-56` and `~/.local/bin/capri`: native Wayland broke the transparent companion and its clicks) and gives one code path for absolute positioning, stacking, input shapes and override-redirect overlays. Desktop *queries* differ: KDE uses KWin scripting over D-Bus (the X server cannot see Wayland windows, the real cursor or Plasma panels), i3 uses i3 IPC + X11.
|
||
|
||
### 8.1 Mapping table
|
||
|
||
| Capri mechanism (Windows/Electron) | KDE Plasma 6.8 Wayland (+XWayland) | i3 4.25 / X11 | Existing bridge |
|
||
|---|---|---|---|
|
||
| Transparent frameless `BrowserWindow` | ARGB32 visual (depth 32) X11 window, `_MOTIF_WM_HINTS` no decorations; KWin composites alpha | Same; **requires a compositor** (picom is started by this user's i3 config) — without it, fall back to an opaque panel background and rectangular input | Electron X11 |
|
||
| Always on top (`setAlwaysOnTop(true,'normal')`) | `_NET_WM_STATE_ABOVE` (KWin "keep above") | i3 floating windows are above tiled ones; `_NET_WM_STATE_ABOVE` has no layer meaning; fullscreen containers cover floating windows | Electron default |
|
||
| Overlay level `'screen-saver'` + `moveTop` every 750 ms | Override-redirect windows (KWin keeps unmanaged X11 windows in its top layer); still re-raise with `ConfigureWindow(stack_mode=Above)` | Override-redirect windows are unmanaged and drawn above everything, on all workspaces | — |
|
||
| `skipTaskbar` / tray-only | `_NET_WM_STATE_SKIP_TASKBAR` + `SKIP_PAGER` (Plasma task manager honours them) | no taskbar in i3 (polybar shows workspaces only) | Electron |
|
||
| Visible on every virtual desktop | `_NET_WM_STATE_STICKY` / `_NET_WM_DESKTOP = 0xFFFFFFFF` | `sticky enable` for floating windows (honours `_NET_WM_STATE_STICKY`); overlays are override-redirect anyway | — |
|
||
| `setIgnoreMouseEvents(ignore,{forward:true})` + 16 ms cursor polling | X11 input shape (XFixes `SetWindowShapeRegion`, `SK_INPUT`) — see §8.2; cursor from KWin script | X11 input shape; cursor via `QueryPointer` on root (works globally) | `main/linux-cursor.mjs` + `cursor.py` (KDE); Electron empty-shape toggling |
|
||
| `screen.getCursorScreenPoint()` | KWin script `workspace.cursorPos` via D-Bus (§5.3), converted to X11 px (§8.4) | `QueryPointer(root)` | `capri_linux/cursor.py` |
|
||
| `screen` displays/work areas, DIP, `scaleFactor` | Outputs + work areas from KWin script (`workspace.screens`, `clientArea`); X11 RandR monitors as cross-check; UI scale from `Xft.dpi`/96 | RandR 1.5 `GetMonitors` + i3 `GET_OUTPUTS`; work area per output = visible workspace `rect` from `GET_WORKSPACES`; scale from `Xft.dpi` (default 1) | `kwin.py`/`x11.py` `outputs()` (bounds only) |
|
||
| Display events | KWin `screensChanged` / RandR `ScreenChangeNotify` | RandR notify + i3 `output` events | — |
|
||
| Window geometry for docking (`avatar_window`) | KWin script: `frameGeometry` of qualifying windows (logical px) | i3 `GET_TREE` `rect` | `capri_linux/main.py:739-796` |
|
||
| WinEventHook + 500 ms poll to follow a perched window | Persistent KWin script pushing `frameGeometryChanged`, `minimizedChanged`, `windowRemoved`, desktop changes | i3 `SUBSCRIBE window/workspace` → re-query `GET_TREE`; 1800 ms poll fallback | none (1800 ms poll through the Python helper today) |
|
||
| Low-level mouse hook "release outside overlay" | Implicit pointer grab: a button pressed in our X window keeps delivering motion/release to it until release (also under XWayland) | Same | — |
|
||
| Desktop background context-menu verb "Teleport Capri" | Global shortcut "Teleport Capri to cursor" (portal) + tray item + `capri teleport` CLI | i3 `bindsym … exec capri teleport` + tray item | none |
|
||
| `globalShortcut` Ctrl+Shift+Space | `org.freedesktop.portal.GlobalShortcuts` (XGrabKey from XWayland only works while an X11 window is focused) | `XGrabKey` on root (or user `bindsym`) | Electron (X11 grab) |
|
||
| `Tray` | StatusNotifierItem (native in Plasma) | SNI via snixembed→XEmbed tray (present on this machine) or polybar tray | Electron libappindicator |
|
||
| `powerMonitor` lock/unlock/suspend | logind `org.freedesktop.login1.Session.Lock/Unlock`, `Manager.PrepareForSleep`; `org.freedesktop.ScreenSaver.ActiveChanged` (KDE) | logind signals; i3lock does not emit logind Lock unless invoked via `loginctl lock-session` → also watch `xss-lock`-style ScreenSaver or document | Electron |
|
||
| `prefers-reduced-motion` | Portal Settings `org.kde.kdeglobals.KDE` `AnimationDurationFactor == 0`, or GTK `gtk-enable-animations=false` | GTK settings / app override | Chromium |
|
||
| WebAudio procedural sounds | Synthesize PCM in Rust, play via `rodio`/`cpal` (ALSA → PipeWire) | same | Chromium |
|
||
| Native file dialog | `org.freedesktop.portal.FileChooser` | portal (if running) or GTK dialog | Electron |
|
||
| App identity / `.exe` grouping | `.desktop` file `capri.desktop`, `WM_CLASS=capri`, `_NET_WM_PID` | same | — |
|
||
|
||
### 8.2 Click-through on X11 (both targets)
|
||
- Preferred: **shaped input**. Each Capri window keeps an X input region = union of its interactive rectangles: control rects (AV-19), the sprite's padded visible box (12 px, AV-20) mapped through crop and lens bounds, the HUD/tab/arrow rects (AV-40), the composer rect when visible. Set with XFixes `CreateRegion` + `SetWindowShapeRegion(dest_kind = INPUT)` (Shape extension `ShapeRectangles` is equivalent). Recompute only when regions change (pose, placement, layout, presence, dialogs), coalesced to one per frame. Taps still check per-pixel alpha in software (AV-16), so the rectangle granularity is enough.
|
||
- Fallback (proven on this machine with Electron): full/empty input shape toggled from a 16 ms global-cursor poll exactly like `PointerController.tick` and `AvatarDetach.updatePointer`. Use this if XWayland/KWin turns out not to honour partial input shapes (open question Q1). Hover-driven behaviours (composer proximity 90 px, reply tab reveal 42/26 px, `interacting` flag) need the global cursor in both modes.
|
||
- During a press/drag keep the window interactive until release (pointer grab), and never change the input shape of a window that currently holds an implicit grab.
|
||
|
||
### 8.3 Global cursor on KDE Wayland
|
||
X11 clients only see the pointer while it is over an X11 surface. Port `capri_linux/cursor.py` to Rust with `zbus`: own `org.capri.cursor.p<pid>`, export `/` `org.capri.Report.Report(s)`, write the script to a private temp file (0600) and `loadScript(path, "capri-cursor")` after `unloadScript("capri-cursor")`, `run()`, parse `"x,y"` (integers) into the latest cursor value, unload on exit. Restart up to 5 times with 2 s delay; fall back to `QueryPointer` when unknown. Convert KWin logical px to X11 px with the XWayland scale (§8.4). On i3 just call `QueryPointer` (no helper).
|
||
|
||
### 8.4 Coordinates, DPI, multi-monitor
|
||
- Electron worked in DIP; persisted geometry (`window.json`, layout) is DIP. The Rust shell keeps **logical px** in persisted state and converts at the X11 boundary: `x11_px = round(logical · ui_scale)` with `ui_scale = Xft.dpi/96` (XResource on the root window `RESOURCE_MANAGER`, default 96). On Plasma 6 with "XWayland: apply scaling themselves", XWayland exposes device pixels and sets `Xft.dpi`; KWin script coordinates are Wayland *logical* px, so `x11_px = kwin_logical · xwayland_scale`. With a single global scale this is exact (the current Electron bridge relies on it). Mixed per-output scales are an open question (Q2).
|
||
- Per-display work areas (needed for clamping, docking, floor detection, reserved strips): KDE → KWin `clientArea(PlacementArea/MaximizeArea, output, desktop)` (Plasma panels are Wayland layer-shell surfaces invisible to X11; `_NET_WORKAREA` from XWayland is one rectangle for all outputs and must not be used per monitor); i3 → visible workspace `rect` per output (excludes i3bar/polybar docks), output `rect` = bounds. Reserved strip = bounds − work area.
|
||
- Size rules expressed in logical px: companion 480×660, sprite 108..240, chip 52, composer 124/344×44..240, radii 12/24/36/42/90, dead zone 30. Drag thresholds (5 px) are logical.
|
||
- Monitor topology changes reset the detached avatar and re-clamp windows (AV-18, AV-46).
|
||
|
||
### 8.5 Stacking, focus and i3 specifics
|
||
- KDE: set `_NET_WM_STATE_ABOVE` on the panel when "Always on top"; KWin focus-stealing prevention may refuse programmatic activation of the composer — activation through a user click on it is always fine (`_NET_ACTIVE_WINDOW` with source indication 2 + user time). Optional KWin window rules are not required.
|
||
- i3: the panel (fixed-size UTILITY window) floats automatically; ship and document a snippet for robustness: `for_window [class="^capri$"] floating enable, sticky enable, border none` and `no_focus [class="^capri$"]` for non-focusable surfaces. i3 places new floating windows at their requested position when `PPosition/USPosition` is set; later moves via `ConfigureWindow` are honoured for floating windows. Fullscreen windows hide floating windows on that output; overlays are override-redirect and remain visible (matches Windows "screen-saver" level behaviour).
|
||
- `ControlWindowLayer` (computer control): remove `_NET_WM_STATE_ABOVE` and lower the panel (`stack_mode=Below`) during control; restore afterwards.
|
||
|
||
### 8.6 Teleport to the cursor without the Windows shell verb
|
||
Replace AV-45 with: tray item (existing), global shortcut "Teleport Capri to cursor" (KDE portal; i3 `bindsym`), and a CLI subcommand `capri teleport` that signals the running instance through the single-instance socket (`{"cmd":"teleport"}`) → `teleportToCursor(currentCursor)`. No context-menu integration is planned (Plasma has no per-app desktop-background verb).
|
||
|
||
### 8.7 Reduced motion
|
||
Read once at start and on change: KDE → portal Settings namespace `org.kde.kdeglobals.KDE`, key `AnimationDurationFactor` (0 ⇒ reduced); otherwise GTK `gtk-enable-animations` (portal `org.gnome.desktop.interface enable-animations`). Add an explicit app setting override (new P2 key `reducedMotion: system|on|off`, defaulting to `system`) because i3 users often have neither.
|
||
|
||
### 8.8 Session lock and sleep
|
||
Subscribe to logind (`org.freedesktop.login1`): `Session.Lock`/`Unlock` for the current session, `Manager.PrepareForSleep(true/false)`; on KDE also `org.freedesktop.ScreenSaver` `ActiveChanged`. Map to AV-47.
|
||
|