# 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//thumb.png` (lazy), expand icon, name (``, 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//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 (`` 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 `