Files
capri-core-rust/docs/spec/04-ui-panels.md
T
2026-11-11 20:20:49 +01:00

1048 lines
160 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 04 — Renderer UI: chat panel, reply bubbles, settings window and panels, theming, localization
Status: behavioral specification extracted from CapriCore 1.0.4 (`~/Capri`, GPL-3.0-only) for a pure-Rust rewrite (Arch Linux, KDE Plasma 6.8 Wayland + XWayland, i3 4.25 / X11).
Feature ID prefix: `UI-`. Source references are `path:line` relative to `~/Capri`. "Main" = Electron main process (`apps/desktop/main.mjs` and `apps/desktop/main/*`); "companion" = `index.html` + `app.js` renderer; "settings" = `settings.html` + `settings-app.mjs` renderer.
Synthetic examples only. No owner data from `data/` or `logs/` is quoted; file schemas were inferred from key/type shapes.
---
## 1. Purpose and scope
This spec covers every user-visible surface rendered by the two Electron renderers and the main-process glue that serves them:
| Area | Capri files (owned) |
|---|---|
| Companion window shell, toolbar, chat dock/composer, reply frame, history page, in-window cards | `apps/desktop/renderer/index.html` (1031 l.), `app.js` (3184 l.), `styles.css`, `cyberpunk.css`, `thinking-mode.{mjs,css}`, `internet-mode.mjs`, `button-feedback.mjs`, `overflow-ticker.mjs`, `panel-frames.mjs`, `startup-panel.mjs`, `update-notification.{mjs,css}`, `memory-hud.mjs`, `inference-picker.mjs` |
| Reply presentation logic | `reply-pages.mjs`, `reply-visibility.mjs`, `reply-bubble-outline.mjs`, `detached-reply-layout.mjs` (consumed by the detached avatar window, see 05-avatar spec) |
| Attachments | `attachment-composer.mjs`, `clipboard-files.mjs`, `history-attachments.mjs`, `attachment-viewer.{html,mjs,css}`, `main/attachment-viewer.mjs` |
| Confirmations | `confirmation-dialog.mjs`, `confirmation-requests.mjs`, `main/confirmations.mjs` |
| Settings window | `settings.html`, `settings-app.mjs`, `settings-api.mjs`, `settings-registry.mjs`, `settings-search.mjs`, `settings-location.mjs`, `settings-loading.mjs`, `settings-help.{html,mjs,css}`, `settings.css`, `main/settings-window.mjs`, `main/settings-channels.mjs`, `main/ipc.mjs` |
| Settings sections (panels) | `companion-panel.mjs`, `inference-panel.mjs`, `inference-endpoint.mjs`, `inference-privacy.mjs`, `api-key.mjs`, `models-panel.mjs`, `model-device-panel.mjs`, `huggingface-panel.mjs`, `knowledge-panel.mjs`, `saved-memory-panel.mjs`, `private-memory-panel.mjs`, `language-panel.mjs`, `language-settings.mjs`, `time-panel.mjs`, `updates-panel.mjs`, `user-tools-panel.mjs`, `workflows-panel.mjs`, `applications-panel.mjs`, `computer-appearance-panel.mjs`, `file-access-panel.mjs`, `discord-panel.mjs`, `developer-panel.{mjs,css}`, `credits-panel.mjs`, `credits.css`, `initiative-panel.mjs` |
| Main-side IPC owned here | `main/companion-ipc.mjs` (companion settings, personality, wake audio, bug report, community links), `main/access-ipc.mjs` (folder grants, Notepad/Calculator grants), `main/localized-dialog.mjs` |
| Theming | `interface-theme.mjs`, `cyberpunk.css`, `styles.css`, `settings.css`, `assets/fonts/exo2/*` |
| Localization | `interface-translations.mjs`, `language-settings.mjs`, `apps/shared/interface-locales.json`, `apps/shared/languages.json`, `apps/desktop/locales/*.json` (50 files), `config/interface-glossary.json` (+ `config/interface-locales.json`, build tool `tools/localization/build-interface-locales.mjs`) |
Hosted but specified elsewhere (only their placement, draft wiring and controls are listed here): speech/microphone pause panel, voice-effects panel, voice-calls panel, music-listening panel, screen snapshot/observation panel, voice-model panel, wake feedback, stopwatch HUD, subtitle controller timing (voice spec), avatar/portrait/CRT/glitch rendering (avatar spec), tray menu (window spec).
Out of scope: chat/turn engine, model management, speech engines, desktop actions back-ends. They are referenced through the interfaces in §9.
Key architectural fact: although `index.html` still contains `.preferences-panel` sections (languages, file access, applications, initiative, screen, time, voice effects, speech, dimming), the companion never shows them anymore. `preferencesOpened(id, true)` (`app.js:709`) redirects to `api.openSettings(PANEL_SECTIONS[id] ?? 'general')`. The settings renderer fetches `index.html`, clones those sections into its own DOM (`settings-app.mjs:117-130`) and is the only place they are interactive. The Rust port should keep a single implementation per panel, rendered only in the Settings window.
---
## 2. Feature catalog
Priorities: P0 = companion broken without it; P1 = expected by a Capri user; P2 = optional/niche.
### 2.A Companion window (chat panel)
#### UI-01 Companion window shell and layout modes — P0
- Native window (main, `main/secure-window.mjs:6-56`, `main.mjs:537`): 480×660 logical px, frameless, transparent background `#00000000`, not resizable/minimizable/maximizable/fullscreenable, `skipTaskbar`, always-on-top by default (`window.json.alwaysOnTop !== false`), no shadow, click-through outside published hit regions (UI-30).
- Body state attributes drive layout (CSS in `cyberpunk.css`): `data-presence` = `portrait` | `core`; `data-avatar-detach` = `attached|leaving|detached|teleporting|returning`; `data-avatar-dock="compact"` when the avatar is outside the frame; `data-reply-hidden`; `data-phase` (backend phase); `data-replying`; `data-voice-busy`; `data-signal` (presence signal state); `data-startup-intro`; `data-initialized="true"` after bootstrap.
- Layout modes:
- **Portrait** (expanded): absolute layout. Toolbar row at `top: var(--toolbar-top)=14px`, left/right 22 px; quick-actions row below it; reply frame (`#subtitle-stage`) at top 86 px; portrait frame (`#portrait-panel`) from `--home-frame-top` (232 px; 246 px if height ≤ 600; 211 px if ≤ 480) to `bottom: dock-height + 24px`; input dock anchored at bottom 10 px. `--dock-height` measured from `#input-dock` (default 100 px, 182 px when process graphs are visible).
- **Core** (compact "signal core"): CSS grid `minmax(0,1fr) min(310px,100%)` × rows `1fr auto 48px auto`; handle row (2/2), quick actions (3/2, width `100% - 48px - gap`), 48×48 presence-core button (3/2, left), dock (4/2). Reply frame, portrait and avatar hidden. Inference label and CTX hidden. Prompt mark hidden. Composer padding 6×10.
- **Compact dock** (`data-avatar-dock=compact`, avatar outside frame): flex column stacking handle(1), quick actions(2), reply(3), startup(4), dock(5) at the bottom; in core+compact the dock is hidden; toolbar width `min(100%, 9·button + 8·gap)` (8·button+56 px+8·gap when stopwatch visible).
- **History page** (`#history-panel` open): grid rows `auto auto 1fr auto` = handle, quick actions, history (fills), dock. Reply, portrait, avatar, presence core hidden. Startup card inserted above the dock if visible.
- When the reply is collapsed in portrait/attached/non-compact mode, the toolbars move down: `--toolbar-top = home-frame-top − 2·button − gap − 14px` (`cyberpunk.css:3466-3476`).
- Responsive breakpoints: width ≤ 380 px → side insets 14 px, packet labels 7 px, input hint hidden; ≤ 360 px (styles.css) subtitle 19 px; height ≤ 600/540/480/440/400 px → smaller subtitle (17/19/14/17/16 px depending on sheet; cyberpunk wins: 17 px at ≤600, 14 px at ≤480), packet context hidden at ≤ 480.
- `#window-shade` (dimming backdrop, UI-54) covers either the whole window or, in compact/collapsed modes, only the union of visible UI rects ±12 px (`dimming-settings.mjs: shadeBounds`).
#### UI-02 Handle (top toolbar) — P0
`index.html:27-89`, `app.js:1-3184`.
- Left `.identity`: status dot (3×12 px, colour `--signal`), `CAPRI` title (12 px, 800, letter-spacing 3.2 px, `#eff4d7`; accent colour in non-Capri themes), inference label button (UI-19), CTX button (UI-20).
- Right `.window-actions`, two groups:
- Community: `♥` Support the author → `openSettings('support')`; `!` Report a bug → `openSettings('bug')`.
- Window controls: Keep Capri visible (`presence-toggle`, aria-pressed = pinned) → `togglePresence()` → `setPresencePinned(bool)` (error notice "Could not save Capri’s presence setting."); Leave frame / Return to frame (`avatar-detach`, avatar spec; disabled while pending/arriving or no frame); Hide (`−`) → `api.hide()` (title "Hide to tray" when attached, "Hide interface" otherwise); Quit (×) → `api.quit()` (main shows a 4-choice confirmation, §6).
- Dragging: pointerdown on `#handle` (not on a button, not while sprite-dragging, primary button) → `api.startDrag()`; pointerup/cancel/lostpointercapture, window blur, document hidden → `api.endDrag()`. Title tooltip "Drag to move the whole window".
#### UI-03 Quick-actions row — P1
`index.html:90-218`, `app.js:291-326`.
- Conversation group: header microphone toggle (wake listening; voice spec), voice toggle (`aria-pressed`=voice enabled; labels "Mute Capri" / "Unmute Capri" / "Retry voice" on error / "Text replies only" disabled when speech language is `off`; tooltip "Capri’s voice is loading…" while enabled but not ready) → `setVoiceEnabled(error ? true : !enabled)`; music toggle (music spec); history toggle (`aria-expanded`); subtitle reveal (shown only while the reply is collapsed).
- Capabilities group: screen indicator (screen spec), application access (`data-quick=applications`): left click toggles pause → `api.applicationAccess(!enabled)` (button disabled during the call; title "Pause application access"/"Enable application access"); right click/context menu → `openSettings('applications')`; timers → open Settings "time"; stopwatch HUD (replaces the timers button while a stopwatch is shown; time spec).
- Settings group: Languages → Settings "languages"; gear → `api.openSettings()` with no section (resume last location).
- Toolbar buttons: `--toolbar-button-size` 26 px (24 px in core mode; 22 px in core with stopwatch), gap 4 px (2-3 px in core).
#### UI-04 Composer — P0
`index.html:322-472`, `app.js:1388-1402, 2600-2646, 2885-2902`.
- Elements left→right: prompt mark `⌁` (pink, hidden in core), textarea `#message` (`dir=auto`, `rows=1`, `maxlength=8000`, placeholder "Talk to Capri…", spellcheck off), wake feedback overlay (voice spec), hidden file input (multiple), attach button (paperclip), thinking toggle (UI-13), internet toggle (UI-14), input microphone key (36×32 cut-corner; direct voice input; voice spec), Send `↗` (title "Send (Enter)"), Stop `■` (title "Stop reply (Esc)").
- Keyboard: `Enter` without Shift and not during IME composition → `send()` (default prevented); `Shift+Enter` inserts a newline (native).
- Auto-height: reset to 29 px, then `clamp(scrollHeight, 29, max)` with `max = 29` if window inner height ≤ 400, `48` if ≤ 540, else `67` px.
- On every input: `draftRevision++` (mini composer sync, UI-32); throttled `api.activity()` (at most every 150 ms); presence touch; `api.draftState(busy)` sent only when "draft non-empty or attachments present/pending" changes.
- Footer: status text (UI-06), Reconnect link, hint `ENTER ↵ / ESC ■` (7 px, hidden ≤ 380 px).
#### UI-05 Send pipeline and control enablement — P0
`app.js:1746-1841` (`controls()`), `app.js:2600-2646` (`send()`).
- `busy = submitting || callSpeechPending || activeTurnId || languageInstall.phase=='installing'`.
- Send **hidden** while `activeTurnId`; Stop visible iff `activeTurnId || voiceBusy || callSpeechPending`.
- Send **disabled** iff any: `!ready` (bootstrap incomplete) · `busy` · attachments pending · (backend phase ≠ `ready` AND power phase = `awake` AND draft is neither a clip command ("Capri, clip that", `clip-command.mjs`) nor a sleep command (`sleep-service.mjs`)) · (empty trimmed draft AND no attachments) · `draft.length > 8000` (UTF-16 units) · attachments present while backend ≠ ready.
- Attach button disabled iff `busy || pending || !ready || backend ≠ ready`.
- `send()`: guard disabled; `text = draft.trim()`; capture attachment ids, thinking and internet flags; `submitting=true`; clear notice; stop local voice + `api.stopVoice()`; unlock audio if voice enabled; `id = uuid v4`; record paint start (map capped at 32 entries); clear textarea; then:
- with attachments: `api.sendAttachments({id, text: text || 'Describe the attached files.', attachmentIds, thinking, internet})`; if result `{accepted:false, message}` → restore draft text, clear attachments, show message in the attachment info line.
- else `api.send({id, text, thinking, internet})`.
- on exception and no active turn: restore draft; notice = screen-image warning (screen spec) or "Your message could not be sent. Reconnect or try again.".
- finally `submitting=false`, resize, `controls()`.
- Stop (`stopReply`, `app.js:859`): clear pending call speech, stop playback, `api.stopVoice()`, and if a turn is active `api.cancel(turnId)` (failure notice "The reply could not be stopped.").
#### UI-06 Turn rendering, status footer, reconnect — P0
`app.js:2483-2598` (event handling), `app.js:1782-1790` (status).
- `turn.started {turnId, source, silent, user?, assistant}`: start paint timer; configure reply visibility (speech expected iff not silent and voice enabled/no error/language≠off); thinking & internet `begin(turnId)`; clear attachments if `source==='attachment'`; reset Spotify-tool set; begin voice reply (or stop voice if silent/error); set packet origin and input (UI-07); `activeTurnId=turnId`; follow output; clear notice; put user and assistant messages; reset subtitles.
- Events for another turn are ignored. `turn.web-search` → UI-14 (ready phase with `sources` copies them onto the assistant message). `turn.preface`/`turn.approach` → UI-13. `turn.tool {tool:'spotify_control', phase, callId}` → maintain pending set (status "Working with Spotify…").
- `turn.delta {turnId, text}` appends to the assistant message; first visible text while document visible → after 2 animation frames `api.responsePainted({id, elapsedMs})`.
- `turn.completed | turn.failed | turn.cancelled {assistant, warning?, message?}`: finalize message + subtitles; `activeTurnId=null`; notice = `warning` or (failed ? `message` : ''); screen-reader announcement "Capri has replied." (completed) or the message.
- Status line text: active turn → "Working with Spotify…" if Spotify tools pending else "Capri is replying…"; else voice busy → "Capri is speaking…"; else backend message (initial "Starting local core…"). Status is visually hidden when phase=`ready` and not replying (unless voice busy). `aria-live=polite`, `unicode-bidi: plaintext`.
- Reconnect button visible iff backend phase `offline` and not busy → `api.reconnect()` (error notice "Could not reconnect. Check the local core.").
- Bootstrap (`app.js:3082-3184`): `api.bootstrap()` returns the full snapshot (§9.2). On failure: backend = `{phase:'offline', message:'Capri could not initialize.'}`, notice "Restart Capri to restore the connection.". `snapshot.warning` (newline-joined) is shown as a notice. Messages are rendered, the packet input is set from the last user message (or prompt "Connection established."), the last assistant message is shown in the reply frame.
#### UI-07 Reply frame (subtitle stage) — P0
`index.html:238-282`, `app.js:436-458, 1414-1427, 2936-2943`.
- Structure: collapse button (top-right, 26 px, "Hide reply"), frame (`data-panel-cut=12`): packet context row (origin label + last input, italic, ellipsized, `dir=auto`), packet title (`CAPRI` in acid + pink " /", then "INCOMING TRANSMISSION"), welcome paragraph "Hey. I'm here." (shown until any reply exists), cue text `#subtitle-text` (`dir=auto`, selectable, 18 px/1.35, weight 500), state label (8 px: "THINKING…" when streaming with no cue, "REPLYING", "STOPPED", "RESPONSE INCOMPLETE"), pager (`‹` "Previous part of this reply", `n / total`, `›` "Next part of this reply", shown iff ≥ 2 cues).
- Origin labels: default `YOU`; `initiative` → `CAPRI // INITIATIVE` with input prompt "A thought of her own."; `screen` → `YOU // SNAPSHOT`; `avatar-click` → `CAPRI` with empty input. Prompts are translated; user text is data.
- Collapse/reveal: Hide reply → `replyVisibility.hide()` and focus the reveal button; Show reply (quick-actions row) → `reveal()` and focus collapse. Hover/focus/selection inside the stage and an open history page act as "holds" on auto-hide (UI-09). Body `data-reply-hidden=true` removes the stage entirely.
- Stepping (`‹`/`›`) reveals, pauses automatic paging.
#### UI-08 Subtitle pagination (SubtitleController) — P0
`subtitle-controller.mjs` (voice-adjacent, logic needed here), `subtitles.mjs`.
- Cue limit (characters) = `clamp(floor(stageWidth/10)·3, 48, 144)`; a cue must also fit ≤ 3 rendered lines of `#subtitle-text` (measured with the element font, width −10 px, letter spacing included).
- Cues via `sentenceSubtitleCues(text, limit, fits, final)`: pack whole sentences while they fit; split a too-long sentence with `subtitleCues` (binary search on fit, break preferably after `.!?…` past 50 % of the limit, else at the last space). While streaming and following voice (`final=false`), an unfinished trailing sentence is not reflowed into a completed page.
- Automatic advance when not paused and history closed: following voice → page index tracks playback position (`subtitleSpeechPlan`, timers to the next step, min 12 ms); not following voice → advance after `readingMs(cue) = clamp(2200 + 48·chars, 3600, 11000)` ms from when the cue was shown.
- `interrupted`/`error` statuses pause paging. Hidden reply: no measuring; the detached avatar still receives the current cue (`onCue`).
#### UI-09 Reply auto-hide (ReplyVisibility) — P1
`reply-visibility.mjs:1-125`.
- Config: `enabled = replyAutoHide !== false`; `delay = clamp(replyAutoHideSeconds ?? 8, 2, 60)` s.
- Per reply record `{id, text, complete, generated, playing, speechExpected, protected}`; a new turn id resets `manual=false`, shows the reply.
- Timer armed only when: enabled ∧ complete ∧ non-empty text ∧ ¬protected ∧ ¬playing ∧ ¬(speechExpected ∧ ¬generated) ∧ no holds ∧ ¬manual ∧ ¬hidden. Delay = configured delay if speech expected, else `max(delay, min(30000, 30 ms × text length))`.
- Statuses `error|cancelled|incomplete` and `voice.cancelled`/`voice.error` mark the reply protected (never auto-hidden; shown again unless manually hidden).
- Holds: `hover`, `focus`, `selection` (text selected inside stage), `history` (history open), `detached` (pointer over the detached bubble). Manual `hide()`/`reveal()` sets `manual=true` and survives streaming of the same turn.
- Disabling the option un-hides a non-manual hidden reply. A settings reset (`companion.settings` with `reset:true`) calls `reveal()` so the current answer stays readable.
#### UI-10 Detached reply bubble logic — P1 (pure logic consumed by the avatar window)
- `ReplyPages` (`reply-pages.mjs`): presentation-only pager over the live cue plus history.
- `replyHistory(messages)`: newest-first scan of assistant messages, max 30 replies, each ≤ 16 000 chars, total ≤ 64 000 chars; ids 1–128 chars without control chars; duplicate ids skipped; text truncated without splitting surrogates, control chars removed (except `\t\n\r`), trimmed; result in chronological order. Never forwards user text.
- `update({text, turnId, history}, fits, layoutKey)`: cue ≤ 512 chars; id = turnId or `__capri-live__`; fits/layoutKey changes clear the page cache; pages = sentence cues (limit 240, `fits ∧ ≤240 chars`) per record with `{start,end}` offsets in the whitespace-normalized text; live page = page containing the cue's offset (searched forward from the last offset, then from 0; unknown new cue → last page start).
- `step(±1)` creates a manual selection `{id, offset}` that survives stream updates; view = `{text, index, total, previous, next}` where text is the live cue if it fits and nothing is selected, else the page text.
- `detachedReplyLayout` (`detached-reply-layout.mjs`): margin 8, gap 24. With a status badge: prefer above (`badgeY − margin − gap ≥ replyHeight`), or below when the avatar is inverted and space allows; else left/right if `max(left,right) ≥ min(144, width)` (width shrunk to the side space); else below. Tab = 28×20 (vertical sides) or 24×clamp(badgeH,20,32) (horizontal). Without a badge the bubble sits centred above the crown with a 24×24 tab on its right edge. `hud` = union of badge, tab and (unless collapsed) bubble.
- `replyBubbleOutline` (`reply-bubble-outline.mjs`): rounded rect (radius 9) with an optional triangular tail (length ≤ 16, base width 18) on the side facing the face target; corner targets pick the side by ray from the centre; base clamped `[r+half, edge−r−half]`, optional anchor moves only the base; tail length 0 (dialogue-only style) → plain rect; no NaN/∞ for any input; returns `{path, side, tip, base, bounds}`.
- Detached text fit (`avatar-detach.mjs:880-905`): width = text box − 24 px; lines = `floor((min(150, innerHeight − 88) − 18) / lineHeight)`; bubble width `min(344, innerWidth − 16)`.
#### UI-11 Conversation history page — P0
`index.html:474-494`, `app.js:1312-1334, 1946-1991`, `cyberpunk.css:3290-3456`.
- Open via quick-actions history toggle; close via ×, toggle, or Esc. Opening: abort if a legacy in-window panel refuses to close; hold reply visibility; `interfaceBusy(true)`; presence reveal; hide other panels; `followOutput=true`; scroll to bottom; focus the close button. Closing focuses the toggle. `aria-expanded`/label "Open/Close conversation history".
- Message article per message id (`role=log`, aria-live off): label ("You" translated / "Capri" literal; assistant label pink), attachment list (UI-17, user messages), text (`dir=auto`, `pre-wrap`, 13 px/1.6, user `#bfcfd3`), web sources (assistant, UI-14), status ("Stopped" for `interrupted`, "Response incomplete" for `error`). Streaming empty assistant text shows "Thinking…". Empty list → "No messages yet.".
- Follow-output: scroll handler sets `follow = scrollHeight − clientHeight − scrollTop < 45`.
- `conversation.cleared` event: clear thinking/internet/attachments/voice/subtitles/messages, packet origin/input, show empty state.
- Transcript contents come from the chat subsystem (max 200 messages, text ≤ 65 536 chars, statuses `complete|streaming|interrupted|error`).
#### UI-12 Notices and announcements — P0
`app.js:1661-1672`, `index.html:339-344`.
- `notice(text, severity='error')`: strips the Electron prefix `^Error invoking remote method 'capri:[a-z-]+': (?:Error: )?`; screen-image warnings force severity `warning`; text displayed through `ui.text()` (backend messages are English source keys); Report button ("Report a bug" → Settings "bug") hidden for warnings; Dismiss clears; empty text hides. No auto-timeout in the companion. Re-rendered on locale change.
- Visual: cut-corner 10 px card, frame `#ff5679` α .9, bg `#101822f5`, text `#ffe0e6` 10 px; warning frame acid `#f4ed75`, bg `#211e15f5`, text `#fff1bc`.
- `#announcement` (screen-reader only, `aria-live=polite`) receives turn completion text.
#### UI-13 Thinking mode toggle — P1
`thinking-mode.mjs:1-143`.
- Session preference (not persisted): button `aria-pressed`, label "Thinking mode: On/Off", tooltip label + "Take more time to check difficult answers."; disabled until ready and while a change is pending.
- `setEnabled(bool)`: optimistic flip, single-flight, `api.setThinkingMode(bool)` → `{enabled}`; on error restore previous and show the error.
- Per turn: `turn.preface {text}` (≤ 280 chars, control chars → space) shown in `#thinking-preface` until the answer starts; `turn.approach {text}` (≤ 900 chars) available behind an "Approach ▾/▴" toggle (expanded state reset per turn, survives the answer). Never renders reasoning transcripts. Cleared on terminal events/`conversation.cleared`.
- Pressed style: text `#ffed52`, border currentColor, 13 % tinted background.
#### UI-14 Internet mode toggle and web sources — P1
`internet-mode.mjs:1-157`, `main.mjs:5783-5811`.
- Session preference: label "Internet mode: On/Off", tooltip + "Search the web for the current request only. Chat history, screenshots and files are not sent automatically."; disabled when not ready, busy (reply, submitting, attachments pending) or pending. Host rejects changes during an active reply ("Wait for the current reply to finish.").
- Per-turn status line (`#internet-status`, polite): `searching` → "Searching the web…", `ready` → "Web sources ready.", `unavailable` → "Web search is unavailable." or exactly one of the two allowed notices ("Web search found no results.", "Web search was skipped because the request may contain private credentials."). Any other text from the event is ignored.
- Sources (assistant messages): up to 5 entries, title ≤ 240 chars plain text, http/https URLs without credentials, URL ≤ 2048 chars shown only as tooltip; button text `[n] title`; click → `api.openWebSource({turnId, index})` (host re-reads the stored message, never trusts a renderer URL; turnId must be a 36-char UUID, index 0–4). Button disabled during the call.
#### UI-15 Attachment composer — P1
`attachment-composer.mjs:1-365`.
- Inputs: paperclip → file picker (multiple); drag & drop of files anywhere (only dropped on the composer is accepted; `dragover` with files is always allowed to avoid navigation); paste into the textarea of clipboard files (UI-16).
- Max 4 attachments total; extra files → message "Attach up to four files at once.". Single-flight (`pending`); a newer `add`/`clear` (revision) cancels older work and removes late uploads.
- Accepted extensions: images `png jpg jpeg webp gif`, video `mp4 webm`, text-like `txt md csv tsv json log docx odt pdf`. Others → "Capri cannot read this file format yet.". Media requires the active model to support vision (`attachmentVision`) else "The active model cannot read images or video frames.".
- Size: 1 byte … 8 MiB (32 MiB for video) else "This file is empty or too large.".
- Images: header sniffing (PNG IHDR, GIF, WebP VP8/VP8L/VP8X, JPEG SOF scan within first 256 KiB) with `width·height ≤ 18 000 000`; rendered into a 1280×720 opaque sheet `#111827` (letterboxed). GIF: up to 4 frames evenly spaced (frame count 1–1200), labels "Frame n". Video: duration (0,120] s, 4 frames at `(i+0.5)/4·duration` in a 2×2 grid with labels "x.x s" (16 px system-ui `#ecffff`), each seek/load times out at 3.5 s. Payload = PNG ≤ 3 MiB.
- PDF: text extraction (pdf.js, no eval, no font face): ≤ 30 pages, ≤ 12 001 chars, 6 s timeout; empty → error; `shortened` if more pages. Other text files are sent as bytes ≤ 8 MiB.
- Name: control chars removed, last 160 chars. `api.addAttachment({name, originalBytes, bytes})` → `{accepted, id, shortened?, animated?, message?}`; info messages "Capri will read the first part of a long document.", "Capri reads sampled frames without audio.", decode failure "Capri could not read this file or its media codec.".
- Draft chips: button "`name` ×" (tooltip "Remove {filename}") → remove + `api.removeAttachment(id)`; info line joins messages, "Preparing attachments…", and "Files are shared with the active API when sent." when the inference source is remote.
#### UI-16 Clipboard files — P1
`clipboard-files.mjs:1-68`. Only the files carried by an explicit paste event: never clipboard text/HTML, paths or remote URLs. File names: last path segment, control chars removed, last 160 chars; nameless bitmaps get `clipboard-image.{png|jpg|webp|gif}` by MIME, else `clipboard-file`. Mini-composer transport (`clipboardFilePayload`): ≤ 4 files, bytes read only for supported extensions within limits (others sent as empty placeholders so the owner shows the normal warning), `overflow` flag if > 4.
#### UI-17 History attachment cards — P1
`history-attachments.mjs:1-142`. Up to 4 records per message, each `{id: uuid, name ≤160, kind ∈ image|document|video|animation, bytes, preview}`. Card: thumbnail button (if `preview` and kind ≠ document) loading `attachments/<id>/thumb.png` (lazy), expand icon, name (`<bdi>`, ellipsized), info "EXT · size" (B/KB/MB decimal, locale number format). Click → `api.openAttachmentImage(id)`; missing thumbnail → disabled "Image preview unavailable"; a failed viewer launch only marks unavailable without disabling (retry allowed). Re-render skipped if `lang + JSON(files)` signature unchanged.
#### UI-18 Attachment image viewer — P2
`main/attachment-viewer.mjs`, `attachment-viewer.{html,mjs,css}`.
- Separate fullscreen frameless window on the companion's display (bg `#07131c`, always-on-top if the companion is), no preload/IPC, no navigation/new windows; Esc closes; F5/Ctrl+R blocked; context menu and image drag disabled; renderer crash closes it. One viewer at a time (new open closes the previous; revision guards late loads).
- Payload `{id, name, theme, labels:{close, fit, actual, unavailable, preview, language, direction}}`; id must be a v1–5 UUID; image `attachments/<id>/preview.png`.
- UI: header "CAPRI //" + file name, buttons "Fit to screen" / "Actual size" (aria-pressed, disabled until loaded), Close (×); stage with image (fit or 1:1 scroll); footer "W × H" + "Esc Close". Failure → "Image preview unavailable". Theme applied via `applyInterfaceTheme`.
#### UI-19 Inference picker (Local/API quick menu) — P1
`inference-picker.mjs:1-270`, `inference-panel.mjs:26-45`.
- Label: mode `API` (remote or setup required) or "Local"; detail = provider display name (OpenRouter, Hugging Face, ProxyAPI, DeepSeek, Google Gemini, else hostname) or "OFFLINE" (setup required) or local model name; remote model shown after "· " (hidden in core mode). API mode text `#f1dd8b`. `aria-label` = "Current model · …". Trailing `▾`.
- Menu (`role=menu`, fixed, width `min(360, innerWidth−16)`, below if ≥ 200 px or more space than above; RTL aligns to the right edge): loading "Current model…", heading, busy notice "Wait for the current reply to finish." (choices disabled while a reply is active), choices (`menuitemradio`): Local (+ residency `CPU`/`GPU`/`GPU + CPU`/`—` when active) and saved API profiles (label = name or hostname; disabled with "No API key is saved." when `canConnect=false`), then shortcuts "Language model" and "API connections" (open Settings sections).
- Keyboard: ArrowDown/ArrowUp on the button opens (focus active/first, or last for ArrowUp); in menu ArrowUp/Down wrap, Home/End, Tab closes, Esc closes (captured). Outside pointerdown and window blur close without refocus.
- Select: no-op if busy/unavailable/active. Local: fetch model status (refresh if empty or inventory unavailable); if the configured local model is not installed/supported → open Settings "models"; else `api.useInferenceApi(null)`. API → `api.useInferenceApi(id)` (main asks "Change AI provider?" and restarts). Closing the menu cancels a pending lookup (request counter).
#### UI-20 Telemetry HUD: memory gauges, CTX, process graphs, resource warnings — P2
`memory-hud.mjs:1-496`, `main.mjs:4348-4399`.
- Settings: `memoryMonitor`, `processGraphs`, `memoryStyle` (rings|bars), `memoryIntervalSeconds` (3|5|10, invalid → 3). Polling only while active, window visible and document visible; one request at a time; `api.memoryStatus()` → `{ram, gpus[], context, processLoad, cpu, sampledAt, gpuSampledAt}`.
- RAM/VRAM gauges (hidden when graphs shown): busiest GPU by used/total; pressure normal/medium (≥75 %)/high (≥90 %)/unknown; ring = SVG circle `pathLength=100`, `stroke-dasharray used 100`; bar 4 px. `role=meter` with aria values when known.
- CTX button: last-request tokens `used/total` (only when `source==='last-request'`), percent; title "Last request: {used} / {total} tokens. Click to change context."; click → `openSettings('model-context')` (= models section, focus context select).
- Process graphs: 4 cards CPU/GPU/RAM/VRAM, 24-sample sparkline (70×16 viewBox, gaps for missing samples, scale 100), readings % plus °C (CPU/GPU) or GB (RAM/VRAM, decimal GB), Capri's own process share in the tooltip.
- Resource warnings: thresholds CPU temp ≥ 95 (recover ≤ 90), GPU temp ≥ 87 (≤ 82), RAM ≥ 95 % (≤ 90), VRAM ≥ 95 % (≤ 90); a warning needs two distinct consecutive high samples; dismissible (×) until recovery. Texts "{device} is overheating ({value} °C)." / "{device} is nearly full ({value}%).".
- Monitor display button: click toggles graphs; the `▾` part, ArrowDown or context menu opens a menu Circles/Bars/Graphs (main native menu) → `api.monitorDisplay('toggle'|'menu')`. Error "Monitor display could not be saved.".
#### UI-21 Startup progress card — P1
`startup-panel.mjs:1-59`. Card "CAPRI pre-alpha" + running stage names joined by " · " ("Starting local core…", "Preparing language models…", "Preparing speech recognition…", "Preparing Capri’s voice…") + progress + ETA. Stage `{id, state: waiting|running|ready|failed, started(ms), estimate(s)}`. Progress = `min(98, Σ/stages·100)` where finished = 1 and running = `min(0.9, elapsed/estimate)`; ETA "Estimated remaining: {seconds} s" = `ceil(max(estimate − elapsed))`; if no running stage or any is overdue: indeterminate + "Still preparing. First startup may take longer.". Re-render every 500 ms; hidden when `finished` or no stages.
#### UI-22 Confirmation dialog (renderer) — P0
`confirmation-dialog.mjs:1-79`, `confirmation-requests.mjs:1-28`.
- Modal (`<dialog>` with backdrop `#020a10b8` + 3 px blur), card width `min(410px, 100%−40px)`, kicker "CAPRI // CONFIRM", title (h2, translated), detail (translated), action buttons. Queue: one dialog at a time, later `ask()` calls wait.
- Choices default `[{cancel,'Cancel'}, {confirm, confirmLabel='Confirm', danger}]`; custom `choices[]` with ids. `delayMs`: non-cancel buttons disabled and labelled "{label} ({seconds} s)" (100 ms refresh, ceil seconds). Esc/`cancel` event → `cancel`. Focus goes to the cancel button (or first); previous focus restored. AbortSignal closes with `cancel`.
- In the companion, opening reveals the presence, marks the interface busy and makes the whole window a hit region.
- `ConfirmationRequests.request(event)`: dedupe by id; `prepare()` (companion: legacy panels' `beforeClose`; settings: await pending draft writes and refuse while applying drafts) → if not ready respond `cancel`; respond `{id, choice}` via `api.confirmAction`; `confirmation.closed {id}` aborts (no response sent).
#### UI-23 Confirmations broker (main) — P0
`main/confirmations.mjs:1-62`. Single pending request; a second request while one is pending resolves `cancel` immediately. Validates ≥ 2 unique non-empty choice ids including `cancel`; `delayMs` integer 0–10 000. Emits `confirmation.request {id, title, detail, confirmLabel?, danger?, delayMs?, choices}`; timeout 180 s → cancel; abort signal → cancel. `respond({id, choice})` rejected if id mismatch, unknown choice, or a non-cancel choice before `acceptAfter = now + delayMs`; on accept emits `confirmation.closed {id}`. `request()` resolves boolean (`choice==='confirm'`), `choose()` resolves the id. `show()` focuses Settings if visible else shows the companion.
#### UI-24 Action approval card — P0 (consent gate)
`index.html:1018-1030`, `app.js:2160-2183, 664-681`. Event `action.approval {proposal: {id, title, detail, expiresAt} | null}`. Card (frame `#f5e955`, bg `#091a21`) with translated title, untranslated detail (pre-wrap, max 170 px scroll), help "Only approve actions you requested. This request expires in 90 seconds.", Confirm/Cancel → `api.actionRespond({id, accepted})` (both buttons disabled during the call) → notice `value.confirmation ?? (value.cancelled ? 'Cancelled.' : 'Done.')`. Timer at `expiresAt` auto-rejects (`accepted:false`) and hides.
#### UI-25 Time alert card — P1
`index.html:1010-1017`, `app.js:2151-2159, 655-663`. `time.due {object}` → reveal presence, show title or "Timer finished.", buttons "Timers and reminders" (open Settings time) and Dismiss (`timeAction({action:'cancel', id})`). `reminder.delivery {state:'failed', error}` → notice (default "Reminder voice unavailable."). `reminder.wake` → wake + reveal.
#### UI-26 Update notification card — P2
`update-notification.mjs:1-109`. Shown when `status.notification.tag` is a SemVer tag (optional `v`, no leading zeros in numeric pre-release parts, ≤ 80 chars) not dismissed in this run. Label "Updates", headline "A new update is available: {version}", buttons Update ("Downloading update..." while pending) → `openSettings('updates')`, `remindUpdateLater()`, `downloadUpdate()`; "Remind me later" → `remindUpdateLater()` then dismiss the tag for the session. Single-flight; failure shows notice and keeps the card.
#### UI-27 Button press feedback — P2
`button-feedback.mjs:1-75`. Capture-phase listener on trusted clicks on enabled buttons when `buttonFeedback` is true (preview button follows its checkbox draft): animate background to `mix(currentColor 38%, background)` + inset 1 px ring + inset 18 px glow (28 %), keyframes lit@0, lit@0.18, base@1 over 520 ms ease-out; reduced motion: constant lit 220 ms. Paint-only (no layout change, no sound, no glitch). Cleared when the document is hidden.
#### UI-28 Overflow ticker — P2
`overflow-ticker.mjs:1-43`, `cyberpunk.css:194-225`. Used for the microphone label/transcript. If content width exceeds the box by > 1 px: alternate horizontal scroll by the overflow distance (RTL-aware), duration `clamp(distance/22 + 3, 5, 40)` s, hold 15 % at each end; pauses on hover/focus; disabled under reduced motion; title = full text.
#### UI-29 Panel frames (cut-corner contour + glitch ghosts) — P1 (visual identity)
`panel-frames.mjs:1-54`, `cyberpunk.css:1135-1215`. Every element with `data-panel-cut=N` gets an overlay path `panelPath(w, h, cut=N, stroke=2.5)`: inset `i = stroke/2 + 0.35`; `c = clamp(cut, 0, min(w/4, h/3))`; `d = c + i·(√2−1)`; path `M d,i H w−i V h−d L w−d,h−i H i V d Z` (top-left and bottom-right corners cut). Four strokes: outline (`--frame-color`, α `--frame-alpha`, width 2.5), accent dash (`dasharray 40 800`, offset −27, α .74), cyan and pink ghosts (width 3.5, opacity `glitch·0.88`, dasharray `37 19 8 41 91 27`, translated by ±(`--glitch-x`, `--glitch-y`)). Ghosts hidden under reduced motion. Panels clip to the same polygon (12 px for panels, 10 px for notice/update card, 6–8 px for small keys/cards).
#### UI-30 Hit regions and footprint publishing — P0 (interface to window subsystem)
`app.js:2648-2747`.
- Recomputed on the next animation frame after any layout change (ResizeObserver on body, hit regions, sprite region). Candidates: visible elements with `[data-hit-region]`; in compact/collapsed modes also `#handle, #input-dock, #subtitle-stage, .resource-warning` (+ `#portrait-panel` unless compact) for the shade backdrop.
- `controls` = hit rects clipped to the window, zero-area removed, rects fully contained in another (earlier or larger) removed. While a modal confirmation is open: one full-window rect. In core mode rects are clipped to `.dock-notifications`.
- `footprint` (compact only): `shadeBounds` of visible rects at the resting float offset, floored/ceiled to integers (window clamping by main).
- `sprite`: avatar hit rect (avatar spec) with `enabled` and optional CRT `lens`.
- `api.setRegions({controls, sprite, footprint?})`. Main validation (`geometry.mjs:124`): ≤ 32 controls, finite, inside window bounds (+2 px tolerance). The Rust port must cap/merge to 32 rather than fail silently.
#### UI-31 Keyboard map and focus — P0
- Companion `keydown` priority (`app.js:2820-2884`): Esc closes, in order, models panel, updates panel; if a confirmation is open nothing else; companion panel, dimming, voice effects (also stops a preview playback), language, file access, applications, initiative, screen, history page; otherwise Esc stops an active reply/voice/call speech. Composer: Enter/Shift+Enter (UI-04). Picker keys (UI-19). Monitor display ArrowDown. Time dials: mouse wheel steps ±1 unit.
- Settings `keydown` (`settings-app.mjs:1726-1739`): ignored if a dialog is open; while loading Esc closes immediately; else closes an open help popup; else if the draft bar is shown → "Keep editing"; else `close()`. Search box: Enter clicks the first result, Esc clears the query (stopPropagation).
- Focus rules: history open → close button, closed → toggle; reply collapse ↔ reveal; confirmation → cancel then restore; settings panels focus their first control (language interface select, file add, initiative level, Notepad checkbox, speech slider); draft save → close button; failed draft apply navigates to its section.
#### UI-32 Mini composer bridge (detached avatar) — P1
`app.js:1843-1944`. While ready, the companion publishes a sanitized snapshot to the floating mini composer: `{draft, draftRevision, canSend, canAttach, busy, attachments:[{id,name}], thinking:{enabled,label,hint}, internet:{…}, microphone:{loading, listening, disabled, label}, labels:{message, placeholder, attach, attachments, microphone, keyboard, menu, send, sendHint, remove, working, microphoneLoading, actionFailed}, locale, status, error, theme}` (deduplicated by JSON). Actions `avatar.composer.action {id, action}`: `edit {revision, draft}` (accepted if newer revision or same revision+same text), `submit` (if send enabled), `thinking {enabled}`, `internet {enabled}`, `microphone`, `files {files:[{name, bytes}], overflow}`, `remove {id}`, `attachment-error`; always acknowledged with `api.acknowledgeAvatarComposer({id, accepted})`. Main sanitizes (`main/avatar-composer-bridge.mjs:176`).
#### UI-33 Clip result, computer-control strip — P1
- `screen.clip-saved {screenshot:{id,name}}` → shutter sound, card "Screenshot saved" with Open (`openScreenshot(id)`), Folder (`openScreenshotsFolder()`), × (errors "The screenshot could not be opened." / "The screenshot folder could not be opened.").
- `computer.control {active}` → danger button "Stop computer control (Esc)" → `stopComputerControl()`. `computer.task {active, phase}` → live status text: call-focus "Switch to the meeting tab", observing "Observing the current window", planning "Thinking", acting "Performing the action", verifying "Checking the result", completed "Ready", stopped "Stopped", else "Computer control".
### 2.B Settings window
#### UI-40 Settings window lifecycle and placement — P0
`main/settings-window.mjs:1-529`, `main.mjs:4401-4416, 6645-6668`.
- One lazily created, reusable window (drafts survive hide). Frameless, `skipTaskbar`, not minimizable/maximizable/fullscreenable, min 400×400, background `#07131c`, always-on-top mirrors the companion, title "Capri Settings" (localized at runtime).
- `open(section|null, focus)`: refused while quitting or in focus mode (main returns false). Opening also skips the startup intro. `section` normalised by `settingsSection()`; `model-context` → section `models` + focus `context`; unknown → `general`; `null` → resume last location.
- Docked bounds `settingsBounds(owner, workArea)`: `width = min(680, area.w − 24)`, `height = min(max(400, owner.h), area.h − 24)`; x = left of the companion (`owner.x − width − 12`), or right (`owner.x + owner.w + 12`) if that would leave the work area; clamp x to `[area.x+12, area.right − width − 12]`, y = clamp(`owner.y`, `area.y+12`, `area.bottom − height − 12`). Follows companion move/resize while docked; a manual move/resize (> 1 px from the docked bounds) undocks it; display add/remove/metric change forces a re-dock.
- Hidden whenever the companion hides/minimizes; shown again only on explicit request. Native close (WM ×, Alt+F4) is intercepted after load and converted into `settings.close-request` (renderer `close()` flow, UI-44).
- Presentation gate: show only when the first frame is painted AND (loading shell ready OR (forms ready AND content rendered)) AND still requested. Windows-only compositor workaround (6 attempts, `capturePage` probe, 2.5 s timeout, back-off `min(attempt·60, 240)` ms, opacity 1/255 click-through pre-show) is not needed on Linux; replace with "present after the first rendered frame".
- Events to the settings renderer are queued until it signals ready; the queue keeps only the latest event per `type` (max 50 types).
- Renderer crash → destroy window, log, companion notice "Settings closed unexpectedly. Open Settings to try again.". Unresponsive/console errors are logged to renderer diagnostics.
- Visibility: emits `settings.visibility {visible}` (credits animation and developer live refresh pause when hidden). Busy flag: `onBusy(visible)` marks the interface busy (suppresses initiative/avatar reactions); on hide: lock private memory and clear any live preview (`updateSettingsPreview({})`).
#### UI-41 Registry and navigation — P0
`settings-registry.mjs:1-83`, `settings-app.mjs:1193-1257, 1279-1396`.
- Groups (heading = labels joined by " · ", 14 px SVG icon, `viewBox 0 0 20 20`, path in source) and sections `[id, label, panel]`:
| Group (labels) | Section id | Label | Panel element |
|---|---|---|---|
| capri ("Capri") | general | General | `general-panel` |
| | languages | Languages | `language-panel` |
| | appearance | Appearance and animations | `companion-settings` (groups) |
| | window | Window | `companion-settings` (Window motion + dimming) |
| conversation ("Conversation", "Voice") | dialogue | Conversation and personality | `companion-settings` |
| | knowledge | Brain and private memory | `knowledge-panel` |
| | initiative | Initiative | `initiative-panel` |
| | microphone | Microphone settings | `speech-panel` (+ Wake acknowledgement group) |
| | voice | Voice effects | `voice-effects-panel` |
| | calls | Voice calls | `call-audio-panel` |
| | music | Music listening | `music-listening-panel` |
| models ("Language model") | models | Language model | `models-panel` |
| | api | API connections | `inference-panel` |
| capabilities ("Capabilities") | computer | Computer control | `computer-access-panel` |
| | workflows | Task training | `workflows-panel` |
| | user-tools | User tools | `user-tools-panel` |
| | screen | Screen snapshot | `screen-panel` |
| | applications | Application access | `applications-panel` |
| | files | File access | `file-access-panel` |
| | time | Timers and reminders | `time-panel` |
| community ("Updates", "Community") | updates | Updates | `updates-panel` |
| | discord | Discord presence | `discord-panel` |
| | bug | Report a bug | `companion-settings` (bug tab) |
| | support | Support the author | `companion-settings` (support tab) |
| | credits | Credits | `credits-panel` |
| development ("Developer") | developer | For developers | `developer-panel` |
- Aliases: `PANEL_SECTIONS[panel] = section` plus `companion-settings→appearance`, `speech-panel→microphone`, `file-access-panel→files`, `dimming-panel→window`; `settingsSection('memory')='dialogue'`, `'dimming'|'motion'→'window'`.
- Navigation buttons: `aria-current=page` for the current section (bg `#19363b`, 3 px inline-start border `#edeb73`, text `#f3f2a4`).
- `navigate(id, focus?, match?)` (ignored while another navigation, draft apply or reset runs, or for unknown ids): remember location → show loading skeleton → leave developer live refresh (unless developer) → stop voice-model preview when leaving models → reset "close requested" and notice → close help popup, saved-memory viewer (unless dialogue) → hide all panels, show target → for companion-settings sections show only the groups mapped to the section (see UI-53..55) and set the panel title (`Wake acknowledgement` for microphone) → per-section loaders (microphone devices, voice effects, models, API status, brain, workflows, user tools, credits, developer, discord (refresh status only if its draft is dirty), updates, applications, computer access/task/appearance, languages, time refresh, file recovery list, screen state, call audio state, music) → capture baselines, sync draft bar, queue preview → rebuild panel frames, apply language, render navigation → wait for fonts + 1 frame → hide skeleton, restore scroll → reveal search match or focus the models context select. First successful paint after a navigation calls `api.settingsRendered()` (after fonts + 2 frames).
- Bootstrap: build forms (clone `index.html` panels, General panel, all JS panels), install help buttons, build search index, `raw.onEvent`, `show(await bootstrap())`, load personality, set baselines (except microphone device, discord, computer appearance which are captured on first visit), `api.settingsReady()`.
#### UI-42 Settings location persistence — P2
`settings-location.mjs:1-46`. Stores only `{schemaVersion:1, section, scrolls:{[section]: px}, navigation: px}` (≤ 8192 chars; offsets finite 0…1e7; unknown sections ignored). Remembered 120 ms after scrolling stops, on navigation, before unload and when the document hides; not while busy or after close (suspended until resume). Corrupt/unavailable storage never blocks opening; default section `general`.
#### UI-43 Settings search — P1
`settings-search.mjs:1-88`, `settings-app.mjs:1193-1278, 1712-1724`.
- Index built once at startup from the English DOM (before data populates). One entry per section (name = section label) and one per control (`input:not([type=hidden]), select, textarea, button, summary, h3, h4`) not inside `.settings-heading`, `[aria-hidden=true]` or info buttons. Name = label text (field) or own text (others), stripped of `svg, output, .beta-badge, [aria-hidden]`, whitespace-collapsed; fallbacks `aria-labelledby` text → `aria-label` → `placeholder`. Descriptions = `aria-describedby` texts, the following `.settings-help` sibling (not `role=status`), the help-row info copy, `title`, and `<option>` texts. Nearest preceding `h3/h4` recorded as heading.
- Folding: `NFKC → toLocaleLowerCase(uiLanguage) → collapse whitespace → 'ё'→'е'`.
- Ranking: 0 = translated or English name equals query; 1 = name contains query; 2 = every query word appears in names or (English or translated) descriptions; section-only entries get +3 and are dropped when that section has any control match. Stable sort by rank.
- UI: while the query is non-empty the navigation is replaced by results (button: translated name + small section label); empty → "No matching settings". Enter activates the first result; Esc clears. Choosing a result navigates, opens the API form if the target is inside it, opens enclosing `<details>`, scrolls the label/target/heading into view (centre), highlights it (1.2 s fade from `#8ef5ed33`; outline under reduced motion) and focuses the target (or the anchor with `tabindex=-1`).
#### UI-44 Drafts, close flow, save/discard — P0
`settings-api.mjs`, `settings-app.mjs:83-116, 262-420, 860-1000, 1690-1724`.
- Every section form is a **draft**: changes preview live (UI-45) and are not persisted until "Save changes". Per-panel Apply buttons are hidden in the Settings window (`companion-save`, `personality-save`, `speech-apply`, `language-apply`, `initiative-apply`, `discord-save`). Switching sections keeps drafts without prompting.
- Draft registry entries `{section, panel, read(), apply(), discard(), preview()}`; `baseline = read()` captured on show/refresh/first visit; dirty ⇔ `read() !== baseline`.
| Draft id (panel) | Section | read() | apply() | preview key |
|---|---|---|---|---|
| general-on-top | general | switch state | `windowAction('always-on-top', v)` | `alwaysOnTop` |
| general-portrait | general | switch state | `windowAction('portrait', v)` | `portrait` |
| companion-settings | appearance | JSON(readSettings()) | `companion.save(false)` → `setCompanionSettings` | `companion` |
| avatar-layout | appearance | portrait zoom slider (%) | `setAvatarLayout({...layout, zoom: v/100})` | `zoom` |
| dimming-panel | window | JSON(dimming draft) | `setDimming` | `dimming` |
| personality-text | dialogue | textarea | `savePersonality` | `personality` |
| communication-style | dialogue | select | `setCommunicationStyle` | `style` |
| speech-panel | microphone | pause slider | `setSpeechSettings` | `speechPause` |
| microphone-device | microphone | device select | `setMicrophoneDevice(id)` | `microphone` |
| language-panel | languages | JSON(draft) | `language.apply()` (may prompt to install voice) | `interface` + `languages` |
| initiative-panel | initiative | JSON(draft) | `setInitiative` | `initiative` |
| voice-effects-panel | voice | JSON(settings) | `effects.commit()` | `voiceEffects` |
| music-listening-panel | music | JSON(draft) | `music.save()` | `musicListening` |
| computer-access-panel | computer | JSON(appearance draft) | `setComputerAppearance` | `computerAppearance` |
| discord-panel | discord | all input values | `setDiscordPresence` | — |
| updates-panel | updates | experimental checkbox | `setUpdateSettings` | — |
| screen-panel | screen | `[interval, duration]` | validate (15–300 s, 0.5–120 min) → `setScreenSettings({intervalMs, durationMs})` then screen state refresh; invalid → notice "Enter a valid screen observation interval and duration." and abort | — |
- Revisioned writes (optimistic concurrency): `setCompanionSettings`, `setLanguages`, `setSpeechSettings`, `setInitiative` send `{payload, expectedRevision}`; main compares `sha256(JSON(current snapshot))` and rejects with "Settings changed elsewhere. Apply or discard your draft."; success returns `{settings, revision}`. Writes on the same channel are serialized. All draft writes are tracked so close/confirmations wait for them.
- Close state machine:
- `close()` (×, Esc, WM close request): ignored while applying/resetting or a dialog is open; await pending writes; set `closeRequested=true`; if nothing is dirty → `finishClose()`; else show header buttons **Keep editing / Discard changes / Save changes** and focus Save.
- Any input/change/click inside a panel sets `closeRequested=false` (bar disappears) and re-queues the preview.
- Keep editing → `closeRequested=false`, focus close.
- Save changes → for each dirty draft in registry order `apply()`; stop at the first returning `false`/throwing (notice the error, navigate to that section). On success the window **stays open** (focus close; re-preview).
- Discard changes → `discard()` each, then reload revisions (`settingsVersions()`), clear deferred external updates, and close.
- During apply: forms inert, header buttons disabled.
- `finishClose()`: stop developer refresh, remember location (then suspend), clear API key field, close saved memories, stop voice preview, await preview queue, `api.closeSettings()`.
#### UI-45 Live preview contract — P1
`settings-app.mjs:306-336`, `main.mjs:3203-3285`. Preview payload = merge of `preview()` of all dirty drafts, debounced 55 ms, deduplicated by JSON, serialized (one in flight). Main validates each key (unknown key → error), refuses (returns `false`) when the Settings window is not requested, stores it as the live overlay and re-emits affected state with `preview:true`: `companion.settings` (merged live companion settings, e.g. theme, motion, glitch), `dimming`, `avatar.layout` (zoom), `settings.set-portrait`, always-on-top layer sync, `voice.effects`, `languages` (interface only), computer border appearance, initiative re-sync, microphone device change (stops capture if running), speech pause. The settings renderer ignores events with `preview:true`. Clearing the preview (`{}`) restores persisted state; happens on hide.
#### UI-46 External-change reconciliation — P1
`settings-app.mjs:1468-1690`. For state events (`companion.settings`, `voice.effects`, `file-access`, `applications`, `initiative.settings/status`, `speech.settings`, `models.status`, `updates.status`, `spotify.settings`, `languages`, `dimming`, `avatar.layout`, window toggles, music): if the panel has no dirty draft → update the form, recapture the baseline, update the revision; if dirty → keep the draft, remember the incoming value in `deferred[panel]` (used on discard), notice "Settings changed elsewhere. Apply or discard your draft." (unless own writes are pending or a reset runs). The language draft also live-applies its interface language to the Settings window itself.
#### UI-47 Reset settings to defaults — P1
`settings-app.mjs:657-683, 1398-1430`, `main.mjs:4422-4551`. Danger button → main confirmation "Reset settings to defaults?" (danger, `delayMs: 3000`, cancelled if Settings hides/crashes). Resets (transactionally, rolling back already written files on failure with "Could not reset settings. Check that Capri can save its preferences and try again."): companion settings, inference startup, voice effects, speech pause, initiative, screen observation options, computer-control appearance, music listening, always-on-top=true, portrait pinned=false, dimming defaults, avatar zoom default (position kept). Conversations, memory, models, connections, permissions are kept. Stops music listening, emits all state events (`companion.settings` with `reset:true`). Renderer applies all panels, clears deferred, recaptures baselines, notice "Default settings restored.".
#### UI-48 Long-help "i" buttons — P2
`settings-app.mjs:1053-1192`, `main/settings-window.mjs:18-44, 131-247`, `settings-help.{html,mjs,css}`.
- Every `.settings-help` paragraph in a panel (and `#call-audio-panel .settings-card > p:not([id])`) longer than 130 characters and without `role` or `data-inline-help` is moved behind an 18 px round italic "i" button (`aria-label` "More information", `aria-expanded`, `aria-controls`) appended to its anchor (explicit `data-help-for`, else previous `label|h2|h3`, a `summary`'s following label, a previous control's label, or the parent's previous heading). Paragraphs sharing an anchor are grouped.
- Toggle: request a native popup `settingsHelp({title ≤160, text ≤2000 (paragraphs joined by blank lines), y (anchor centre in window coords), palette {--cyan, --theme-panel, --theme-border, --theme-text}})`; if refused → inline fallback (collapsible block `min(100%, 22rem)`, 170 ms grid-row animation). Closes on outside pointerdown, wheel (native only), Esc, navigation, reset, settings move/resize/hide (`settings.help-closed`).
- Native popup placement `settingsHelpBounds`: try right then left of the Settings window, gap 10, width `min(344, available)` ≥ 210, inside a work area containing the anchor y, at most 96 px away from the edge; height `min(requested, area.h − 20)`; y = clamp(anchorY − 14); the popup measures itself (`height + 12`, must be 1–800) and is hidden if it doesn't fit. Window: frameless, transparent, non-focusable, click-through, child of Settings; colours validated against `^(#hex|rgb(a)/hsl(a)(...))$`. Fade 145 ms + 8 px slide.
- Linux recommendation: implement the inline fallback as the only mode (§8).
#### UI-49 Loading skeleton — P2
`settings.html:31-74`, `settings-loading.mjs`, `settings.css:10-120`. Shell paints immediately: header, close button (works during loading → `closeSettings()`), skeleton nav/content (bars `color-mix(cyan 11%, theme-panel)`, radius 3, sweep gradient 1.6 s). `settingsLoading()` lets main show the shell before data. Per-navigation skeleton covers the form area (`data-panel-loading`, `aria-busy`).
#### UI-50 Settings notice toast — P1
`settings-app.mjs:83-89`. Fixed below the header (`top 58px`, inline 185 px…12 px), border `#f4d976`, bg `#263234`, text `#fff1b5`, `pre-wrap`; Electron prefix stripped; translated; auto-hides after 10 s; cleared on section change.
### 2.C Settings sections (one feature per section; every control is listed in §4)
#### UI-51 General — P0
`settings-app.mjs:131-198, 637-706`. Status line (backend message). Groups: Window controls (Hide to tray, Reset Capri position and zoom, Reset to bottom-right corner, switches Always on top / Keep portrait open (drafts), Focus mode (immediate)), Voice and microphone (switches Voice, Microphone — immediate), Connection, sleep and quit (Reconnect, Sleep (confirm "Unload models and sleep?"), Quit and unload models (danger; 4-choice confirm)), Settings reset (UI-47). Switches are `role=switch` buttons with `aria-checked/aria-pressed` and a 31×17 track. Immediate switches disable themselves during the call. Events `window.focus-mode`, `window.always-on-top`, `window.portrait`, `microphone.settings`, `voice.settings` update them.
#### UI-52 Languages — P0
`index.html:595-667`, `language-panel.mjs:1-347`, `language-settings.mjs:1-100`.
- Controls: Interface language (50 locales by native name), Conversation language (100 catalog languages as "<localized name>[ / text only]" + "Other language / text only"), Language name (custom, ≤ 60, letters/marks/space/`()'-` only), Spoken voice ("Automatic — <language> / <Capri English|multilingual Capri|text only>[ / Not installed]" or "Text replies only"), Speech recognition (Automatic · <language> / Parakeet|Whisper; Auto-detect / Whisper; Fast auto / English, Russian and European languages; Microphone unavailable; each language "<name> / Parakeet|Whisper"), status/help lines, Install and enable, install progress card (stage labels, bytes progress, Cancel installation, Report a problem), download details.
- `validateLanguages` (§4.2) runs before save; the saved value maps `autoDetect = recognition==='auto'`.
- Apply semantics: interface-only change → save directly (no model/voice change). Otherwise refuse while installing; refresh speech availability; if the resolved spoken voice isn't installed → 3-choice dialog "Selected voice is not installed" (Stay here / Use text replies / Install and enable): install → `installSpeech({speech, recognition})` and save the draft automatically when installation reaches `ready` (then enable voice if speech≠off); text → save with `speech:'off'`.
- Leaving with unsaved changes in the legacy in-window flow asks "Unsaved language changes" (Stay here / Discard changes / Apply and leave); in the Settings window the generic draft bar is used.
- Install progress labels: checking "Checking speech components…", python "Preparing speech installer…", recognition "Installing recognition and its models…", voice-pack "Preparing Capri’s included voice…", voice-runtime "Installing voice dependencies…", voice-models "Downloading multilingual voice…", verify "Checking voice files…"; per-file transfer "Connecting"/"Reconnecting"/"Downloading voice model…"; results ready/cancelled/interrupted/error texts (§6). Controls disabled during installation; installation also blocks Send (UI-05).
#### UI-53 Appearance and animations — P1
`companion-panel.mjs:64-209`, `settings-app.mjs:398-450`. The companion settings form is split by its `h3` headings into groups; this section shows: Interface theme (UI-80), Button press feedback, System resource usage, Portrait (portrait zoom 60–300 %, expand on reply), Desktop presentation (restore chip, out-of-frame style, auto-hide replies + delay), Visual glitch (+ Preview glitch → `glitchPreview(draft)` broadcasting `settings.glitch` to both windows for 850 ms), Teleport effects, Drag lightning, Avatar attachment zones (with an SVG illustration whose band width = radius·0.2), Avatar click reactions. Dependent enabling: glitch sliders/preview disabled when glitches off; drag-lightning sliders disabled when the tether is off; chart style disabled unless RAM/VRAM shown; interval disabled unless RAM/VRAM or graphs shown. Groups "Qwen model" and "Updates" (legacy shortcuts) are never shown in the Settings window.
#### UI-54 Window — P2
Window motion group (motion preview box with animated card, Enable floating motion, Motion amplitude 0–24 px, Motion cycle 4–30 s) + "Window dimming" (Dim the area behind Capri, Strength 0–85 %, Soft edges 0–320 px step 5). In the companion, dimming draws `#window-shade` at opacity `level/100` (0 when disabled) with a soft-edge mask of `softness` px; 180 ms opacity transition.
#### UI-55 Conversation and personality — P1
`companion-panel.mjs:188-208, 414-469, 604-655`, `saved-memory-panel.mjs`, `main/companion-ipc.mjs:47-62`.
- Conversation: Communication style (neutral/romantic/business/wild), follow-up listening checkbox + seconds (5–30).
- Personality: textarea (≤ 24 000 chars, `dir=auto`, monospace 13 px) showing the full effective character text; "Show Personality file" (creates the file if missing, reveals it in the file manager; reloads if not dirty); "Restore original character" (danger confirm "Restore original character?" → save empty → file rewritten with the factory text). Saving requires the chat engine idle (`assertIdle`). The panel reloads the personality when the window regains focus if neither text nor style are dirty (external editor support).
- Memory controls: "View saved memories" toggles the saved-memory viewer; "Clear conversation" and "Clear long-term memory" (danger) — main confirms ("Start a new conversation?" / "Delete saved notes about you?").
- Saved-memory viewer: heading + Refresh, help, "Add a memory" (≤ 1200, placeholder "A fact you want Capri to remember…", Save memory → `saveMemory(text)` must return `{saved:true}` else "The memory could not be verified."; receipt "Memory saved and verified."), search (≤ 200; NFKC + locale lowercase; all words must match text+source), list of `{text, source, date YYYY-MM-DD}` rendered as plain text (date formatted `dateStyle: medium`, UTC noon), statuses: "Loading saved memories…", "Saved memories could not be loaded. Try again.", "Memory files are unavailable.", "No saved memories yet.", "No matching memories.", "{shown} of {total} memories", "{count} saved memories", partial flag "Showing a limited list. Some notes could not be displayed.". Generation counter discards late loads; closes and wipes on hide/navigation.
#### UI-56 Brain and private memory — P2
`knowledge-panel.mjs`, `private-memory-panel.mjs`.
- Brain: help, "Use local knowledge" and "Allow relevant Brain excerpts to be sent to an external API" (immediate `brainAction({action:'configure', enabled, shareWithApi})`), Open Brain folder, Refresh index, status "Indexing documents…"/"Documents indexed: n · Skipped: m", test search (≤ 500) → result cards `source · page` + content or "No matching knowledge found.".
- Private memory: password (8–256, never kept in the field after use), Unlock / "Create private memory", Lock now, status ("Private memory is unlocked. It locks after five minutes of inactivity." / "Private memory is locked."); when unlocked: private note (≤ 1200) + Save, notes list with Remove, private conversation (allow external API checkbox, message ≤ 2000, Send privately; shows "Thinking" then the reply text only while unlocked), change password (current + new). All private fields wiped (and checkbox unchecked) when the document hides; main locks on Settings hide.
#### UI-57 Initiative — P2
`index.html:776-861`, `initiative-panel.mjs`. Controls per §4; changing level clears the hourly limit, sets its placeholder (10 for occasional, 30 otherwise) and disables it for `off`; quiet-hour inputs disabled when quiet hours are off. Buttons: Try initiative (`testInitiative`), Less of that kind of comment (`dismissInitiative`), Restore dismissed comment types. Status: "App awareness active. No screen images or window contents are captured." / "App awareness stopped. Apply settings to try again." / "App awareness is off."; scheduling detail "Initiative status: <reason with _→space> · Next attempt: HH:MM".
#### UI-58 Microphone settings — P1
Device card (prepended to the speech panel): "Microphone input" select (System default + devices + disabled "Unavailable — {device}" for a missing saved device), Refresh devices; pause slider (speech panel; 0.5–5 s step 0.1, "{value} s" with one decimal, "Reset to 1 s"); Wake acknowledgement group (restore from tray on wake, sound tone/file/voice/off, voice phrase (only for voice), volume 0–1 step .05, Choose audio file, Prepare voice response). Device list refreshes on `microphone.device-changed` while this section is shown.
#### UI-59 Voice effects (hosted) — P2
`index.html:519-556`, `voice-effects-panel.mjs`. Enable effects, Preset (clean/cybernetic/radio/synthetic/holographic/custom), sliders (moving any slider switches to custom), Preview voice (disabled while a reply/playback is active or voice is off; preview never enters history), Reset to clean.
#### UI-60 Voice calls (hosted) — P2
`settings.html:76-216`, `settings-app.mjs:520-656`. Virtual-microphone setup card (phases idle/checking/missing/downloading/connecting/installing/reboot/ready/error), VB-CABLE consent, share replies, call voice volume (0–100, debounced 50 ms saves), allow model routing, advanced manual cable selection, system-audio inclusion. Windows-only; on Linux replaced by the voice spec (PipeWire virtual source). Listed for completeness.
#### UI-61 Music listening (hosted) — P2
Start/Stop music listening (explicit click only), status label, Music animations / Floating notes / Move to the music / auto BPM (drafts).
#### UI-62 Language model — P1
`models-panel.mjs`, `model-device-panel.mjs`, `huggingface-panel.mjs`.
- Current model (or "API connections" when remote), model select (optgroup "Recommended for {language}" with up to N supported non-HF picks for the conversation language, then the rest; option text "Family · TAG · ≈ x.xx GB · BETA · Downloaded"; unsupported models remain selectable with tooltip "This model needs more system RAM."), primary "Use local model" (prepare if needed then apply; restart confirmation in main), details (description by tier id minimal/balanced/desktop/quality, size "Approximate download: {size}"/"Model files: {size}", RAM/VRAM requirement, install state, "Recommended for the detected hardware."), progress card (phases idle/checking/downloading/preparing/ready/applying/error; GB transfer "x.xx / y.yy GB"), buttons Refresh models, Open models folder (ollama or huggingface store), Download and prepare / Prepare model, Cancel download, Switch model and restart; Context window card (choices `NK`, "Active context: {size}", Apply and restart; disabled when unchanged or busy).
- Model devices card: Language model device / Voice model device selects (Automatic, CPU, GPU name · BACKEND · Unavailable), reasons, Refresh devices, Save and restart Capri (enabled only if both selections available and changed).
- Hugging Face card: search (≤ 160, task llm "Language models · GGUF" / tts "Voice models"), results (repository buttons), details (license or "License not specified", revision, GGUF file + optional projector selects, compatibility note, Check download size → plan "Download / Required free space / Free space / RAM (CPU) ≈ … GiB · VRAM ≈ … GiB", Download and prepare enabled only for a valid plan with enough disk and matching projector), progress, Cancel, installed list (Repair model / Remove (confirm)), token (password ≤ 512, Save token / Remove token, "Token saved securely"/"No token saved").
- Voice models card (voice spec).
#### UI-63 API connections — P1
`inference-panel.mjs:47-581`, `api-key.mjs`, `inference-endpoint.mjs`.
- Disclosure (§6), "Skip local language model when using an API" (immediate `setInferenceStartup({skipLocalModelOnApi})`, then "Applies on next startup or reconnect."), current model (`model · provider` or "OFFLINE" or `local · Local`), "Test all connections" (2 concurrent workers), connection cards (active first; name or provider host; detail; encrypted key indicator; health "Not tested"/"Testing connection…"/"Connection works · x.x s"/"Unavailable · <error>"/"No API key is saved."; buttons Test connection, Use connection (disabled if active or no key), Edit, Remove (danger; disabled if active; main confirms)).
- Add/Edit form (toggle with "Add an API connection"): setup guide, Connection name (≤ 64), API provider presets (OpenRouter `https://openrouter.ai/api/v1`, Hugging Face `https://router.huggingface.co/v1`, ProxyAPI `https://api.proxyapi.ru/v1`, DeepSeek `https://api.deepseek.com`, Google Gemini `https://generativelanguage.googleapis.com/v1beta/openai`, Lemonade (local) `http://127.0.0.1:13305/api/v1`, Custom), base URL (≤ 512), model id (≤ 128; Lemonade preset fills `Phi-4-mini-instruct-NPU`), API key (password, ≤ 4096), tools / vision checkboxes, provider context limit (min 32 768 remote / 8 192 local, max 262 144, step 1024).
- Key handling: paste is intercepted and validated as a whole (no silent cropping); normalization strips outer whitespace/ZW chars and one pair of outer double quotes; valid = 8–4096 printable ASCII without `"` or `\`. Editing an existing profile may leave the key empty to keep it only if the URL origin is unchanged ("Enter a new API key when changing the provider address."). Local endpoints (`http://localhost|127.0.0.1|[::1]`) may omit the key; Lemonade NPU models normalise the base path to `/api/v1` and force tools/vision off (Phi text-only). Save disabled if secure storage is unavailable and a key must be stored. The key field is cleared on cancel, save, navigation away and window close.
#### UI-64 Computer control — P2
`applications-panel.mjs:72-140`, `computer-appearance-panel.mjs`. Full computer access (Give/Revoke full computer access; danger style when enabled; disabled while application access is paused or enabling; status "Application access is paused." / "Full computer access is enabled." / "Individual application and folder grants are in use."), task card (goal ≤ 8000, Test → `runComputerTask(text)`; status per phase; Stop computer control (Esc)), Control effects (enable edge effects, style capri/blackwall, intensity 0–100 %, Capri cursor and trail, pointer movement duration 0–1000 ms step 20, Preview effects for 3 seconds).
#### UI-65 Task training (workflows) — P2
`workflows-panel.mjs`. Start recording / Stop, status "Recording — press Esc to stop" / "Playing — press Esc to stop" / "Ready" + count, workflow name (≤ 80), step list (index, localized action label Click/Drag/Keyboard shortcut/Scroll/Type text, target label or keys or amount; text steps editable ≤ 2000; ↑/↓/× reorder/remove), "Add text after the last input-field click" (requires a recorded click on a `ControlType.Edit` target; adds `{...click, action:'text', text:'{{text}}', delayMs:100}`), Save workflow, advanced JSON step editor, saved workflows (Edit, Run workflow with variables JSON object, Remove).
#### UI-66 User tools — P2
`user-tools-panel.mjs`. Folder/refresh/example/stop buttons, "Available user tools: n", per-tool card (name, description, `runtime · mode · Network allowed|blocked · Selected input files only|No owner files · timeout ms`), enable toggle ("I reviewed this tool — enable" / "Review changed code and enable" / "Disable tool"), private settings JSON (password field ≤ 8000, "Encrypt tool settings"), Choose input files, Test parameters JSON + Test tool (output pretty JSON). Password fields and outputs wiped when hidden.
#### UI-67 Screen snapshot (hosted) — P2
Source select, Refresh sources, Capture once, previews, question (≤ 8000), Ask Capri, Start/Stop observation, lock notice "Stop observation before changing its interval or duration." + Stop, interval (15–300 s) and duration (0.5–120 min) drafts, privacy help replaced by the API disclosure when the inference source is remote (`inference-privacy.mjs`). Commands go through `screenFormCommand({action: refresh|capture|ask|start|stop|select|state, sourceId, interval, duration, question})` executed by the companion renderer (capture is not allowed from Settings).
#### UI-68 Application access — P2
`index.html:705-775`, `applications-panel.mjs`. Prepends: "Computer control" shortcut, Application access pause card ("Pause application access"/"Enable application access"), Find installed applications (query ≤ 80, Enter = Search; results with "Allow launch"; empty "No matching applications found. You can choose an executable manually."). Built-in Notepad and Calculator grants (immediate; inputs disabled during save; failure "Application permissions could not be saved."), Custom applications BETA (Add application; per app Allow launch / Allow accessible field inspection / Allow confirmed text entry (requires inspect; package apps launch-only); Remove), Action journal (Refresh → pretty JSON), Spotify BETA (Enable/Disable (main confirm + restart), Repair, Check connection; statuses §6).
#### UI-69 File access — P1
`index.html:668-704`, `file-access-panel.mjs`, `main/access-ipc.mjs`. Help, empty state "No folders are shared with Capri.", warning line, scope cards (label, path, "Allow file changes" checkbox (immediate), "Revoke folder access" danger), "Choose a folder…" (native folder dialog titled "Choose a folder Capri may read"; failure "This folder cannot be added. Choose a personal folder outside system and Capri application data."), "Revoke all access", capabilities help, File recovery (Refresh; per item Restore / Delete permanently (both confirmed by main); "No recovery copies.").
#### UI-70 Timers and reminders — P1
`index.html:971-1000`, `time-panel.mjs`. Reminders group (Wake Capri and prepare her voice for reminders) on top; Type (Reminder/Timer/Stopwatch), title (≤ 1000), duration dials Hours (0–8784) / Minutes (0–59) / Seconds (0–59) with ▲/▼ buttons, wheel and blur normalization (max 366 days; default 00:05:00; disabled for stopwatch), Start → `timeAction({action, title, seconds?})`; list refreshed every 1 s while visible: up to 100 non-cancelled/acknowledged objects: title or kind label, state "Due now"/"Paused"/"Running" · `HH:MM:SS` (elapsed for stopwatch, remaining otherwise) · reminder due date (short date+time), buttons Show on companion (stopwatch), Speak reminder (due), Pause/Resume (non-reminder running/paused), Snooze 5 minutes (due, non-stopwatch), Dismiss; empty "No active timers or reminders.".
#### UI-71 Updates — P2
`updates-panel.mjs`. Installed version, "Include experimental updates" (draft), status card (phases idle/checking/available/current/downloading/verifying/ready/installing/error; release tag; progress MB + MB/s; error), Check for updates / Download update / Cancel download / Restart and update ("Open installer" for non-managed or full-installer mode; main confirms), mode help texts, GitHub access card (status, token password ≤ 255 placeholder `ghp_… / github_pat_…`, Save and check access, Remove saved access, Create read-only token instructions, classic token link hidden).
#### UI-72 Discord presence — P2
`discord-panel.mjs`. Open Discord Developer Portal, steps, Application ID (digits, 17–22, ≤ 22 input), Show Capri in my Discord activity, Refresh status, optional asset key (≤ 64 `[A-Za-z0-9_-]`); status off/setup-required/connecting/connected/waiting/unavailable (§6). Linux: Discord IPC socket `$XDG_RUNTIME_DIR/discord-ipc-0` (other spec).
#### UI-73 Report a bug — P1
`companion-panel.mjs:77-89, 470-485`, `main/companion-ipc.mjs:160-201`. Problem area (voice, recognition, model, startup, interface, installer, other), Short title ≤ 160, What went wrong? ≤ 4000, Steps ≤ 3000, Expected ≤ 1500, Actual ≤ 1500, Include recent diagnostic logs (default on), privacy help, Save report → save dialog "Save and review bug report" default `capri-diagnostics-<ISO timestamp with : and . → ->.zip`, written via temp file + rename, revealed in the file manager; result "Collecting diagnostics…" → "Report saved. Review it before sharing."; single-flight ("A diagnostic report is already being collected."). "Open GitHub issues" opens the fixed issues URL.
#### UI-74 Support the author — P2
Animated heart/orbit art (4 s heartbeat, 26 s orbit, 5 s sparks; disabled under reduced motion), "Help Capri grow", "Developed by Overyx", text, link buttons Boosty (gold shimmer icon), Discord, TikTok, GitHub, capri-core.com; payment note. Buttons send only an identifier (`communityLink(id)`); main maps ids to fixed HTTPS URLs (`community-links.mjs`).
#### UI-75 Credits / Hall of Fame — P2
`credits-panel.mjs`, `credits.css`, `config/hall-of-fame.json`. Hero, "The team" (3 fixed members with role labels and epithets; validated against the registry), Major supporters / Community helpers (reserved placeholders until data), Early access supporters (count, search ≤ 39 by nickname or epithet, "No matching nicknames."). Registry validation: `schemaVersion 1`, team exactly the 3 fixed `{name, role}`, supporters ≤ 50 000 GitHub-login-shaped names (dedupe case-insensitively), names ≤ 80 chars, epithets "Adjective Noun" from fixed word lists, unique, complete. Load failure → "The supporter list could not be loaded." + Try again. Per-name stable hash (FNV-1a) picks one of 6 tones and drift timings; animations pause when hidden/off-screen/scrolling; `forced-colors` support.
#### UI-76 For developers — P2
`developer-panel.mjs`. Refresh, Open logs folder, Live refresh (3 s while visible), status "Updated {time}", Response timing (recent requests select: time · status · model; metrics First reply text / Full reply / First interface paint / Model calls; pipeline stage bars; model call details (load, prompt eval, generation, first token/text, token counts, tokens/s); all timing events table), Logs (select "Runtime|Updates|Installer · name", tail ≤ 64 KB, JSON lines pretty-printed, keeps scroll-to-bottom). Shows technical counters only.
### 2.D Theming, localization, accessibility
#### UI-80 Interface theme presets and custom colours — P1
`interface-theme.mjs:1-70`, `companion-panel.mjs:220-250`.
- Setting `interfaceTheme = {preset, hue, saturation, backgroundHue, backgroundSaturation}`; defaults `capri, 174, 84, 174, 40`. Validation: only these keys; preset ∈ `capri|blackwall|amethyst|overdrive|custom`; integers hue 0–359, saturation 35–100, backgroundHue 0–359, backgroundSaturation 0–100. Migration: missing `backgroundHue` → `hue`; missing `backgroundSaturation` → 40.
- Preset table `[accentHue, vividSat, highlightHue]`: capri `[174, 84, 344]`, blackwall `[346, 91, 284]`, amethyst `[264, 79, 190]`, overdrive `[46, 95, 338]`; custom = `[hue, saturation, hue]`.
- Derived colours (`interfaceThemeColors`):
| Token | Formula |
|---|---|
| `cyan` (accent) | capri → `#8ef5ed`; else `hsl(accent, vivid%, 76%)` |
| `pink` (glitch/highlight) | capri → `#ff3c68`; else `hsl(highlight, (custom ? vivid : 88)%, 61%)` |
| surface hue/sat | custom → `(backgroundHue, backgroundSaturation)`; else `(accent, 40)` |
| `theme-panel` | `hsl(surfaceHue, min(100, round(surfaceSat·1.1))%, 13%)` |
| `theme-background` | `hsl(surfaceHue, surfaceSat%, 8%)` |
| `theme-border` | `hsl(accent, round(vivid·0.42)%, 38%)` |
| `theme-text` | `hsl(accent, round(vivid·0.54)%, 92%)` |
- For every preset except `capri`, the `--ui-*` role tokens are derived (`cyberpunk.css:2-13`): `ui-accent=cyan`, `ui-glitch=pink`, `ui-surface=theme-background`, `ui-raised=theme-panel`, `ui-text=theme-text`, `ui-muted=mix(theme-text 73%, theme-background)`, `ui-line=theme-border`, `ui-grid=mix(cyan 12%, transparent)`, `ui-wash=mix(cyan 20%, theme-panel)`. Under `capri` they are **undefined** and every rule uses its literal fallback colour (§2.D UI-81 table) — the Capri look is a hand-tuned palette, not the formula.
- Custom editor: two fieldsets (Accent colour, Background colour) each with a hue wheel (conic gradient, pointer drag sets hue = `atan2(x, −y)` in degrees, ignore within 4 px of centre; selected-hue marker) plus Hue and Saturation sliders with live outputs (`174°`, `84%`). Changes preview instantly (settings window applies locally; companion via preview). Swatches next to "Color palette" show accent and background.
- Also applied to: attachment viewer, mini composer (theme colours passed as validated CSS colours), help popup palette.
#### UI-81 Design tokens (Capri preset) — P0 (visual identity)
Sources: `styles.css`, `cyberpunk.css`, `settings.css`, `thinking-mode.css`, `update-notification.css`, `attachment-viewer.css`, `settings-help.css`, `credits.css`. Later rules in `cyberpunk.css` override `styles.css`; values below are the effective ones.
Core palette:
| Token | Value | Use |
|---|---|---|
| `--cyan`/`--signal` | `#8ef5ed` | accent, frame colour, status dot, headings |
| `--pink` | `#ff3c68` | prompt mark, pink rails, glitch ghost, assistant label |
| `--acid` | `#f4ed75` | packet title, speaking frame, warnings, API "active", recommendations |
| `--ink` | `#080e15` | — |
| base text | `#f5f9fa`, 13 px | root |
| `--muted` | `#d5e4e7` | help text (`settings-help` 11 px/1.5) |
| `--update-accent` | `#8cf5ec` | updates |
| shadow | `0 1px 2px #000, 0 2px 7px #000, 0 0 2px #000` | toolbar text |
Surfaces:
| Element | Background | Border / frame |
|---|---|---|
| Reply frame | `linear-gradient(115deg, #111821ed, #070d13ef)`; inset glow `#8ef5ed05` 24 px | contour accent α .74; pink rail 3 px `#ff3167` + glow; cyan tail 27×16 at right-bottom |
| Composer | `linear-gradient(110deg, #142832f5, #09141bf5)` (focus: `#172b34fa→#0b1b25f5`) | contour α .83 (focus α 1, colour `#befff2`); pink rail 3 px left; cyan dash 32×3 top-right |
| Preferences panel / history / dimming | `#08141bf7` (`#0a141bf5`) | contour α .95, inset glow `#8ef5ed08` 40 px |
| Portrait frame | `radial(ellipse 50% 44%, #3b134145, transparent 73%) + linear(130deg, #09171ce8, #080b17d9)` | contour α .86; corners 22 px 4 px `--signal`; scanline overlay `#06101954` 1/3 px; vignette |
| Confirmation card | `#08171cfa`, backdrop `#020a10b8` blur 3 px | kicker `#f1ec86` monospace 10 px |
| Notice | `#101822f5` text `#ffe0e6` | `#ff5679` α .9 (warning acid, bg `#211e15f5`, text `#fff1bc`) |
| Action approval | `#091a21` | `#f5e955` |
| Time alert | `#0b2029` | `--cyan`, glow `#43d8d330` |
| Startup card | `#07151df5` text `#b4f5f5` | 2 px `#62d6dc`, glow `#13d5da25` |
| Inference picker | `#0b1c25`, radius 3 | 1 px accent, top 3 px; shadow `0 12px 28px #0009` |
| Settings window | body `#07131c`, text `#d7eeed`; header `#0b202b` 56 px, bottom 2 px `#5adcd1`; nav border `#296373` | — |
Controls:
| Control | Normal | Hover / active / focus |
|---|---|---|
| Generic button | bg `#102a33`, border 1 px `#5fcac5`, text `#c9f5ee`, radius 0, transitions 120 ms | hover brightness ×1.2; focus `inset 0 0 0 2px #d7fff4, 0 0 10px #64f3e477`; disabled α .32–.4 |
| Panel button hover/focus | bg `#1b414c`, border `#a7f4ec`, text `#e0fffa`, glow `0 0 11px #43d8d33d` | — |
| Danger button | text `#ffb4c4`, border `#ff4f78`, bg `#341421` | hover bg `#581c31` + `0 0 12px #ff37643d` |
| Toolbar button (26 px) | border `#3d8790`, bg `#071820dc`, text `#9ad9df`, icon 16 px stroke 1.35 | hover border `#a7f4ec` text `#d3fff5` bg `#12313b`; pressed/expanded border `#cfe96f` text `#ecf5a0` bg `#252d1e`; quit hover bg `#5b1d34` border `#ff6289` |
| Support button | border `#fc6ca383`, bg `#251425bd`, text `#ff86b6`, glow animation 3.8 s | outline `#ff9ec4` |
| Thinking/Internet toggles 28 px | accent text, border `#72d2da88` | on: text `#ffed52`, tinted bg 13 % |
| Text input | bg `#07111b`, border `#3b8391`, text `#eefaff`, padding 7 | focus outline 1 px cyan |
| Select | bg `#10242c`, text `#c7faf3`, border `#65d5cf`, padding 8 | — |
| Range | track 5 px, border `#397e88`, bg `#102c38`; thumb 12×15 `#92f5df`, border `#d6fff2`, glow `#65d5cf70` | disabled α .45 |
| Checkbox | `accent-color: --cyan` | — |
| General switch | track 31×17 r10 border `#627881` bg `#152632`, knob 11 px `#b0c0c5` | on: border cyan 68 %, bg cyan 23 %, knob cyan +14 px; 150 ms |
| Disabled input/select/textarea | α .45, grayscale, bg `#172128`, text `#91a0a5` | — |
| Settings nav item | text `#9bc6cd`, 12 px, padding 8, 3 px start border | hover bg `#15353e` text `#dafff6`; current `#19363b` / `#edeb73` / `#f3f2a4` |
| Draft bar | Save bg `#103c34` border `#6de1a8` text `#bdffdc`; Discard bg `#3e1a27` border `#f47a92` text `#ffb8c5` | appear 190/230 ms |
| Scrollbars | 9 px; thumb `#337c86` hover `#66e2d5`; track `#0b1b24` | — |
Status colours: pressure normal = accent, medium `#f4ed75`, high `#ff678b`, unknown `#879aa7`; resource warning border `#ff779f` bg `#351726` text `#ffdbe3`; API health available `#90f7a9`, unavailable `#ff8f9e`, testing `#90e1ef`, idle `#a9bac4`; graph inks GPU `mix(accent,#97b8ff)`, RAM `mix(accent,#e2df85)`, VRAM `mix(accent,#ff779f)`, unavailable `#8a9ba5`, warning `#ff90a6` on `#3d192a`; settings warning border `#e3d26b` bg `#8f812315` text `#e7dc9c`; models error `#ffa4b9`, unavailable `#ff8b94`; microphone live `#ffed52`; command listening `#aaffec`/`#8affdf`.
Signal states (portrait/core status label, `presence-model.mjs:2-17`): starting CONNECTING `#a295ff`, idle STANDBY, input TEXT INPUT, listening LISTENING, wake SAY CAPRI, online ONLINE (all `#8ef5ed`), thinking THINKING, replying RECEIVING, buffering VOICE PENDING (displayed "PREPARING VOICE"), speaking SPEAKING (all `#f4ed75`), offline OFFLINE and stopping DISCONNECTING (`#ff5679`), sleeping GOING TO SLEEP and asleep SLEEPING (`#a295ff`).
Typography: family `'Exo 2'` (variable, wght 100–900, default 400; Latin + Cyrillic + Vietnamese only), fallbacks (Windows) Segoe UI, Nirmala UI, Yu Gothic UI, Malgun Gothic, Microsoft YaHei UI, sans-serif; monospace Consolas (stopwatch, task status, transfer), Georgia italic (info "i"). Sizes: reply text 18 px/1.35 w500 `#e5edf0` (17 px h≤600, 14 px h≤480); toolbar title 12 px w800 ls 3.2 px; packet title 8 px ls 1.5 `#93adba` (strong 9 px acid w700); packet context 9 px `#8299a5`, origin 7 px ls 1.4; state 8 px ls 1.5; composer 12 px/19 px `#e6eff1`, placeholder `#819fa9`; footer 8 px `#8da9b1`; input hint 7 px; history text 13 px/1.6, labels 10 px ls 1; panel headings 10 px ls 2 (companion) / 18 px (settings); settings `h3` `#a0f5e9`; help 11 px/1.5; notice 10 px; toolbar telemetry 8–10 px tabular numerals. Symbol glyphs used as labels (`↗ ■ ⌁ ♥ ◇ ▾ ▲ ▼ ×`) are not all in Exo 2 (↗ ■ ⌁ ♥ ◇ ▾ ▲ missing) and need a symbol fallback font or vector icons.
Shapes: cut-corner polygons (UI-29) 12 px panels/frames/composer/confirmation, 10 px notice/update card, 8 px attachment cards, 7 px viewer buttons, 6 px microphone key; send button clipped `polygon(0 0,100% 0,100% 75%,75% 100%,0 100%)`. Radius 0 everywhere except inference picker (3), help popup (5), switches, info button (round), theme wheel.
Animations (all disabled or reduced under reduced motion): button feedback 520 ms; telemetry ticker; wake confirm 0.7 s; mic key pulse 1.6 s; microphone preparing spinner 0.9 s/turn; support heartbeat 4 s / orbit 26 s / sparks 5 s / gold shimmer 3.8 s / glow 3.8 s; motion preview (cycle = setting); avatar frame leave/return 210 ms; settings skeleton sweep 1.6 s; search highlight 1.2 s; update card enter 240 ms + signal 3.2 s ×2 (1.2 s loop while downloading); help popup 145/170 ms; switch 150 ms; credits drift/spectrum/rays/sheen; glitch frame envelope (UI-29 ghosts, `presence-model.mjs:153`) with events spaced ≥ 6 s.
#### UI-82 Reduced motion — P1
All CSS animations/transitions above honour `prefers-reduced-motion: reduce`; JS paths check it too (button feedback constant, avatar centring immediate, glitch preview skipped, settings scroll `instant`). On Linux read `org.freedesktop.appearance` `reduced-motion` from the settings portal (§5), fall back to GTK `gtk-enable-animations` or an app preference.
#### UI-83 Localization runtime — P0
`interface-translations.mjs:1-140`.
- Catalog model: English **source strings are the keys** (1962 keys); every locale maps each key to a translation with identical `{placeholder}` sets. Unknown locale id → English. Missing key in a locale → the English text.
- `uiText(text, locale, values?)`:
1. Non-strings are returned unchanged.
2. If `text` is not a key but its whitespace-collapsed/trimmed form is, use the collapsed form.
3. If key: return `interpolate(messages[key] ?? key, values)` (no values → raw translation).
4. Else try **template reverse matching**: every key containing `{name}` is compiled once into `^literal(.+?)literal…$`; the first matching template (in catalog order) extracts variables; a `language` variable equal to a catalog language `name` or `id` is replaced by its localized display name; the literal "automatically detected language" becomes the locale's "Automatic". Return the translated template interpolated with these variables. This lets the backend send fully formatted English sentences (e.g. "Enable microphone (Japanese)") that the UI re-localizes.
5. Else return `text` (interpolated if values are given) — unknown/owner text passes through unchanged.
- `interpolate` replaces `{key}` only for own properties of `values`; unknown tokens stay literally.
- Data vs UI: elements marked `data-untranslated` (and `textarea`, `output`, `script`, `svg` without `data-ui-text`) are never translated; transcript, drafts, device names, file names/paths, window titles, model ids, user tool names and API errors embedded as details are data.
- `InterfaceLanguage.apply(locale)` (DOM re-translation) is a DOM artefact; in Rust every UI label is looked up at render time from its English key, so no reverse map is needed except for step 4.
- Formatting follows the interface locale: percent (`Intl.NumberFormat percent, 0 decimals`), decimals (`maximumFractionDigits` 1–2), sizes, reminder date/time (`dateStyle short, timeStyle short`), memory dates (`medium`, UTC), clock (`HH:MM` 2-digit), developer ms unit format.
- Interface language change never changes conversation/recognition/voice (`languageBehaviorChanged`).
#### UI-84 Locale metadata, language names, RTL — P0
- 50 interface locales (bundle order): en ru de fr es it pt nl pl uk cs sk bg hr sr sl ro hu el da no sv fi et lv lt is ca ar he fa ur hi bn ta te mr gu pa zh ja ko vi th id ms tl tr sw af. RTL: `ar he fa ur`.
- Interface language select shows `nativeName` (first letter upper-cased with the locale's rules at build time).
- `displayLanguage(id, locale)`: if `id` is not in `languages.json` → `id`; else `bundle.languageNames[locale][id]` (precomputed at build time for all 100 catalog ids × 50 locales, so no ICU data is needed at runtime) → fallback `languageNames.en` → `Intl.DisplayNames` → catalog `label`.
- RTL handling: `html[dir]` follows the locale; the companion geometry stays LTR (`#companion{direction:ltr}`); preferences panels, history and dimming switch to RTL (`text-align:start`, mirrored paddings, letter-spacing normal); notice/status/update headline use `unicode-bidi: plaintext`; user-entered text and messages use `dir=auto`; names/models/files use `<bdi>`; the picker anchors to the right edge in RTL; overflow ticker reverses direction.
#### UI-85 Native dialog localization — P1
`main/localized-dialog.mjs`. App-owned strings in open/save/message dialogs (`title, message, detail, buttonLabel, checkboxLabel`, filter names, button labels) pass through `uiText(interfaceLanguage)`; chosen paths remain data. Dialog titles used: "Choose a folder Capri may read", "Choose a short wake sound (up to 10 seconds)" (filter "Audio": wav mp3 ogg flac m4a), "Save and review bug report" (filter "Diagnostic ZIP archive": zip).
#### UI-86 Fonts — P0
`assets/fonts/exo2/Exo2-Variable.ttf` (303 940 B, SHA-256 `205a4486…bfb5`, OFL 1.1, no Reserved Font Name), served as `fonts/exo2.ttf`. Must be bundled (no font service). Keep `OFL.txt` and `README.md` with redistributed copies. Fallback fonts are required for Greek, Arabic, Hebrew, Devanagari, Bengali, Tamil, Telugu, Gujarati, Gurmukhi, Thai, CJK, Persian/Urdu (Nastaliq optional) and the UI symbols.
#### UI-87 Accessibility semantics — P1
- Roles/states to preserve: toggles expose pressed state (voice, mic, music, history (expanded), thinking, internet, monitor display, switches `role=switch` + checked), busy states (`aria-busy` on mic preparing, picker, settings content, attachment viewer), menus (`menu`/`menuitemradio` with checked), meters (`meter` 0–100 for RAM/VRAM), live regions (status footer, notices, internet/thinking status, wake feedback, startup, update headline, announcement), `log` for history (not live), labelled groups for toolbars and settings nav, `aria-describedby` for slider help, `aria-keyshortcuts` on monitor display.
- Screen-reader announcements on turn completion; reduced motion; focus visibility ring; all icon buttons have labels/tooltips; keyboard reachability of every control; `forced-colors` handling for credits.
---
## 3. Data and persistence
Root = `data/` of the installation (Electron `state` = `data/desktop`). All JSON writes go through `writeJsonAtomic` (`packages/runtime/src/atomic-json.mjs`): `mkdir -p`, temp file `<file>.<pid>.<uuid>.tmp` opened `wx` mode `0600`, pretty JSON + `\n`, `fsync`, `rename`, temp always unlinked. Port as `atomic_write_json(path, &T)` with the same steps (plus `fsync` of the directory, recommended).
Preferences envelope (`apps/desktop/preferences.mjs`): `{"schemaVersion": 1, "settings": {...}}`; file > 16 384 bytes, wrong schema or failed validation → defaults in memory + warning "Saved settings could not be restored. Defaults are in use."; the bad file is left untouched until the next explicit save.
| File | Format / schema (synthetic example) | Read/written by UI flows | Notes |
|---|---|---|---|
| `desktop/companion.json` | envelope; settings = companion keys §4.3, e.g. `{"schemaVersion":1,"settings":{"expandOnReply":true,"replyAutoHideSeconds":8,"interfaceTheme":{"preset":"capri","hue":174,"saturation":84,"backgroundHue":174,"backgroundSaturation":40},…}}` | Appearance, Window motion, Wake acknowledgement, Conversation, Reminders, monitor display shortcut | revisioned (sha256 of snapshot JSON) |
| `desktop/languages.json` | envelope; `{"interface":"fr","conversation":"fr","customConversation":"","recognition":"follow","speech":"follow","autoDetect":false}` | Languages | revisioned; also read at very early startup (`main.mjs:7083`) |
| `desktop/dimming.json` | flat `{"schemaVersion":1,"enabled":true,"level":35,"softness":140}` | Window dimming | save debounced in main |
| `desktop/presence.json` | flat `{"schemaVersion":1,"pinned":false}` (read only if < 4096 B) | Keep portrait open | |
| `desktop/window.json` | flat `{"schemaVersion":1,"x":1200,"y":300,"alwaysOnTop":true}` | Always on top (+ window position, window spec) | |
| `desktop/avatar-layout.json` | flat `{"schemaVersion":1,"x":0.5,"y":1,"zoom":1.15}` (x,y ∈ [0,1], zoom ∈ [0.6,3]) | Portrait zoom, reset position | save debounced 250 ms |
| `desktop/speech.json` | envelope `{"trailingSilenceSeconds":1}` | Pause after speech | revisioned |
| `desktop/initiative.json` | envelope; §4.8 | Initiative | revisioned |
| `desktop/voice-effects.json`, `music-listening.json`, `computer-control.json`, `screen-observation.json` (`{"intervalMs":30000,"durationMs":600000}`), `inference-startup.json` (`{"skipLocalModelOnApi":true}`), `discord-presence.json`, `call-audio.json` (`{"allowModel":false,"callVoiceVolume":50}`), `applications.json` (`{"notepad":false,"calculator":false}`), `application-access.json` | envelope | respective sections | owned by their subsystems; listed because the UI edits them |
| `desktop/microphone.json` | audio input selection (voice spec) | Microphone input | |
| `desktop/wake-audio` | raw audio copy (wav/mp3/ogg/flac/m4a), ≤ 4 MiB | Choose audio file | copied with `copyFileSync`; served back as bytes |
| `desktop/wake-voice-<20 hex>.pcm` | mono float32 LE @ 24 000 Hz, 0 < size ≤ 960 000 B, size % 4 = 0, regular non-symlink file; key = first 20 hex of sha256(JSON `{language, phrase, text, identity}`) | Prepare voice response | written `wx` temp + rename; synthesized by `POST {voiceUrl}/synthesize` (§5) |
| `workspace/PERSONALITY.md` | UTF-8 text ≤ 24 000 chars, no NUL; empty save writes the factory text | Personality editor | `packages/runtime/src/personality.mjs` |
| `workspace/.capri/communication.json` | `{"schemaVersion":1,"style":"neutral"}` (≤ 4096 B, non-symlink) | Communication style | `packages/runtime/src/communication.mjs` |
| Settings location | `{"schemaVersion":1,"section":"appearance","scrolls":{"appearance":420},"navigation":0}` ≤ 8192 chars | Settings window | Electron localStorage key `capri.settings.location.v1`; Rust: `desktop/settings-location.json` (UI-42) |
| Stopwatch HUD selection | string id | Show on companion | localStorage `capri.stopwatch.selected` (time spec) |
| Bug report ZIP | user-chosen path, default `capri-diagnostics-2026-01-01T12-00-00-000Z.zip` | Report a bug | temp `<path>.<uuid>.tmp` (`wx`) then rename; content per diagnostics spec |
| `desktop/attachments/<uuid>.{thumb,preview}.png` | PNG thumb ≤ 512 KiB, preview ≤ 3 MiB, archive ≤ 128 MiB | history cards, viewer (read-only here) | attachments spec |
| `desktop/transcript.json` | messages `{id, turnId, role, text, status, createdAt, attachments?, webSources?, avatar?, origin?}`, ≤ 200 messages | history page (read via bootstrap snapshot) | chat spec |
Read-only assets: `apps/shared/interface-locales.json` (11.4 MB bundle), `apps/shared/languages.json` (100 entries), `config/hall-of-fame.json`, `config/community.json`, `config/discord-presence.json` (defaults), `assets/fonts/exo2/*`, `assets/default/brand/{boosty,discord,github,capricore}.svg`. Developer-time only: `apps/desktop/locales/*.json`, `config/interface-locales.json`, `config/interface-glossary.json`.
Retention: none of the UI files grow; settings location and drafts are overwritten in place; previews are in memory only.
### 3.1 Localization file formats (load verbatim)
- `apps/desktop/locales/<id>.json` (editable sources): `{"locale":"en","nativeName":"English","direction":"ltr","review":"source","messages":{"<English key>":"<translation>",…}}`; non-English files also carry `id`, `name`, `audit {sourceRevision, kind, corrections, rejected[]}` and `reviewedIdentical[]` (keys intentionally identical to English).
- `config/interface-locales.json`: `{"schemaVersion":1,"locales":[{"id":"en","name":"English","nativeName":"English","direction":"ltr"},…]}` (id regex `^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$`, direction `ltr|rtl`).
- `apps/shared/interface-locales.json` (generated runtime bundle, the only file the app needs): `{"schemaVersion":1,"source":"en","locales":{"<id>":{"id","name","nativeName","direction","review","messages":{1962 keys}}},"languageNames":{"<uiLocale>":{"<languageId>":"<display name>"}}}`. Builder guarantees: every locale has every English key, non-empty, same placeholder multiset, script-contamination checks; key order = English order.
- `apps/shared/languages.json`: array of `{"id":"fr","name":"French","label":"Français","recognizer":"parakeet-v3","speech":true,"interface":true}`; recognizer ∈ `whisper` (75), `parakeet-v3` (24), `parakeet-v2` (1: `en`); `speech:true` for the voice-capable languages (en ar zh da nl fi fr de el he hi it ja ko ms no pl pt ru es sw sv tr).
- `config/interface-glossary.json`: `{"keys":[11 core keys],"locales":{"<id>":[11 values]},"overrides":{"<id>":{"<key>":"<value>"}}}`. Core keys: Languages, Interface language, Conversation language, Speech recognition, Spoken voice, Apply languages, Menu, Automatic, Text replies only, trained Capri, multilingual Capri. Applying the glossary writes these values (and `Languages…` = first value + `…`) into the locale files before building.
- Rust loading: deserialize the bundle once (background thread at startup, ~11 MB) into `HashMap<String, Arc<Locale>>`; keep `en` and the active locale resident; precompile template regexes from English keys containing `{\w+}` (32 keys). Do not re-run the builder at runtime.
---
## 4. Settings
Notation: **D** = draft (saved with "Save changes"), **I** = immediate, **R** = runtime-only (not persisted). Labels/help texts are the English catalog keys.
### 4.1 General (`general-panel`)
| Key / action | Type | Control | Default | Effect / help key |
|---|---|---|---|---|
| `window-action hide` | action | button "Hide to tray" | — | "Hide the companion window. Bring it back from the system tray." |
| `window-action reset-avatar` | action | "Reset Capri position and zoom" | — | "Restore Capri’s default position and zoom inside the window." (layout → `{0.5, 1, 1.15}`) |
| `window-action reset-position` | action | "Reset to bottom-right corner" | — | "Move the companion window to the bottom-right of the primary display." |
| `window.json alwaysOnTop` | bool **D** | switch "Always on top" | true | "Keep the companion window above other windows." |
| `presence.json pinned` | bool **D** | switch "Keep portrait open" | false | "Keep the portrait visible. Turning this off restores the compact view." |
| focus mode | bool **I/R** | switch "Focus mode" | false | "Hide both windows until you bring Capri back from the system tray." Ends on exit. |
| voice enabled | bool **I/R** | switch "Voice" | false at every launch | "Capri reads replies aloud." |
| microphone enabled | bool **I/R** | switch "Microphone" | off | "Turn voice input on or off." (`window-action microphone` → toggle request) |
| reconnect / sleep / quit / reset | action | buttons | — | §6 confirmations |
### 4.2 Languages (`languages.json`, revisioned, **D**)
| Key | Type | Allowed | Default | Notes |
|---|---|---|---|---|
| `interface` | string | 50 locale ids | `en` | display only |
| `conversation` | string | 100 catalog ids or `custom` | `en` | |
| `customConversation` | string ≤ 60 | `^[\p{L}\p{M} ()'-]+$` or empty; required when `conversation=custom` | `""` | trimmed |
| `recognition` | string | `follow, auto, auto-europe, off`, any catalog id | `follow` | `follow` → conversation id (or `auto` for custom) |
| `speech` | string | `follow`, `off`, speech-capable ids | `follow` | resolved speech must be `off` or equal to the conversation language ("Choose a voice matching the conversation language, or Use conversation language.") |
| `autoDetect` | bool | derived `recognition==='auto'` | false | |
Errors (exact): "Invalid interface language", "Enter a language name, without instructions or formatting.", "Unknown conversation language", "Enter the conversation language name.", "Unknown recognition language", "No voice model for this language.". Host refuses behaviour changes while a reply/preview/training/install is running: "Wait for the current reply to finish before changing languages.".
### 4.3 Companion settings (`companion.json`, revisioned, **D**) — sections appearance / window / dialogue / microphone / time
| Key | Type | Range / values | Default | Control label (help) |
|---|---|---|---|---|
| `interfaceTheme` | object | UI-80 | capri/174/84/174/40 | "Color palette", "Hue", "Saturation" ("Choose a palette or set the accent and background colors separately.") |
| `buttonFeedback` | bool | | true | "Briefly highlight a pressed button" (+ "Try button feedback") |
| `memoryMonitor` | bool | | true | "Show RAM and VRAM usage" |
| `memoryStyle` | enum | `rings` ("Circles"), `bars` | rings | "Chart style" |
| `processGraphs` | bool | | true | "Show system resource graphs" |
| `memoryIntervalSeconds` | int | 3, 5, 10 | 3 | "Refresh interval" |
| `expandOnReply` | bool | | true | "Expand Capri when replying" |
| `minimizedChip` | bool | | true | "Show a restore chip when minimized" |
| `detachedStyle` | enum | `character`, `dialogue` ("Dialogue only") | character | "Out-of-frame appearance" |
| `replyAutoHide` | bool | | true | "Auto-hide completed replies" |
| `replyAutoHideSeconds` | int | 2–60 | 8 | "Delay after speech (seconds)" |
| `floatEnabled` | bool | | false | "Enable floating motion" |
| `floatAmplitude` | int px | 0–24 | 6 | "Motion amplitude" |
| `floatPeriodSeconds` | int s | 4–30 | 10 | "Motion cycle" |
| `glitchEnabled` | bool | | true | "Enable visual glitches" |
| `glitchStrength` | int % | 0–100 | 65 | "Glitch intensity" |
| `glitchIntervalSeconds` | int s | 10–120 | 35 | "Ambient glitch interval" |
| `glitchEvents` | bool | | true | "Glitch on speech and pose changes" |
| `teleportIntensity` / `teleportJaggedness` / `teleportBranches` | int % | 0–100 | 75 / 78 / 75 | "Teleport intensity", "Lightning jaggedness", "Lightning branches" |
| `teleportReducedFlash` | bool | | false | "Reduce teleport flashes" |
| `teleportSound` | enum | off, spark, thunder, pulse | spark | "Teleport sound" |
| `avatarDragTether` | bool | | true | "Show drag lightning on the desktop" |
| `avatarDragTetherIntensity` / `Chaos` | int % | 0–100 | 45 / 55 | "Intensity", "Chaos" |
| `avatarDragTetherDeadZone` | int px | 0–120 | 30 | "Dead zone" |
| `avatarSnapRadius` | int px | 12–100 | 36 | "Attachment distance" |
| `avatarTapGapSeconds` | int s | 1–15 | 10 | "Maximum time between taps (seconds)" |
| `restoreFromTrayOnWake` | bool | | true | "Restore Capri from the tray on voice activation" |
| `wakeSound` | enum | tone ("Signal tone"), file ("My audio file"), voice ("Capri's voice"), off ("Silent") | tone | "Sound after Capri hears her name" |
| `wakePhrase` | enum | "Listening.", "Yes, choom.", "Mhm?" | "Listening." | "Voice response" (visible for `voice`) |
| `wakeVolume` | float | 0–1 step .05 | 0.7 | "Acknowledgement volume" |
| `followUp` | bool | | true | "Let Capri keep listening when she asks a question" |
| `followUpSeconds` | int s | 5–30 | 12 | "Follow-up listening time (seconds)" |
| `wakeOnReminder` | bool | | true | "Wake Capri and prepare her voice for reminders" (shown in Timers section) |
Validation: unknown keys rejected; any violation → "Invalid companion settings" (glitch: "Invalid visual glitch settings", motion: "Invalid window motion settings", theme: "Invalid interface theme."). Snapshot adds read-only `customAudio: bool` (wake audio file exists).
Non-envelope companion-adjacent drafts: `avatar-layout.zoom` slider "Portrait zoom" 60–300 % (default 115 %; stored ×1/100), dimming (`enabled` "Dim the area behind Capri" true, `level` "Strength" 0–85 → 35, `softness` "Soft edges" 0–320 step 5 → 140), communication style (`neutral|romantic|business|wild`, default neutral, **D**), personality text (**D**, ≤ 24 000).
### 4.4 Microphone
| Key | Type | Range | Default | Control |
|---|---|---|---|---|
| microphone device id | string | `""` = system default or a device id | `""` | "Microphone input" (**D**) |
| `speech.trailingSilenceSeconds` | float | 0.5–5 step 0.1 (one decimal) | 1 | "Pause after speech" (**D**, revisioned) |
| wake acknowledgement keys | see 4.3 | | | |
### 4.5 Voice effects (`voice-effects.json`, **D**)
`enabled` false; `preset` clean|cybernetic|radio|synthetic|holographic|custom (clean); `intensity` 0–200 (40), `mix` 0–100 (25), `reverb` 0–200 (0), `delay` 0–200 (0), `filter` 0–200 (0), `glitch` 0–200 (0), `electronicMix` 0–100 (0), `carrierHz` 20–200 (60). Labels: Intensity, Effect mix, Room / reverb, Short delay, Radio filtering, Glitch frequency, Electronic voice blend, Electronic carrier frequency (Hz). Preset values in `voice-effects-settings.mjs:24-70`.
### 4.6 Voice calls / Music
`call-audio.json`: `allowModel` false ("Allow Capri to choose where to speak"), `callVoiceVolume` 0–100 (50, "Capri’s voice volume in calls"); share replies, mix mic, wake from system audio are runtime. `music-listening.json`: `enabled` false ("Music animations"), `notes` true ("Floating notes"), `motion` true ("Move to the music"), `autoBpm` true.
### 4.7 Models / API
| Key | Type | Default | Control |
|---|---|---|---|
| selected local model profile | id | recommended/active | "Language model" select (action-based, not a draft) |
| context window tokens | int from `contextChoices` | backend | "Context window" + "Apply and restart" |
| model devices `{language, voice}` | `auto`/`cpu`/GPU id | backend | "Language model device", "Voice model device" |
| `inference-startup.skipLocalModelOnApi` | bool **I** | true | "Skip local language model when using an API" |
| API profile `{id?, name ≤64, key, settings:{enabled:true, baseUrl ≤512, model ≤128, vision, tools, contextTokens}}` | action | tools true (false for local), vision false, context 32768 (8192 local) | API form |
| Hugging Face token | secret | none | "Hugging Face token" (≤ 512) |
### 4.8 Initiative (`initiative.json`, revisioned, **D**)
`level` off|occasional|conversational (off); `hourlyLimit` null or 1–30 (blank → preset 10/30); `quietHoursEnabled` true; `quietStart` 0–23 (23); `quietEnd` 0–23 (9) (equal start/end = no quiet hours); `spontaneous` true ("Start a conversation occasionally"); `returnReactions` true ("React when I return after being idle"); `appReactions` false ("React to supported media app changes"); `excludedApps` ≤ 30 process names `^[a-z0-9_.-]{1,60}$` lower-cased/deduped, edited as comma text ≤ 1800 chars, default `discord, ms-teams, teams, zoom, powerpnt, obs64`. Error "Initiative settings could not be applied.".
### 4.9 Capabilities
| Key | Type | Default | Control |
|---|---|---|---|
| `computer-control` `{enabled, theme, intensity, cursor, pointerDuration}` | **D** | `true, capri, 50, true, 260` | "Enable edge effects", "Control style", "Effect intensity" 0–100, "Capri cursor and trail", "Pointer movement duration" 0–1000 step 20 ms |
| full computer access | **I** | off | "Give full computer access" |
| application access paused | **I** | enabled | "Pause application access" |
| `applications.{notepad,calculator}` | **I** | false/false | checkboxes |
| custom app grants `{launch, inspect, text}` | **I** | per app | checkboxes |
| Spotify access | **I** (+ restart) | off | "Enable Spotify" |
| folder grants `{id, label, root, write}` | **I** | none | file access list |
| `screen-observation {intervalMs, durationMs}` | **D** | 30 000 / 600 000 (15 000–300 000 / 30 000–7 200 000) | "Minimum analysis interval" s, "Stop observation after" min |
| Brain `{enabled, shareWithApi}` | **I** | true / false | Brain checkboxes |
### 4.10 Community / developer
`update experimental` bool **D** (false, "Include experimental updates"); GitHub token (secret, ≤ 255); Discord `{enabled false, applicationId "" (17–22 digits), assetKey "" (≤ 64 `[A-Za-z0-9_-]`)}` **D**; developer "Live refresh" (R, true).
---
## 5. External protocols
### 5.1 Renderer → core commands (Electron `ipcRenderer.invoke('capri:<channel>')`, `apps/desktop/preload.cjs`)
In Rust these become a `UiCommand` enum handled by the core (same names kept for traceability). Payloads are validated by the core exactly as listed; the Settings window may only use the subset in `main/settings-channels.mjs` (capture, raw audio, avatar acknowledgements and companion geometry are excluded).
| Command (channel) | Payload → result | Used by |
|---|---|---|
| `bootstrap` | — → snapshot (§9.2) | both windows |
| `send` | `{id: uuid, text ≤8000, thinking: bool, internet: bool}` | composer |
| `attachment-add` / `-remove` / `-send` / `-open` | `{name ≤160, originalBytes, bytes: u8[]}` → `{accepted, id, shortened?, animated?, message?}` / `id` / `{id, text, attachmentIds[], thinking, internet}` → `{accepted:false, message}` or turn / `id` → bool | attachments |
| `cancel` | turnId ≤ 80 chars → bool | Stop |
| `voice-stop`, `voice-enabled` (bool → voice snapshot) | | voice toggle |
| `thinking-mode-set` / `internet-mode-set` | bool → `{enabled}` | toggles |
| `web-source-open` | `{turnId: uuid, index 0–4}` (exact keys) | sources |
| `response-painted` | `{id, elapsedMs}` (exact keys) | metrics |
| `activity`, `draft-state` (bool), `interface-busy` (bool), `playback-state` (bool) | | presence/initiative throttling |
| `regions` | `{controls: rect[≤32], sprite: rect+{enabled?, source?, lens?}, footprint?}` | window input shape |
| `drag-start` / `drag-end` | — | handle drag |
| `hide`, `quit`, `reconnect` (→ backend state), `presence-pinned` (bool) | | window controls |
| `settings-open` (section?) → bool; `settings-close`; `settings-preview` (object) → bool; `settings-reset` → reset result or false; `settings-ready`; `settings-loading`; `settings-rendered`; `settings-help` (`{title,text,y,palette}` or null) → bool; `settings-versions` → `{companion, languages, speech, initiative}` | | settings window |
| `window-action` | `{action, value?}` with action ∈ `always-on-top(bool)`, `reset-position`, `reset-avatar`, `reconnect`, `hide`, `focus-mode(bool?)`, `portrait(bool?)`, `microphone`, `quit`, `sleep`, `leave-frame`/`return-to-frame` (companion only) | General |
| `companion-settings` | settings or `{payload, expectedRevision}` → settings or `{settings, revision}` | Appearance… |
| `languages`, `speech-settings`, `initiative` | same revision protocol | sections |
| `personality-get` → `{text, original, communicationStyle}`; `personality-save` (text) → saved text; `personality-open`; `communication-style` (style) → style | | Personality |
| `wake-import` → companion snapshot or null; `wake-prepare` → true; `wake-audio` → `{bytes, pcm, sampleRate:24000, text?}` or null | | Wake acknowledgement |
| `reset-context`, `reset-memory` → bool (main confirms) ; `saved-memory` → `{items:[{text,source,date}], truncated?, unavailable?}`; `memory-save` (text) → `{saved}` | | memory |
| `brain` `{action: status|configure|open|refresh|search, enabled?, shareWithApi?, query?}`; `private-memory` `{action: status|create|unlock|lock|list|add|remove|chat|password, …}` | | knowledge |
| `workflow` `{action: status|record|stop|save|remove|run, …}`; `user-tool` `{action: status|open|refresh|example|stop|enable|settings|inputs|test, …}` | | capabilities |
| `models-status`, `models-refresh`, `models-prepare`(id), `models-cancel`, `models-apply`, `models-folder`(ollama|huggingface), `context-apply`(tokens), `model-devices`, `model-devices-apply`({language, voice}) | | models |
| `huggingface-status|search({query,task})|inspect(repo)|plan({repository,revision,filename,projector})|install|cancel|remove(id)|repair(id)|token-save(token)|token-remove` | | models |
| `inference-api-status|save|test(id)→{elapsedMs}|use(id|null)|remove(id)`, `inference-startup-set({skipLocalModelOnApi})` | | API |
| `update-status|settings({experimental})|check({experimental})|download|cancel|install`, `update-remind-later`, `github-status|connect(token)|remove|token-page(kind?)` | | updates |
| `file-folder-add|write({id,write})|revoke(id ≤80)`, `file-folders-clear`, `file-recovery`, `file-restore(id)`, `file-purge-recovery(id)` | | files |
| `applications({notepad,calculator})`, `application-access(bool?)`, `app-catalog`, `app-discover({query, refresh:bool})`, `app-discover-grant(id)`, `app-catalog-add`, `app-catalog-update({id, launch?|inspect?|text?|remove?})`, `desktop-journal`, `spotify-status|access(bool)|check` | | applications |
| `computer-access-status|set(bool)`, `computer-task(text)`, `computer-task-status`, `computer-stop`, `computer-appearance|appearance-set|preview` | | computer |
| `time-status`, `time-action({action, id?, title?, seconds?})`, `reminder-retry(id)`, `stopwatch-select(id)` | | time |
| `discord-status|configure({enabled,applicationId,assetKey})|portal` | | discord |
| `bug-report({category,title,description,steps,expected,actual,includeLogs})` → `{saved, reportId, files, bytes}` or false; `community-link(id)` | | bug/support |
| `confirmation({id, choice})` → bool; `action-respond({id, accepted})` → `{confirmation?, cancelled?}` | | consent |
| `memory-status`, `monitor-display('toggle'|'menu')` | | HUD |
| `glitch-preview(settings)`, `dimming(settings)`, `avatar-layout(layout)` | | appearance |
| `developer-diagnostics`, `developer-log(id)` → `{text, truncated}`, `developer-open-logs` | | developer |
| `screen-form-command({action, sourceId, interval, duration, question})`, `screen-settings({intervalMs,durationMs})` | | screen |
| `microphone-devices` → `{devices:[{deviceId, deviceLabel}], selection:{deviceId, deviceLabel, inputDeviceId?}}`, `microphone-device(id)` | | microphone |
| `call-audio-command|devices|setup` | | calls |
| `speech-availability`, `speech-install-status`, `speech-install({speech, recognition})`, `speech-install-cancel` | | languages |
| `avatar-composer-state`, `avatar-composer-ack({id, accepted})` | | mini composer |
Trust boundary (`main/ipc.mjs`): channel names `^capri:[a-z-]+$`; accepted only from the current window's exact main frame and expected URL; settings frame restricted to `SETTINGS_CHANNELS`; revisioned channels serialized per channel.
### 5.2 Core → UI events (`capri:event` payload `{type, …}`)
Companion (`app.js:1993-2598`): `application.access`, `avatar.reply-hover`, `thinking.settings`, `internet.settings`, `music.status`, `avatar.composer.action`, `startup-intro.skip`, `avatar.headpat`, `avatar.tap`, `avatar.detach`, `wake.error`, `voice.warning`, `wake.audio-ready`, `time.hud-selected`, `initiative.activity|settings|status|error`, `settings.toggle-portrait`, `settings.set-portrait {active, preservePresentation?}`, `reminder.wake`, `reminder.delivery`, `glitch.preview`, `open-time|open-models|open-updates|open-companion|open-voice-effects|open-languages|open-speech-settings|open-file-access|open-applications|open-initiative|open-screen|open-dimming`, `time.changed {objects}`, `time.due {object}`, `action.approval {proposal}`, `spotify.settings`, `models.status`, `updates.status`, `confirmation.request`, `confirmation.closed`, `startup.progress`, `companion.settings {settings, reset?}`, `monitor.error`, `settings.renderer-lost`, `conversation.cleared`, microphone events, `voice.settings`, `speech.settings`, `file-access`, `applications`, `computer.control`, `computer.task`, `screen.status|observation|clip-request|clip-status|clip-saved|reset|settings`, `languages`, `speech-install.status`, `speech-components`, `voice.effects`, `voice.preview-started`, `call-audio.reset|policy`, `voice.call-started|audio|generated|cancelled|error`, `dimming`, `backend {phase, message}`, `power.state`, `focus-input`, `avatar.selection`, `avatar.layout`, `turn.started|web-search|preface|approach|tool|delta|completed|failed|cancelled`.
Settings (`settings-app.mjs:1468-1690`): `settings.visibility`, `music.status`/`music-listening.status`, `settings.help-closed`, `window.focus-mode|always-on-top|portrait`, `microphone.device-changed|settings`, `computer.task`, `computer-access`, `application.access`, `brain.status`, `private-memory.status`, `workflow.status`, `settings.resume`, `settings.navigate {section, focus}`, `settings.close-request`, `settings.screen-state`, `settings.call-audio`, `call-audio.reset`, `settings.call-setup`, `confirmation.request|closed`, `settings.glitch {start, eventAt, timestamp, settings}`, `huggingface.status`, `voice-catalog.status`, `voice-training.status`, `initiative.activity`, `dimming`, `companion.settings`, `languages`, `avatar.layout`, `speech-install.status`, `speech-components`, `voice.settings`, `settings.activity {chat, playback}`, `time.changed`, `backend`, `discord.presence`, and the state events of UI-46. Events with `preview:true` are ignored by Settings.
### 5.3 HTTP
- Wake voice preparation (`main/companion-ipc.mjs:114-155`): `POST {voiceUrl}/synthesize` with voice auth headers, `content-type: application/json`, body `{"text":"<translated phrase>","language":"fr","requestId":"wake:<uuid>"}`, timeout 90 s, redirects forbidden; requires `x-sample-rate: 24000`; streamed body capped at 960 000 bytes, non-empty, multiple of 4 (voice spec owns the server).
- Hall of Fame: local `hall-of-fame.json` (≤ 2 MiB, no credentials). No other network access from the UI; external links are opened by the system browser.
### 5.4 Linux desktop protocols (new in the Rust port)
| Need | KDE Plasma 6.8 | i3 4.25 / X11 | Fallback |
|---|---|---|---|
| Open folder/file dialogs, save dialog | `org.freedesktop.portal.FileChooser` `OpenFile` (`directory: true` for folders, `multiple`, `filters`) / `SaveFile` (`current_name`) — verified present on the host | portal only if `xdg-desktop-portal-gtk` is running; otherwise GTK3 native dialog | `rfd` (GTK3 backend) |
| Open external URL | `org.freedesktop.portal.OpenURI.OpenURI` | `xdg-open <url>` | `open`/`opener` crate |
| Reveal file in folder | `org.freedesktop.FileManager1.ShowItems(["file:///…"], startup_id)` (Dolphin) | same if a file manager owns the name | `xdg-open <parent dir>` |
| Reduced motion | `org.freedesktop.portal.Settings.ReadOne("org.freedesktop.appearance","reduced-motion")` (uint 0/1; verified exposed) and `SettingChanged` signal | GTK `gtk-enable-animations` in `~/.config/gtk-3.0/settings.ini` | app setting |
| Work area for Settings placement | X11 `_NET_WORKAREA` (KWin sets it for XWayland clients) + RandR monitors | i3 IPC `GET_WORKSPACES` (`rect` excludes bars) / `GET_OUTPUTS`; see `capri_linux/x11.py:i3()` | full monitor rect −24 px |
| Secret storage (API keys, tokens) | Secret Service `org.freedesktop.secrets` (provided by `ksecretd`, verified) | needs gnome-keyring/KeePassXC | show "Secure credential storage is unavailable…" and disable save (UI-63/UI-71) |
Example (zbus, portal file chooser for a folder grant):
```text
method call org.freedesktop.portal.Desktop /org/freedesktop/portal/desktop
org.freedesktop.portal.FileChooser.OpenFile
parent_window = "x11:0x4a00007"
title = "Choisir un dossier que Capri peut lire" (uiText of "Choose a folder Capri may read")
options = {"directory": <true>, "multiple": <false>, "modal": <true>, "handle_token": <"capri_1">}
→ Response(u 0, {"uris": <["file:///home/alex/Documents/projets"]>})
```
---
## 6. Text to reproduce
All visible strings are catalog keys of `apps/desktop/locales/en.json` (1962 keys) and must be displayed through the i18n layer, including English (29 English values differ from their keys, e.g. `VOICE PENDING` → "PREPARING VOICE", `Desktop presentation` → "Desktop appearance", `Save memory` → "Save fact", `I reviewed this tool — enable` → "I reviewed the code — enable tool", and the initiative reason codes `cooldown`, `delivered`, `disabled`, `excluded_app`, `fullscreen`, `generation_*`, `hidden`, `hourly_limit`, `locked` ("Windows is locked"), `model_busy`, `model_chose_silence`, `preparing_comment`, `quiet_hours`, `ready`, `settings_open`, `sleeping_or_offline`, `speaking`, `suspended`, `typing`, `user_away`, `user_speaking`, `waiting`). Copy the catalogs verbatim; never hard-code translated text.
Long blocks to copy from source (do not paraphrase; they are also catalog keys):
- Companion settings form, support and bug tabs: `apps/desktop/renderer/companion-panel.mjs:64-209`.
- General panel: `apps/desktop/renderer/settings-app.mjs:136-197`.
- Hosted index.html panels (dimming, voice effects, microphone, languages, file access, application access, initiative, screen, timers, alerts): `apps/desktop/renderer/index.html:495-1030`.
- Voice calls panel: `apps/desktop/renderer/settings.html:76-216`; call setup statuses `settings-app.mjs:539-549`.
- API connections panel: `inference-panel.mjs:62-109`; key help variants `inference-panel.mjs:498-507`.
- Models: states and tier descriptions `models-panel.mjs:5-19`, panel `models-panel.mjs:28-51`; model devices `model-device-panel.mjs:7-14`; Hugging Face `huggingface-panel.mjs:7-31`.
- Languages status/help strings: `language-panel.mjs:126-206, 239-290`.
- Updates: `updates-panel.mjs:2-12, 25-52`. Update card: `update-notification.mjs:71-88`.
- Knowledge/private memory/saved memory: `knowledge-panel.mjs:10-11`, `private-memory-panel.mjs:6-13, 106-120`, `saved-memory-panel.mjs:9-16, 141-153`.
- Workflows / user tools: `workflows-panel.mjs:2-8, 17`, `user-tools-panel.mjs:9-10, 55-89`.
- Developer labels: `developer-panel.mjs:2-51, 69-103`. Credits: `credits-panel.mjs:3-7, 151-210`.
- Discord statuses `discord-panel.mjs:63-70`; Spotify statuses `applications-panel.mjs:297-311`; computer task labels `applications-panel.mjs:231-239`, `app.js:2333-2341`.
- Communication-style prompt fragments shown only as names in the UI but stored here: `packages/runtime/src/communication.mjs:6-20` (persona spec). Factory personality text: `packages/runtime/src/personality.mjs` (persona spec).
Short strings to reproduce verbatim (English source):
- API disclosure (`inference-privacy.mjs:2`): "Optional alternative to the local language model. Your messages, personality, relevant memory and tool results are sent to your chosen provider. Screen images are sent only when you enable vision and use screen features. Provider charges and privacy terms apply. Speech recognition and voice remain local."
- Internet hint: "Search the web for the current request only. Chat history, screenshots and files are not sent automatically." Thinking hint: "Take more time to check difficult answers."
- Attachment-only prompt sent to the model: "Describe the attached files." (English regardless of UI language).
- Composer placeholder "Talk to Capri…"; welcome "Hey. I'm here."; packet title "INCOMING TRANSMISSION"; initial input "Connection established."; initiative prompt "A thought of her own."; announcement "Capri has replied.".
- Action approval help: "Only approve actions you requested. This request expires in 90 seconds."
- Settings: "Settings changed elsewhere. Apply or discard your draft.", "Default settings restored.", "No matching settings", "Settings closed unexpectedly. Open Settings to try again.", "Enter a valid screen observation interval and duration.".
- Confirmation dialogs issued by the core (title / detail / confirm label):
- Quit: "Quit Capri?" / "Capri will close and unload the local models. Any active reply will stop." / choices Cancel, Sleep, Restart, "Quit and unload models" (danger).
- Sleep: "Unload models and sleep?" / "Models will be loaded again when you wake Capri." / "Unload models".
- Reset: "Reset settings to defaults?" / "This restores the default window and appearance settings, monitoring, voice effects, speech pause, initiative, screen observation and computer control effects. Unsaved changes to these settings will be discarded." / "Reset settings" (danger, 3 s delay).
- Clear: "Start a new conversation?" / "Current context and the visible history will be cleared. Long-term memory is retained." · "Delete saved notes about you?" / "USER.md, MEMORY.md and notes in memory will be cleared. Conversation archives remain separate. This cannot be undone." / "Clear" (danger).
- Personality: "Restore original character?" / "Your custom personality will be replaced by the original character." / "Restore original character" (danger).
- Provider: "Change AI provider?" / remote: "Your conversation, personality, relevant memory and tool results will be sent to this provider. Images are sent only with enabled vision and screen features. Provider charges may apply. Capri will restart." · local: "Capri will send requests to the selected server on this PC and restart." / "Apply and restart". "Remove API connection?" / "Its saved API key will be removed from this PC." / "Remove".
- Models: "Switch language model?", "Context window", "Model devices" / "Capri will restart with the prepared model. Your conversation, memory, voice and personal settings will be kept." / "Switch model and restart" · "Apply and restart" · "Save and restart Capri". "Remove downloaded model?" / "The selected Hugging Face package will be removed from this PC." / "Remove".
- Files: "Restore this file?" / "<relative path>\n\nThe current folder write permission is required. Existing files are never overwritten." · "Delete recovery copy permanently?" / "<relative path>\n\nCapri will permanently delete this recovery copy. It cannot be restored through Capri. The Windows Recycle Bin, restored originals and other backups are managed separately." / "Delete permanently".
- Spotify: "Enable Spotify control?"/"Disable Spotify control?" / "Capri will restart to apply Spotify access. Your history, memory and voice settings will be kept. Only the Spotify desktop app is controlled." / "Enable and restart"/"Disable and restart".
- Language voice: "Selected voice is not installed" / "Capri can install the selected voice automatically in its own folder. No ZIP files, destination folders or terminal commands are needed. Keep Capri open until installation finishes." / Stay here · Use text replies · Install and enable.
- Unsaved (legacy in-window): "Unsaved changes" / "Save your changes before leaving?" / Stay here · Discard changes (danger) · Save and leave.
- Templates with slots (must keep placeholders): "{label} ({seconds} s)", "{seconds} s", "{value} s", "{value} px", "Remove {filename}", "Recommended for {language}", "Enable microphone ({language})", "Microphone ({language})", "Unavailable — {device}", "Estimated remaining: {seconds} s", "Active context: {size}", "Approximate download: {size}", "Model files: {size}", "Recommended system RAM: at least {ram} GB.", "Last request: {used} / {total} tokens. Click to change context.", "{device} is overheating ({value} °C).", "{device} is nearly full ({value}%).", "{count} saved memories", "{shown} of {total} memories", "A new update is available: {version}", "Next attempt: {time}", "Updated {time}", "Model call {number}", "Example: {value}", "Choom, your reminder: {text}", "Elapsed time: {time}.", "Result: {value}", "Spotify volume: {value}%.", "API provider returned HTTP {status}. Check access, model availability and account balance.", "API connection failed. Check the provider URL and network. ({code})", "Enter text or a {{variable}} for the text step.".
No LLM prompts, tool descriptions or JSON schemas are owned by this subsystem; its only model-bound text is the attachment default prompt above and the user's drafts.
---
## 7. Security, privacy and permission invariants
1. **UI text is never markup.** Every dynamic value (transcript, memory notes, file names, model ids, provider errors, tool output, Hall of Fame names) is rendered as plain text; no HTML/Markdown interpretation in the UI. Untrusted strings are bounded and stripped of control characters before display (titles ≤ 240/160, approach ≤ 900, preface ≤ 280, names ≤ 160).
2. **Data vs UI separation in i18n.** Only owned labels go through `uiText`; user/owner data must never be looked up as a translation key (a note that happens to equal a key must display verbatim).
3. **Consent gates are fail-closed.** Confirmations: single pending request, unknown/expired ids rejected, non-cancel choices refused before `delayMs`, 180 s timeout → cancel, closing/hiding/crash → cancel, a request arriving while one is pending → cancel; the UI responds `cancel` if it cannot show the dialog (unsaved draft writes pending, applying drafts). Action approvals auto-reject at `expiresAt` (90 s) and display the untranslated detail of exactly what will run. Destructive buttons use the danger style and default focus goes to Cancel.
4. **Optimistic concurrency for settings.** Revisioned writes must be rejected when the snapshot changed; drafts are never silently overwritten by external changes (UI-46).
5. **Credentials never round-trip to the UI.** API keys/tokens are write-only fields (password inputs, never pre-filled; placeholder "Encrypted"); cleared after save/cancel/navigation/close/hide; key validation before IPC; editing a profile keeps a stored key only for the same origin; saving is refused when secure storage is unavailable (no plaintext fallback). Private memory passwords, notes, replies and user-tool secrets are wiped on hide; private memory locks when Settings hides and after 5 min inactivity.
6. **No remote content in UI surfaces.** Fonts, icons, brand SVGs and the Hall of Fame are local; the only outbound actions are explicit link openings by fixed identifiers (`community-link` ids → fixed HTTPS origins with no credentials; web sources opened by `{turnId, index}` re-read from the stored transcript, http/https only, no userinfo). The attachment viewer has no command channel and only reads `attachments/<uuid>/preview.png`.
7. **Clipboard and drag-drop are explicit.** Files are read only from an explicit paste/drop/picker action; never clipboard text/HTML, paths or URLs; names reduced to their last segment; size/format/vision limits enforced before reading/encoding; dimensions ≤ 18 MP; PDF parsing without script evaluation and with page/char/time limits.
8. **Remote inference disclosure.** When the active source is remote: attachment info shows "Files are shared with the active API when sent."; screen privacy help is replaced by the API disclosure (warning style); provider change requires confirmation; Brain excerpts and private chat to an API are separate opt-ins (default off).
9. **Settings window capability restriction.** The Settings surface cannot capture the screen/audio, send chat turns, or move the avatar; such actions are proxied to the companion (`screen-form-command`, `window-action microphone`). Keep this separation as distinct command sets in Rust.
10. **Diagnostics.** Bug reports are only written to a user-chosen path after a save dialog; chat history, memory, recordings and screenshots are excluded and secrets redacted (diagnostics spec); single collection at a time. Developer panel shows technical counters and log tails only (≤ 64 KB).
11. **Interface-busy suppression.** While Settings or a modal is open, or a draft exists, initiative comments and avatar click reactions are suppressed (`interface-busy`, `draft-state`).
12. **Hit regions.** The transparent companion must only capture input on published regions (≤ 32 rects) and the full window only during a modal confirmation; everything else passes through to the desktop.
---
## 8. Windows-specific mechanisms and their Linux replacements
Baseline decision: all Capri UI windows are **X11 clients**. On KDE Plasma 6.8 (Wayland session, verified `kwin 6.8.2`, `XDG_SESSION_TYPE=wayland`, `DISPLAY=:1`) they run through XWayland so they can position themselves and use X input shapes; on i3 4.25.1 they are native X11. Force winit's X11 backend (`EventLoopBuilderExtX11::with_x11()` through eframe's `event_loop_builder` hook) rather than relying on environment variables.
| # | Windows/Electron mechanism (source) | KDE Plasma 6.8 (XWayland) | i3 4.25 (X11) | Existing `capri_linux` help |
|---|---|---|---|---|
| 1 | Transparent frameless always-on-top 480×660 companion; click-through via `setIgnoreMouseEvents(true,{forward:true})` + published regions (`secure-window.mjs`, `pointer-controller`) | ARGB visual + KWin compositing; `_NET_WM_STATE_ABOVE`, `_NET_WM_STATE_SKIP_TASKBAR/SKIP_PAGER`; click-through = XShape **input** region (`ShapeInput`, union of UI-30 rects; full window while a modal is open). With an input shape the X server delivers events only inside the regions, so the KWin cursor-polling helper becomes unnecessary for the UI | Same X11 calls; transparency requires a compositor (picom). Detect `_NET_WM_CM_S0` owner; without it paint the opaque fallback `#07131c` behind UI rects or accept black. Float via `_NET_WM_WINDOW_TYPE_UTILITY` (or user `for_window [class="^Capri$"] floating enable, sticky enable`); floating windows stay above tiled ones; `_NET_WM_STATE_ABOVE` has no effect | `capri_linux/cursor.py` (KWin `workspace.cursorPos` reporter used by `main/linux-cursor.mjs` because Electron forward-mode needs polling under XWayland) — only needed if input shapes are not used |
| 2 | Settings window docked beside the companion using `screen.getDisplayMatching(...).workArea` (`settings-window.mjs:5-16`) | RandR monitor of the companion + `_NET_WORKAREA` (KWin publishes it to X11 clients); X11 clients may self-position | i3 `GET_WORKSPACES` (`rect` = output minus bars) / `GET_OUTPUTS`; mark Settings as `_NET_WM_WINDOW_TYPE_DIALOG` + `WM_TRANSIENT_FOR` = companion so i3 floats it and honours its position | `capri_linux/x11.py:i3()` (i3-msg JSON), `capri_linux/kwin.py` `outputs()` (KWin script listing `workspace.screens`) |
| 3 | Native help popup: non-focusable, click-through, transparent child window beside Settings (`settings-window.mjs:131-247`) | Recommended: drop; use the inline fallback (UI-48) | Same | — |
| 4 | Attachment viewer fullscreen on the companion's display (`main/attachment-viewer.mjs`) | `Fullscreen::Borderless(Some(monitor))` | i3 honours `_NET_WM_STATE_FULLSCREEN` | — |
| 5 | Electron native dialogs `showOpenDialog`/`showSaveDialog` (localized via `localizedDialog`) | `org.freedesktop.portal.FileChooser` (verified on host) via `ashpd`/`zbus` | Portal only if a backend runs; otherwise GTK3 file chooser (`rfd` gtk3 feature, pkg-config, no bindgen) | — |
| 6 | Native popup menus (`Menu.buildFromTemplate().popup`: monitor display style, screen source picker) | In-app egui popup menus anchored to the button (consistent theme, localizable) | Same | — |
| 7 | `shell.openExternal`, `shell.showItemInFolder` | portal `OpenURI`; `org.freedesktop.FileManager1.ShowItems` (Dolphin) | `xdg-open`; FileManager1 if available, else open the parent folder | — |
| 8 | `safeStorage` (DPAPI) behind `secureStorage` flag (API keys, GitHub/HF tokens, tool secrets) | Secret Service (`ksecretd`, verified `org.freedesktop.secrets`) | gnome-keyring/KeePassXC Secret Service if present; else `secureStorage:false` → saving disabled with the existing messages | — |
| 9 | Chromium compositor first-frame probe (`capturePage`, opacity 1/255, 6 retries) | Not needed: present after first egui frame | Same | — |
| 10 | Chromium `localStorage` (settings location, stopwatch selection) | `data/desktop/settings-location.json` (atomic JSON) | Same | — |
| 11 | `prefers-reduced-motion` | portal Settings `org.freedesktop.appearance` `reduced-motion` (verified key present) + `SettingChanged` | GTK `gtk-enable-animations=false`, else app preference | — |
| 12 | Windows font fallbacks (Segoe UI, Nirmala UI, Yu Gothic UI, Malgun Gothic, Microsoft YaHei UI, Consolas, Georgia) | fontconfig: Noto Sans (+ Arabic, Hebrew, Devanagari, Bengali, Tamil, Telugu, Gujarati, Gurmukhi, Thai, CJK), DejaVu Sans (symbols), DejaVu Sans Mono / Liberation Mono, Noto Serif Italic — host has Noto + DejaVu installed | Same | — |
| 13 | Chromium ICU (`Intl.NumberFormat`, `DateTimeFormat`, `DisplayNames`, `toLocaleLowerCase`) | ICU4X (`icu` crate, compiled data) for numbers/dates; language names already precomputed in the bundle; locale-aware lowercase special cases (tr/az) + `unicode-normalization` NFKC | Same | — |
| 14 | Canvas text measurement for subtitle/bubble fitting | egui galley layout with the same font/size/letter spacing | Same | — |
| 15 | DOM drag & drop and paste of `File` objects | winit `DroppedFile` (XDND; XWayland bridges Wayland drags); clipboard `text/uri-list` (`file://` only, read bytes, keep only the file name) and `image/png|jpeg|webp|gif` targets, only on explicit Ctrl+V in the composer | Same (X11 selections) | — |
| 16 | `KeyboardEvent.isComposing` | winit IME events (`Ime::Preedit` active → Enter does not send); XIM with fcitx5/ibus | Same | — |
| 17 | DIP coordinates on Windows | KDE "Legacy applications (X11)": prefer "Apply scaling themselves" so winit gets the real scale factor; otherwise the compositor scales bitmaps | Xft.dpi / XSETTINGS scale | — |
| 18 | Ctrl+Shift+Space focus-mode exit, tray "Show Capri" (window/tray spec) | KGlobalAccel or portal GlobalShortcuts; SNI tray (`ksni`) | user `bindsym … exec capri --show`; i3bar tray is XEmbed only (needs `snixembed` for SNI) | — |
| 19 | Windows wording in the catalog ("Windows logical pixels", "Windows Recycle Bin", "Windows AppContainer", "Windows is locked", "Restart Windows…", VB-CABLE, Notepad/Calculator, "only supported Windows apps") | See open questions; do not edit the 50 catalogs by hand | Same | — |
---
## 9. Interfaces with other subsystems
### 9.1 Consumed
- **Core command API** (§5.1) and **event stream** (§5.2), delivered to the UI thread through a channel; every event handler must tolerate unknown types.
- **Chat/turn engine**: transcript snapshot (`messages`), turn events, `activeTurnId`, cancel, attachment drafts (`attachment-*`), web source opening, response-paint metric sink.
- **Voice/speech**: voice snapshot `{enabled, ready, error, language}`, playback events for subtitle sync (`voice.audio/generated/cancelled/error`, preview), microphone state for the input key/preview row, speech install status/availability, wake audio bytes, call-audio state.
- **Avatar/presence**: presence model (`expanded`, `pinned`, `sleeping`, signal state → SIGNAL_STATES), avatar detach phase, avatar hit rect for UI-30, startup intro gating.
- **Models/inference**: inference snapshot `{remote, vision, setupRequired, model, providerHost}`, model status/inventory, devices, HF status, API profiles (`{id, name, baseUrl, model, vision, tools, contextTokens, hasKey, canConnect}`), local residency.
- **Settings stores**: Preferences snapshots + `settingsVersions()` + `updateSettingsPreview()` + `resetDesktopSettings()`.
- **Capabilities**: time objects `{id, kind: remind|timer|stopwatch, title, state: running|paused|due|cancelled|acknowledged, remainingMs, elapsedMs, dueAt}`, action approvals, application access, desktop catalog, file permissions `{scopes:[{id,label,root,write}], warning}`, recovery list `[{id, relative}]`, screen form state, initiative status/scheduling `{nextAt, reason}`, computer task status `{active, phase, steps}`, Spotify state `{enabled, prepared, phase, connection, error}`, Discord `{enabled, applicationId, assetKey, phase}`.
- **System resources**: memory/CPU/GPU samples for the HUD.
- **Diagnostics**: `createDiagnosticReport`, developer diagnostics `{capturedAt, unavailable, turns[], logs[]}`.
### 9.2 Bootstrap snapshot (`main.mjs:5694-5768`)
Keys: `attachmentVision, thinking{enabled}, internet{enabled}, time, inference, windowSettings{alwaysOnTop, focusMode, avatarOnly}, settingsVersions, screenSettings, spotify, models, updates, messages, companion (+customAudio), startup, backend{phase, message}, power{phase}, warning (string|null), artwork, activeTurnId, language, sprite, avatars, animation, musicArtwork, musicListening, startupIntro, avatar, avatarLayout, dimming, voice, speech, microphone (+available), presence{pinned}, voiceEffects, allowModelCallAudio, callVoiceVolume, languages, languagePacks, recognitionAvailability, speechAvailability, speechInstallation, fileAccess, applications, applicationAccess, initiative, awareness, screen, screenObservation, lastScreenshot`. Both windows receive the same snapshot; in Rust split it into typed sub-snapshots fetched on demand.
### 9.3 Provided
- To **window/pointer**: hit regions `{controls[≤32], sprite, footprint?}`, handle drag start/end, `interface-busy`, `draft-state`, window actions (always-on-top, portrait, reset position/avatar, hide, focus mode, quit, sleep, reconnect).
- To **avatar** (detached window, mini composer, minimized chip): desktop cue `avatarReply({text, turnId, fullText ≤ 16000, autoCollapsed?})`, `avatarStatus({text (translated signal label), color #rrggbb})`, reply labels (show/hide/previous/next), mini composer state (UI-32) and action acknowledgements, theme colours, the reusable logic crate (ReplyPages, detachedReplyLayout, replyBubbleOutline), `avatar.reply-hover` hold handling.
- To **voice**: voice enable/disable, stop, playback state, preview requests, wake acknowledgement settings, speech pause, microphone device, call commands.
- To **chat**: send/cancel/attachments with thinking/internet flags; `activity` pings (≥ 150 ms apart).
- To **initiative**: activity/draft/busy signals; settings.
- To **everyone rendering text** (tray menu, native dialogs, monitor menu, avatar HUD, notifications): the i18n service (`uiText`, language names, direction) and the theme service (`interfaceThemeColors`).
- Live **settings preview** overlay: keys `companion, dimming, zoom, alwaysOnTop, portrait, voiceEffects, interface, languages, personality, style, initiative, microphone, speechPause, computerAppearance, musicListening`; consumers must render `liveSettings = persisted ⊕ preview` while Settings is open and drop the overlay when it closes.
---
## 10. Recommended Rust design
### 10.1 Crates (workspace members)
| Crate | Responsibility | Depends on |
|---|---|---|
| `capri-i18n` | Load `interface-locales.json` + `languages.json`; `tr`, `tr_fmt`, `localize_message` (template reverse matching), `language_name`, `direction`, `fold_search`, number/date formatting | `serde`, `serde_json`, `regex`, `unicode-normalization`, `icu` (icu_decimal, icu_datetime; compiled data) |
| `capri-theme` | Theme settings/validation, derived palette, Capri fallback token table, `panel_path`, glitch envelope helpers | `serde` |
| `capri-ui-logic` | Pure, GUI-free logic shared with the avatar crate: reply pages/visibility, subtitle cues/timing, bubble outline, detached layout, settings registry/search/location, draft engine core, confirmations broker, HUD math (memory display, warnings, sparkline), startup progress, update tag check, API key/endpoint validation, attachment validators and clipboard name sanitizer, `settings_bounds`/`help_bounds`, hit-region merge (≤ 32) | `serde`, `sha2`, `uuid`, `unicode-segmentation` |
| `capri-ui` | eframe/egui application: companion viewport, settings viewport, attachment viewer viewport, widgets, sections, event/command bridge | `eframe`/`egui` (accesskit feature), `winit` (x11), `x11rb` (pure-Rust connection; `shape`, `randr` features), `zbus`/`ashpd` (portals, FileManager1), `rfd` (gtk3) fallback, `image` (png/jpeg/webp/gif), `arboard` (clipboard), `open`, `tokio` handle or `crossbeam-channel` |
No crate in this list runs bindgen at build time (x11rb is pure Rust; gtk3 `-sys` crates are pre-generated and use pkg-config; icu4x is pure Rust).
### 10.2 Key types
```rust
pub enum UiEvent { // core -> UI (mirror §5.2, serde-tagged by "type")
TurnStarted { turn_id: Uuid, source: TurnSource, silent: bool, user: Option<Message>, assistant: Message },
TurnDelta { turn_id: Uuid, text: String },
TurnFinished { turn_id: Uuid, kind: Finish, assistant: Message, warning: Option<String>, message: Option<String> },
ConfirmationRequest(ConfirmationRequest), ConfirmationClosed { id: Uuid },
ActionApproval(Option<ActionProposal>), Backend { phase: BackendPhase, message: String },
StateChanged(StateEvent), // companion.settings, languages, dimming, ... (+ preview: bool, reset: bool)
/* … */
}
pub enum UiCommand { // UI -> core (mirror §5.1); Settings gets a restricted subset type
Send { id: Uuid, text: String, thinking: bool, internet: bool },
SetCompanionSettings { payload: CompanionSettings, expected: Option<Revision> },
SettingsPreview(PreviewPatch), Confirm { id: Uuid, choice: String }, /* … */
}
pub struct Revision(pub [u8; 32]); // sha256 of canonical JSON (or a counter, §12)
pub trait Draft {
fn section(&self) -> SectionId;
fn panel(&self) -> &'static str;
fn read(&self) -> serde_json::Value; // compared with baseline
fn preview(&self) -> Option<PreviewPatch>;
fn apply(&mut self, core: &CoreHandle) -> BoxFuture<'_, anyhow::Result<bool>>; // false = stop, stay
fn discard(&mut self, deferred: Option<&serde_json::Value>);
}
pub struct DraftEngine { drafts: Vec<Box<dyn Draft>>, baselines: HashMap<&'static str, serde_json::Value>,
close_requested: bool, applying: bool, resetting: bool, deferred: HashMap<&'static str, serde_json::Value>,
preview_debounce: Duration /* 55 ms */, last_preview: Option<String> }
pub struct ConfirmationRequest { pub id: Uuid, pub title: String, pub detail: String,
pub choices: Vec<Choice>, pub delay: Duration, pub danger: bool }
pub struct ReplyPages { /* §UI-10 */ } pub struct ReplyVisibility { /* §UI-09 */ }
pub struct Palette { pub cyan: Color32, pub pink: Color32, pub panel: Color32, pub background: Color32,
pub border: Color32, pub text: Color32, pub roles: Option<RoleTokens> /* None for capri */ }
```
### 10.3 UI structure (egui)
- One `eframe` app with three viewports: `companion` (transparent, undecorated, always-on-top, X11 input shape updated from UI-30 rects after each frame), `settings` (undecorated 680×N, docked), `viewer` (fullscreen, on demand). Help popups inline.
- Companion screens are immediate-mode functions over an `AppState` updated from `UiEvent`s; layout constants from §2.A/UI-81; the cut-corner frame is a custom `egui::Shape` path (UI-29) drawn over a clipped polygon fill.
- Settings: left nav (176 px, 136 px below 540 px width) with grouped buttons and a search field; right scroll area per section remembering scroll offsets; header with draft bar. Sections are `fn ui(&mut self, ui, ctx)` structs owning their form state and registering drafts.
- Text: all labels via `t!("English key")`/`tr_fmt`; data via plain strings. Hard-code no translated text.
- Accessibility: enable eframe's AccessKit (AT-SPI on Linux via `accesskit_unix`, zbus-based); set roles/labels/toggled states per UI-87.
- Fonts: Exo 2 (embed with `include_bytes!`; generate static instances for 400/500/600/700/800 offline or use a variation-capable rasterizer), then fallback faces resolved through fontconfig at startup (only for scripts of the active locale + symbols to bound memory).
- Threading: core on tokio; UI receives events via channel and calls `ctx.request_repaint()`; commands are sent async and awaited in UI tasks (`poll_promise`-style) with the same busy/disabled rules as Capri.
- Persistence helpers: `atomic_write_json` (§3) and `Preferences<T>` (16 KiB cap, schemaVersion 1, warning on invalid file).
### 10.4 Minimal viable order
P0 first: UI-01, UI-02, UI-04–UI-08, UI-11, UI-12, UI-22–UI-24, UI-30, UI-31, UI-40, UI-41, UI-44, UI-51, UI-52, UI-81, UI-83, UI-84, UI-86. Then P1 sections, then P2.
---
## 11. Test plan
### 11.1 Port from Capri (paths + what they assert)
| Capri test | Assertions to port |
|---|---|
| `tests/reply-pages.test.mjs` | history forwards only recent assistant `{id,text}`, dedupes streamed snapshots; per-reply and total bounds without splitting surrogates; default view follows the live cue; manual selection survives streaming and resets on a new message; empty cue keeps history; narrow bubble starts with a fitted page; repeated sentence anchoring; cache reuse and resize reflow keep the selected anchor |
| `tests/reply-visibility.test.mjs` | never hides before the last sentence played; one timer for text-only replies (re-render cannot postpone forever); hover/selection/history holds; new turn/cancel/late events cannot hide another reply; errors stay visible; manual collapse survives same-turn streaming; reset defaults apply to the next reply |
| `tests/reply-bubble-outline.test.mjs`, `tests/detached-reply-layout.test.mjs` | single closed contour per side, corner targets, anchor clamping, close targets, no tail inside/zero length, fractional sizes, no NaN/∞; tab side/position on all sides, collapse keeps tab, narrow screens stay inside |
| `tests/interface-locales.test.mjs` | all 50 locales complete with identical placeholders and glossary/override values; UI language change never implies behaviour change; editable catalogs equal the bundle; `uiText` behaviours (`Open`→ru "Открыть", whitespace-collapsed keys, owner text unchanged, slot preservation, `Microphone (Japanese)` in de contains the German name of Japanese); RTL ids `ar he fa ur`; unknown locale → en; language names without ICU (`displayLanguage('en','is') == 'enska'`) |
| `tests/language-settings.test.mjs` | missing voice requires install or text-only; interface-only change saves with a missing voice; multilingual limits; custom name cannot inject instructions; CJK/Arabic/Hindi sentence boundaries |
| `tests/interface-theme.test.mjs` | migration of old custom themes; accent/background independence |
| `tests/settings-location.test.mjs` | restore last tab + per-section scroll; only known sections/bounded offsets; corrupt/oversized/unavailable storage tolerated |
| `tests/settings-window.test.mjs` | inherits/follows pin state; presentation waits for content; hide cancels presentation; latest navigation intent sent once; context shortcut focuses the right control only once; visibility events |
| `tests/settings-confirmations.test.mjs`, `tests/desktop-polish.test.mjs` (first test) | restart confirmation cannot approve another request; read delay respected; draft writes flushed before confirmations; failed draft writes keep draft and release barrier; expired approval closes UI and rejects late confirm; cancellation during saving never resurrects; destructive confirmations accept only the active request |
| `tests/desktop-boundaries.test.mjs` | IPC sender trust and settings-channel restrictions → in Rust: Settings command subset cannot express capture/chat/avatar commands (compile-time) |
| `tests/update-notification.test.mjs` | semver tag validation, single-flight update/later, dismissal per run, retry after failure, locale refresh |
| `tests/memory-monitor.test.mjs` | invalid readings rejected, per-GPU pressure, AMD capacity without usage, two-sample warnings and dismissal until recovery, interval validation, toggle semantics (`setMonitorDisplay`), sparkline gaps, context uses last-request only |
| `tests/inference-picker.test.mjs` | residency labels; residency only on active local row; choices expose no secrets; local switch only when installed+configured else open models; cancellation; busy/unavailable/current never switch |
| `tests/internet-mode.test.mjs`, `tests/thinking-mode.test.mjs`, `tests/thinking-privacy.test.mjs` | boolean-only host calls, single-flight, rollback on error, only known phases/notice texts, bounded plain-text preface/approach, reset on terminal events, sources open by `{turnId,index}` only |
| `tests/clipboard-files.test.mjs`, `tests/attachment-viewer.test.mjs` | text/HTML ignored, names sanitized, payload bounded before allocation; viewer is isolated, on the owner display, and late loads cannot show |
| `tests/inference-api.test.mjs` (key/endpoint parts), `tests/models-panel-actions.test.mjs`, `tests/music-listening-panel.test.mjs`, `tests/community-links.test.mjs`, `tests/personality.test.mjs` | API key normalization/validation; local model one-click flow and blockers; music labels; fixed community origins; personality reset/empty file semantics |
Behavioural verifiers worth re-creating as egui/X11 integration tests (`tools/verify/`): `verify-settings-layout.mjs` (every section fits without horizontal overflow, unique group icons, accent vs background theme independence, draft bar fits header), `verify-settings-first-open.mjs`, `verify-settings-lifecycle.mjs`, `verify-settings-reset.mjs`, `verify-conversation-layout.mjs` (history page bounds and unobstructed close), `verify-interface-locales.mjs` (all locales render and persist), `verify-text-selection.mjs`, `verify-composer-focus.mjs`, `verify-reply-navigation.mjs`, `verify-reply-tab.mjs`, `verify-button-feedback.mjs`, `verify-inference-picker.mjs`, `verify-thinking-mode.mjs`, `verify-internet-mode.mjs`, `verify-attachments.mjs`, `verify-window-dimming.mjs`, `verify-credits.mjs`, `verify-speech-subtitles.mjs`.
### 11.2 New Rust tests
- Golden palette tests: all presets + boundary custom values → exact colours (UI-80).
- `panel_path` and hit-region merge (containment removal, ≤ 32 cap) property tests.
- Send enablement truth table (UI-05) and Esc priority chain (UI-31) as pure-state tests.
- Composer keyboard via `egui_kittest`: Enter sends, Shift+Enter inserts newline, Enter during IME preedit does nothing, 8000-unit limit.
- Draft engine: dirty detection, close → bar → Save keeps window open, Discard closes and reloads revisions, apply failure stops and navigates, external change while dirty → deferred + notice, revision mismatch error text.
- Search ranking table (exact/substring/word match, section entries dropped when controls match, Cyrillic `ё` folding, Turkish lowercase).
- i18n: template reverse-matching with language substitution; every catalog key with placeholders round-trips; RTL direction drives layout mirroring of settings panels only.
- Smoke-render every settings section in all 50 locales at 400 px and 680 px widths (no panic, no text overflowing panel width beyond wrap).
- AccessKit tree snapshot of companion and settings (roles, labels, toggled/pressed/expanded states).
- Linux integration (CI with Xvfb + i3, manual on KDE): Settings docks inside the work area on both sides; viewer goes fullscreen on the companion monitor; input shape passes clicks through outside regions; portal/GTK dialog fallback.
---
## 12. Open questions
1. **Complex-script text rendering.** egui's built-in text layout historically has no OpenType shaping or bidi; ar/he/fa/ur (RTL), Indic scripts (hi, bn, ta, te, mr, gu, pa) and Thai need shaping. Verify the egui version chosen; if insufficient, options are a cosmic-text/parley-based text path, another toolkit (iced uses cosmic-text) for the Settings window, or shipping those locales later with English fallback. This is the main UI risk.
2. **Windows-specific catalog strings** (e.g. "Windows logical pixels", "Windows Recycle Bin", "Windows AppContainer", "Windows is locked", "Restart Windows…", VB-CABLE, Notepad/Calculator, "Only supported Windows apps are available"): add Linux-specific keys (translated with the existing pipeline `tools/localization/translate-interface.mjs`, which needs Node + local Qwen) or accept English fallback for new keys?
3. **Which capability sections exist on Linux** (Notepad/Calculator grants, Spotify desktop control, VB-CABLE call setup, user tools sandbox wording, Recycle Bin) — hide, relabel, or keep with "unavailable on this platform" states? Depends on the actions/voice specs.
4. **Legacy in-companion panels**: confirm they can be dropped entirely (current behaviour always redirects to Settings).
5. **Native help popup**: inline-only on Linux acceptable?
6. **i3 without a compositor**: is an opaque companion acceptable, or should the app require picom? Should Capri ship an i3 `for_window` snippet?
7. **KDE fractional scaling for XWayland**: require "Apply scaling themselves", or support compositor-scaled mode in positioning math?
8. **Revision tokens**: keep sha256-of-JSON (cross-process semantics) or switch to monotonic counters now that UI and core share a process?
9. **Variable font weights**: commit generated static Exo 2 instances (OFL permits; keep notices) or require a variation-capable rasterizer?
10. **Attachment media decoding** (PDF text, video frames) is done in the renderer today (pdf.js, HTMLVideoElement): Rust replacements (`lopdf`/`pdf-extract`, ffmpeg CLI) belong to the attachments spec — confirm ownership and whether mp4/webm support stays in v1.
11. **Numbering system for ar/fa/ur** (Arabic-Indic vs Latin digits) — Chromium followed CLDR defaults; confirm ICU4X output is the desired look.
12. **Global shortcut and tray on i3** (XEmbed tray, no global shortcut API) — owned by the window/tray spec but affects UI texts ("Bring it back from the system tray").
13. **Settings location storage**: new JSON file location acceptable (`data/desktop/settings-location.json`)?