# 10 — Orchestrator, lifecycle, companion state machine and UI↔core protocol (ORC) Status: behavioral specification extracted from CapriCore 1.0.4 source (GPL-3.0-only) for a pure-Rust Linux rewrite (KDE Plasma 6.8 Wayland+XWayland, i3 4.25 X11). Code is the source of truth; doc/code disagreements are listed in §12. All paths are relative to the Capri install root (`root`) unless prefixed `DS/` (= `root/data/desktop`, the desktop state directory) or `RUN/` (= `root/data/run`). --- ## 1. Purpose and scope The orchestrator is the Electron main process of Capri. It owns process lifetime, constructs and wires ~60 services, holds the global companion state (backend phase, power phase, window mode, active turn, locks), arbitrates every user/UI command, routes all events to UI surfaces, owns every window, the tray and global shortcuts, and implements the end-to-end request flow glue (input → local intercepts → chat/visual/clip turn → TTS → subtitles/mouth → follow-up listening). ### 1.1 Files owned by this spec (read in full) | File | Lines | Role | |---|---|---| | `apps/desktop/main.mjs` | 7095 | Entire orchestrator: bootstrap, wiring, state, IPC handlers, windows, tray, shutdown | | `apps/desktop/main/ipc.mjs` | 61 | IPC admission gate + revision-checked settings writes | | `apps/desktop/main/companion-ipc.mjs` | 203 | Companion settings, personality, wake audio, resets, bug report channels | | `apps/desktop/main/settings-channels.mjs` | 143 | Allowlist of channels callable from the Settings window | | `apps/desktop/main/protocol.mjs` | 53 | `capri://` resource responder + CSP | | `apps/desktop/preload.cjs` | 244 | `window.capri` bridge (companion and Settings) | | `apps/desktop/avatar-composer-preload.cjs`, `minimized-chip-preload.cjs`, `recording-indicator-preload.cjs` | 20/14/13 | Bridges of the auxiliary windows | | `apps/desktop/renderer/app.js` | 3184 | Companion renderer: event consumer, send/stop, subtitles, presence, regions | | `apps/desktop/renderer/settings-api.mjs` | 47 | Settings draft-save barrier + revision bookkeeping | ### 1.2 Files read because the orchestrator directly drives them (behavior summarized here, detailed elsewhere) `main/screen-ipc.mjs`, `main/access-ipc.mjs` (channels registered by main), `main/secure-window.mjs`, `main/settings-window.mjs`, `main/minimized-chip.mjs`, `main/avatar-composer.mjs`, `main/avatar-composer-bridge.mjs`, `main/control-overlay.mjs`, `main/control-window-layer.mjs`, `main/window-topmost.mjs`, `main/tray-only-windows.mjs`, `main/attachment-viewer.mjs`, `main/confirmations.mjs`, `main/startup-intro.mjs`, `main/linux-cursor.mjs` (FWS-LINUX-BRIDGE), `main/pointer-controller.mjs`, `main/resources.mjs`, `main/localized-dialog.mjs`, `main/avatar-settings-window.mjs`, `main/call-audio.mjs`, `main/screen-form-state.mjs`, `main/avatar-detach.mjs` (window options only); `sleep-service.mjs`, `model-startup.mjs`, `startup-progress.mjs`, `preferences.mjs`, `storage.mjs`, `avatar-state.mjs`, `voice-follow-up.mjs`, `gateway-rpc.mjs`, `voice-residency.mjs`, `companion-settings.mjs`, `inference-startup.mjs`, `geometry.mjs`, `desktop-avatar-commands.mjs`, `clip-command.mjs`, `native-escape-stop.mjs`; flow-level only: `chat-service.mjs`, `request-router.mjs`, `conversation-route.mjs`, `task-route.mjs`, `tool-loop.mjs`, `turn-context.mjs`, `voice-service.mjs`, `microphone-service.mjs`, `action-broker.mjs` (approvals), `renderer/presence-model.mjs`, `renderer/subtitle-controller.mjs`, `renderer/reply-pages.mjs`, `renderer/reply-visibility.mjs`, `renderer/voice-player.mjs`, `renderer/avatar-mouth.mjs`, `renderer/microphone.mjs`, `renderer/settings-registry.mjs`; runtime: `packages/runtime/src/providers/core.mjs`, `desktop-launcher.mjs`, `host/launch-receipt.mjs`, `hardware/responsiveness.mjs`, `atomic-json.mjs`; Linux helpers `integrations/desktop-actions/native/linux/capri_linux/{cursor,escape,kwin,x11,main}.py`. ### 1.3 Out of scope (owned by other specs; only the orchestrator contract is given here) Prompt engineering and tool loop internals of the chat route, OpenClaw gateway/Ollama process management, ASR engine and wake-phrase gate, TTS engine, avatar animation director and detached-avatar rendering, screen capture/observation, computer-control executor, file/application/Spotify tools, memory/Brain/private memory, initiative/awareness, updates/installer, Hugging Face/model catalog, credentials storage, diagnostics report contents, localization tables. --- ## 2. Feature catalog Priorities: **P0** companion broken without it; **P1** expected by a Capri user; **P2** optional/niche. Line numbers refer to `apps/desktop/main.mjs` unless another file is named. ### ORC-01 — Process bootstrap and state roots (P0) - Synchronous, before the UI toolkit is ready (main.mjs:297-332): - `verification = argv.includes('--verification')`. In verification mode `CAPRI_DESKTOP_VERIFICATION_DIR` must resolve inside `root/.runtime/` else throw `Verification state must be inside this project’s .runtime directory`. State dir = `$DIR/desktop`, otherwise `DS` (`root/data/desktop`). - App name `Capri` (or `Capri Verification`). Windows-only AppUserModelID `Overyx.Capri.`. - Chromium userData/session → `DS/profile`, crash dumps → `DS/crashes` (Electron-only; Rust: keep `DS/crashes/` for panic reports). - Register privileged scheme `capri` (standard, secure, fetch, CORS) — see ORC-43. - Every created window gets icon `assets/default/icon-source.png`; every window is forced `skipTaskbar` on show/hide/minimize/restore (ORC-11). - After toolkit ready: Linux bridge `installLinuxCursor(screen)` (KDE Wayland only, §8.2), then `initializeDesktop()` (ORC-03). Any rejection → ORC-10. ### ORC-02 — Single instance and external show/stop channel (P0) - Single-instance lock; a second process exits with code 0 immediately. Primary on `second-instance`: `restoreCompanion()` (= clear focus mode and avatar-only, show + focus + `focus-input` event) (6795). - The CLI launcher (`capri desktop`, `packages/runtime/src/desktop-launcher.mjs`) refuses when `.runtime/updates/active.json` exists, when arch ≠ x64, when `config/core.local.json` is missing; if a managed `desktop` process exists it writes `RUN/desktop.show` = `{"show":true,"launchNonce":}` and reports `alreadyRunning`; otherwise deletes stale `RUN/desktop.stop` and `RUN/desktop.show`, unsets `ELECTRON_RUN_AS_NODE`, and starts Electron with `--ozone-platform=x11` on Linux (forces XWayland). - Control poll every **400 ms** (`controlTimer`, 6994-7019, unref'd; the two file checks are skipped in verification): - `RUN/desktop.stop` exists → unlink → `app.quit()` (goes through ORC-09 only; services are stopped by the CLI `stop` command, not by the desktop). - `RUN/desktop.show` exists → read `launchNonce` (ignore parse errors) → unlink → `restoreCompanion()` → `publishLaunchReceipt(root, nonce)`. - Launch receipt (`host/launch-receipt.mjs`): only if nonce matches `^[a-f0-9]{32}$`; refuses if any ancestor of `RUN` is a symlink or target exists and is not a regular file; writes atomically `RUN/launch-.json` = `{schemaVersion:1, nonce, phase:"window-ready", pid, at:}`. Also published once on first `ready-to-show` with env `CAPRI_LAUNCH_NONCE`. ### ORC-03 — Startup sequence and service wiring (P0) Ordered; "await" = blocking. Source main.mjs:333-4212 (construction) and 6862-7068 (ready phase). 1. Response-timing log → `logs/response-desktop.jsonl` (bounded 512 KiB, rotate to `.1`). 2. Runtime context `rt` (gateway port, URLs, token path, workspace, logPrefix `capri`). Verification overrides: stateDir `$DIR/openclaw`, workspace `$DIR/workspace`, gatewayPort `CAPRI_DESKTOP_VERIFICATION_PORT` (default 18790), logPrefix `desktop-verification`. 3. **await** legacy private storage key (`DS/private-data-key.json`, OS-sealed) — used only to open legacy sealed transcripts. 4. InferenceApi (external OpenAI-compatible provider profiles, credential store, loopback proxy). `rt.remote = inferenceApi.config`; model-selection diagnostic log; `npuDialogue` = remote endpoint is a Lemonade NPU endpoint; `screenVisionAvailable = remote ? remote.vision : (!modelCapabilities || includes 'vision')`. 5. `rt.inferenceUrl = remote ? http://127.0.0.1:(gatewayPort+2) : ollamaUrl`. Auxiliary runner params `{num_ctx: contextTokens, ...local runner options}` (frozen). 6. Validate `gatewayPort` integer 1024..65535 else throw `Invalid local Gateway port`. mkdir `DS`, `DS/profile`, `DS/crashes`; `initialize(rt)` (runtime config files). 7. Avatar catalog load (`loadInstalledAvatar`), startup intro pack (if animated), `StartupIntroGate`; restore `DS/presence.json`, `DS/dimming.json`, `DS/avatar-layout.json`, `DS/avatar.json` (each read only if < 4096 bytes and `schemaVersion===1`); `AvatarState`; alpha-mask LRU (max 20 entries). 8. Window prefs `DS/window.json` with migration (ORC-12). `TranscriptStore(DS/transcript.json)`; `AttachmentHistory(DS/conversation-attachments)` + immediate prune. 9. Preferences objects (ORC-§4): companion, inference-startup, computer-control, voice-effects, languages, applications, initiative, music-listening, call-audio, screen-observation, speech, discord-presence; `Confirmations`; GitHubAccess; UpdateService; SpeechInstallService; HF credentials/hub/service; ModelService; ModelDeviceService; DeveloperDiagnostics; VoiceCatalogService; VoiceTrainingService; Spotify worker/settings; StartupProgress; ApplicationAccess; BrainKnowledge; PrivateMemory; UserTools; FullComputerAccess; FilePermissions; AudioInputSettings; call reply generator. 10. ScreenshotFiles (`data/screenshots`), `DS/last-screenshot.json`; RequestRouter; `responsiveness()`; WebSearch; **ChatService** (wiring in ORC-25). 11. Voice: `voiceEnabled=false` (speech is opt-in per session; only verification with `CAPRI_DESKTOP_VERIFICATION_VOICE=1` reads `DS/voice.json`); `voiceAvailable = companionVoiceInstalled()`; VoiceService(url, headers, enabled = allowed && enabled, language = available ? resolved speech language : 'off'). 12. ASR config from `config/companion-asr.json` (mutated in memory: trailingSilenceSeconds from `DS/speech.json`, language from languages prefs); MicrophoneService(ASRWorker) with `interrupt` = chat.cancel + cancelVisual + voice.cancel and `submit` = wait for current task then `submitMessage(value,'microphone')`. 13. SystemAudioCapture, MusicListeningService, MusicAudioCapture, VirtualCableInstaller, CallAudioSetup (all Windows-gated), initiative budget `DS/initiative-state.json` (<16384 B), WindowsObserver, **CompanionRpc** (gateway WebSocket metadata client), DiscordPresence, ContextSampler, ScreenCapturePolicy, ScreenObservation, ScreenClipFrames, VisualService, AttachmentDrafts, AttachmentViewer, InitiativeService, AvatarClickReactions, MutedVoiceResidency, **SleepService**, IPC factory, DesktopCatalog, NativeEscapeStop (win32+linux), **ComputerControl**, ComputerAgent, ComputerRequests, TaskWorkflows, Escape `before-input-event` hook, **CompanionActions** (approvals broker, time, files, apps, Spotify), TimeConversation, ReminderDelivery → `reminders.start()`. 14. Register `second-instance`, `before-quit` (ORC-09), `window-all-closed` → quit. 15. Ready phase (async): `brain.start()` (not in verification); **await** `userTools.refresh()` (on failure warn `User tools could not be listed. Open Settings to retry.`); install permission handlers (ORC-42); register `capri` protocol handler; **await** `companionActions.start()`; `installIpc()` (all handlers); `preload = consumeFirstLaunchPreload(DS)`; `createWindow()` (ORC-11, also creates detached-avatar controller, composer, chip, recording indicator, settings host, pointer controller, tray, global shortcut, display listeners, starts loading the renderer). 16. First-run routing (ORC-50); `discordPresence.start()`; window `minimize` → resetCallAudio; power monitor handlers (ORC-41); window `show` → `syncInitiative()`; start `controlTimer` (ORC-02/ORC-53). 17. Model services (ORC-04) **await** `startModelServices(...)`; `startup.finish()`; **await** `syncInitiative()` (error other than AbortError → event `initiative.error` "App awareness could not start."). 18. Any exception in 15-17 → `Desktop startup failed: ` on stderr and `app.exit(1)` (no dialog). - Companion window `ready-to-show` (6753): show inactive (not in verification), publish launch receipt, `updates.checkOnStartup()` (errors ignored), log bounds. ### ORC-04 — Model warmup scheduling and startup progress (P0) - `consumeFirstLaunchPreload` (`model-startup.mjs:6-21`): `DS/first-start.json` = `{schemaVersion:1, preloadModels:boolean}` written by the installer wizard; missing/invalid → `true`; valid → delete the file (warn if deletion fails with error ≠ ENOENT) and return the value (one-shot). - Startup stages list = `core` + (`models` if preload) + (`recognition` if preload ∧ !verification ∧ ASR allowed ∧ installed ∧ microphone capture active ∧ language≠off) + (`voice` if preload ∧ !verification ∧ voice.enabled ∧ language≠off). Because voice is disabled and the microphone is off at process start, a cold start only warms `core`/`models`; voice/recognition warm only on wake (ORC-06). - `startModelServices({core, recognition, voice, sequential, voiceFirst, shouldContinue})`: voiceFirst → run voice alone first, stop with `Model startup cancelled` if `shouldContinue()` false, then the rest; `sequential` (low-memory) → run core, recognition, voice in order, break when core rejected or `shouldContinue()` false; else all in parallel (allSettled). Result order `[core, recognition, voice]`. `shouldContinue = !shuttingDown && power ≠ 'sleeping'`. - Each optional stage is wrapped: `begin(key)`, on success `end(key)`, on error `end(key, true)` (errors swallowed; text chat stays available). - `StartupProgress` (`startup-progress.mjs`): per stage `{state: waiting/running/ready/failed, estimate, started?}`; estimate seconds = previous measured duration (clamped 1..600) else defaults `core 15, models 12, recognition 8, voice 25`; measured durations (seconds, float, ≥1) saved to `DS/startup-times.json` at `finish()`; every change emits `startup.progress` `{started, stages:[{id,state,estimate,started?}], finished}`. - Timing budgets (`hardware/responsiveness.mjs`): `lowMemory` = total RAM ≤ 17 GiB; `memoryPressure` = free RAM < 6 GiB at launch; `slow` = lowMemory ∨ pressure ∨ resourceProfile `minimal` ∨ acceleration `cpu`. `sequentialModels = lowMemory ∨ pressure`; `firstTextTimeoutMs = slow ? 120000 : 30000`; `timeoutMs = slow ? 300000 : 180000`; `agentWarmupTimeoutMs = slow ? 180000 : 60000`. ### ORC-05 — Backend connection state machine (P0) - `backendState = {phase, message}`; every change logs `Capri local core: ` and emits `backend` (2337-2341). | Phase | Typical message | Set by | |---|---|---| | `starting` | `Starting local core…` / `Updating shared memory…` / `Preparing Spotify integration...` | connectBackend, memory reset, Spotify switch | | `ready` | `Ready` | connectBackend success | | `offline` | `The local core is unavailable. Reconnect to try again.` / `Choose a language model in Settings → Language model.` / `API connections` / Ollama bundle message / restart rollback `Reconnect to try again.` / `Some services could not be stopped. Use stop.cmd or try again.` / `Some models could not be unloaded. Reconnect to try again.` | failures | | `sleeping` | `Freeing model memory…` | sleep unload | | `asleep` | `Sleeping. Send a message to wake Capri.` | sleep done / failed wake | | `stopping` | `Stopping Capri and freeing model memory…` or restart message | quit / restart | - `connectBackend({preload=true})` (2439-2495): returns silently if voice training busy; offline gates for model setup / API setup (messages above); throws `Capri is shutting down` when shutting down; concurrent calls share one promise. Body: `starting` → if preload and not (remote ∧ `skipLocalModelOnApi`) start the request router in background → await muted-voice release → await `inferenceApi.start(gatewayPort+2)` → first time in remote mode stop an already running managed gateway once (so it restarts with the remote config) → `startCore(rt + remote merged with inference-startup prefs, {signal, voiceExpected: voice.enabled∧language≠off, voiceReady, preload, onStage})` → `ready`. Error → offline (unless sleeping/shutting down) with the error message only for `CAPRI_OLLAMA_BUNDLE_INCOMPLETE`, else the generic message; rethrow. Abortable via `backendController`. - `startCore` order (`packages/runtime/src/providers/core.mjs`): Ollama → (remote ∧ skip-local ∧ model≠embedding: unload resident chat model via `/api/generate keep_alive:0`, 30 s) → ensure native model (local) → ensure embedding model → verify inventory (`Model is missing. Run scripts/pull-models.mjs.`) → gateway → stage `core` ready → if preload: prewarm (`/api/chat` "Hello." `num_predict:1`, `/api/embed`, 180 s each, skipped if already resident with matching context) + agent warmup once per gateway pid (`data/run/.primed.json`) → stage `models` ready/failed. - Post-turn health check: if the last stored message has status `error`, GET `{gatewayUrl}/v1/models` with gateway auth headers, timeout 2000 ms; failure → offline generic message (1305-1313). - Reconnect entry points: tray `Reconnect` (enabled iff no connect in flight ∧ not shutting down), `window-action reconnect`, `capri:reconnect` (throws `Wait for the current reply to finish.` if a chat turn is active; wakes if power ≠ awake else connects), avatar tap while sleeping/offline (ORC-56). ### ORC-06 — Sleep / wake (P1) - Power phases (`sleep-service.mjs:34-117`): `awake`, `sleeping`, `asleep`, `waking`, `notifying`, `voice-awake`. Each change emits `power.state {phase}` (suppressed after `close()`). | From | Trigger | To | Notes | |---|---|---|---| | awake | `sleep()` | sleeping → asleep | unload failure → awake + rethrow | | asleep | `sleep()` | asleep | no-op | | sleeping | `sleep()`/`wake()` | — | joins pending, then re-evaluates | | waking/notifying | `sleep()` | — | waits pending, then sleeps | | asleep / voice-awake | `wake()` | waking → awake | reload failure → asleep + rethrow | | awake/voice-awake | `wakeForReminder(fn)` | — | runs fn directly | | asleep | `wakeForReminder(fn)` | notifying → voice-awake | fn failure → asleep | | any | `close()` | — | all further calls throw `Capri is shutting down` | - `unload` (2345-2379): cancel workflows; lock private memory; stop music listening; cancel click reactions; reset call audio; `backend=sleeping`; abort backend start and voice start; clear voice preview & pending follow-up; cancel chat & visual; clear screen capture/previews + `screen.reset`; cancel initiative; stop observer; stop gateway RPC; close voice; router pause; close ASR worker unless the microphone is capturing (an enabled mic stays available for wake); await pending backend/voice starts; `stopCore(rt,{companion:false})` (voice + gateway concurrently, then Ollama); failure → `offline` "Some models could not be unloaded…" + rethrow; `startup.finish()`; `backend=asleep`. - `reload` (2380-2435): throw if shutting down; warmVoice = voice.enabled ∧ language≠off; warmAsr = ASR allowed ∧ installed ∧ capturing ∧ language≠off; `startup.start(['core','models',voice?,recognition?])`; `startModelServices(core: connectBackend, ...)`; core rejected → abort voice, close voice, router pause, close ASR worker if not capturing, stopCore, `backend=asleep`, rethrow; then `syncInitiative()`; finally `startup.finish()`. - Sleep command (`isSleepCommand`, 18-31): NFKC, lowercase, normalize quotes, strip leading `hey/эй`, `capri/капри` + punctuation, strip `please/пожалуйста`; exact match of: `sleep | go to sleep | you can (go to )?sleep | (it's |it is )?time to (go to )?sleep | take a nap | get some rest | иди спать | иди поспи | ложись спать | (тебе )?пора спать | можешь (идти спать|поспать|отдохнуть) | отдыхай`. Handled in ORC-24. - Any other input while not awake first awaits `sleepService.wake()` (1279). Quit dialog choice `Sleep` and `window-action sleep` (confirmation `Unload models and sleep?`) also sleep. - `visuallySleeping(power, backend)`: false if power ∈ {notifying, voice-awake}; true if power ∈ {sleeping, asleep} or backend ∈ {offline, stopping}. `avatarTapsSleeping` additionally true for power `waking` or backend ∈ {sleeping, asleep}. - Sleep caption (renderer): `sleepCaption(ms)`: tick = floor(ms/500); mask = floor(tick/3) % 8; three letters, bit i set → `Z` else `z`, then 1-3 dots (`tick % 3 + 1`). ### ORC-07 — Quit and unload (P0) - Entry: close button (`capri:quit`), tray `Quit and unload models`, `window-action quit` (3398-3464). - Guards: no-op if already shutting down; if the VB-CABLE installer is busy throw `Wait for VB-CABLE setup to finish before closing or restarting Capri.`; await `computerControl.stop()`. - Confirmation (multi-choice, ORC-20): title `Quit Capri?`, detail `Capri will close and unload the local models. Any active reply will stop.`, choices `cancel: Cancel`, `sleep: Sleep`, `restart: Restart`, `confirm: Quit and unload models (danger)`. - cancel → return; sleep → `sleepService.sleep()`; restart → ORC-08 `shutdownForRestart('Preparing to restart Capri...')` + relaunch + quit (on error: `shuttingDown=false`, offline `Reconnect to try again.`, rethrow). - confirm → `shuttingDown=true`; close attachment viewer; clear drafts; detached avatar keeps showing but stops pointer handling (so it can display DISCONNECTING) else reset; destroy Settings; close sleep service and reminders; abort backend/voice start; cancel visual; clear capture/previews; close initiative; stop observer and RPC; cancel chat; close voice and microphone; close router; `backend=stopping "Stopping Capri and freeing model memory…"`; await pending backend/voice/sleep; `stopCore(rt,{companion:false})` (verification: stop its gateway only); await speech installer close; `app.quit()`. On failure: log `Shutdown failed:`, `shuttingDown=false`, restart avatar pointer, offline `Some services could not be stopped. Use stop.cmd or try again.` - Window close request (any OS close) while not quitting → hide to tray instead (6734-6742). ### ORC-08 — Restart-to-apply flows (P1) - `shutdownForRestart(message)` (3361-3396): await computer stop; `shuttingDown=true`; close viewer/drafts; reset detached avatar; destroy Settings; await speech installer, voice training, voice catalog close; HF close; sleep service & reminders close; abort backend (`Startup cancelled for restart`) and voice start; cancel visual; clear capture; close initiative, observer, RPC; cancel chat; close voice, microphone, router; `backend=stopping `; await pending; stopCore. Failure → `shuttingDown=false`, offline `Reconnect to try again.`, rethrow. - `queueDesktopRelaunch()`: relaunch `root/Capri.exe` if present else `node packages/runtime/bin/capri.mjs desktop` (Rust: re-exec current executable with the same args after shutdown; see §10). - Callers (each confirms first via ORC-20, re-checks idleness after the dialog, rolls back files on failure, then quits): | Command | Confirmation title / button | Applies | Rollback | |---|---|---|---| | quit dialog `restart` | (choice) | — | — | | `capri:models-apply` | `Switch language model?` / `Switch model and restart` | `saveModelProfile` (forces local), deselect API profile if one was active | `change.restore()`, rewrite previous API selection | | `capri:context-apply` (tokens) | `Context window` / `Apply and restart` | `saveContextWindow` | `change.restore()` | | `capri:model-devices-apply` | `Model devices` / `Save and restart Capri` | `modelDevices.save` + `saveInferenceSettings({acceleration: language==='cpu' ? 'cpu' : 'auto'})` | both restore | | `capri:inference-api-save` (active profile) | `Change AI provider?` / `Apply and restart` | save profile + select | rewrite/delete previous profile & settings files; `AggregateError` if rollback fails | | `capri:inference-api-use` (id or null) | `Change AI provider?` / `Apply and restart` | select profile | rewrite previous API settings | | `capri:spotify-access` | `Enable/Disable Spotify control?` / `Enable and restart` or `Disable and restart` | spotify.setEnabled with beforeCommit = shutdownForRestart | restore previous backend state or offline message | | `capri:update-install` | see ORC-49 | update | — | - Common details in §6.2. Restart flows refuse in verification mode with `… disabled in desktop verification.` messages. ### ORC-09 — `before-quit` cleanup and persistence flush (P0) Synchronous, in order (6796-6860): destroy recording indicator; close user tools, workflows, private memory, Brain; destroy minimized chip; close attachment viewer; clear drafts; stop music; **if VB-CABLE installer busy → cancel the quit and quit again once it settles**; reset call audio; hide teleport menu; cancel click reactions; reset detached avatar; destroy composer; resolve all pending composer actions with `false`; stop process/CPU samplers; close inference proxy, Discord presence; stop computer control; close companion actions (approval broker), sleep service, reminders, Spotify; abort backend (`Desktop closed during startup`) and voice start; close models, HF, voice training/catalog, updates, GitHub, speech installer; cancel confirmations; cancel visual; clear capture; close initiative, observer, RPC; `quitting=true`; destroy Settings; cancel chat; close voice, microphone, router; **save window, avatar layout, dimming** (bypassing debounces); stop pointer polling; clear timers; unregister all global shortcuts; destroy tray. `window-all-closed` → quit. ### ORC-10 — Fatal startup failure dialog (P0) If `initializeDesktop()` rejects (7079-7094): stderr `CAPRI_DESKTOP_INIT`; read `DS/languages.json` (`settings.interface` or legacy top-level `interface`, default `en`); show a modal error box titled `Capri could not start.` with body `Your saved data has been preserved. Repair Capri with the installer and try again.` (both localized); exit code 1. ### ORC-11 — Companion main window (P0) - Size **480×660** DIP; frameless; transparent background; not resizable/maximizable/minimizable/fullscreenable; created hidden; skip taskbar; always-on-top = `window.json alwaysOnTop !== false` (default **on**); focusable (not in verification); no shadow; no menu; title `Capri`; navigation, `window.open`, webviews denied; F5 and Ctrl+R swallowed (`main/secure-window.mjs`). - Click-through: the window starts mouse-transparent; a 16 ms poll (`main/pointer-controller.mjs`) reads the global cursor and makes the window interactive only when the cursor is over one of the renderer-published control rectangles, over the opaque part of the sprite (alpha ≥ 16 within a 12-px padded visible box, CRT lens aware), or during a drag/press. Regions arrive via `capri:regions` (≤32 control rects, sprite rect with optional `enabled`, `source` crop (unit box), `lens {rect, curve 0..0.06}`, optional `footprint`); rects must lie inside the window (+2 px tolerance) (`geometry.mjs:124-177`). - Placement: saved position clamped into the matching display work area; default bottom-right of the primary work area with a 16-px margin (`placeInWorkArea`). When a compact `footprint` (visible sub-rectangle) is published, the window may extend off-screen as long as the footprint stays inside the work area (`placeVisibleInWorkArea`); `compactPlacement` remembers where the footprint was after a drag. - Window drag: renderer title handle → `capri:drag-start/-end`; the 16 ms poll moves the window by cursor delta using `setBounds` (size preserved, no call when unchanged), clamps the footprint on the cursor display; gesture expires after 30 s; blur ends drags; on end clamp to work area, update `compactPlacement` if moved, save. - Display changes: `display-removed` → capture topology change, reset detached avatar, clamp; `display-added` → topology change; `display-metrics-changed` (bounds/scaleFactor/rotation) → topology change, reset avatar, clamp unless dragging. `moved` → avatar display check + save debounced **350 ms**. - Always-on-top changes made outside the control layer emit `window.always-on-top {active, preview?}`. `ControlWindowLayer` (`main/control-window-layer.mjs`) temporarily demotes the window (and moves it to the bottom) during computer control without changing the saved preference; `end()` restores the latest saved/preview preference. - Renderer console warnings/errors (level ≥ 2) are kept in a 50-entry ring (`rendererDiagnostics`, message ≤4000, source ≤300) for diagnostics. ### ORC-12 — Window persistence and migration (P1) - `DS/window.json` v3 = `{schemaVersion:3, x, y, footprint?, compactPlacement?, alwaysOnTop}` (undefined fields omitted). Read at start; v1 → `x += 380-480; y += 680-660`; v2 → `x += 460-480; y += 580-660` (keeps the bottom-right anchor of older panel sizes). `footprint` kept only if it validates against 480×660; `compactPlacement` kept if integer coords |v|<2³⁰ and valid size. - Written by `saveWindow()` after move (350 ms debounce), drag end, always-on-top change, reset position, quit; settings reset writes `alwaysOnTop:true`. Write failure → console only (`Could not save companion position`). ### ORC-13 — Visibility modes: tray, chip, focus mode, avatar-only (P0 hide/restore, P1 rest) State flags: `focusMode`, `avatarOnly`, window visible/minimized, `sessionLocked`, `shuttingDown`, `quitting`. `companionPresent() = window alive ∧ (visible ∨ avatarOnly)`. - `hideCompanionToTray()` (2594): `avatarOnly=false`; hide window; if it was already hidden run `stopHiddenCompanion()`; unless focus/locked/shutting/quitting and if `companion.minimizedChip !== false` show the minimized chip. - Window `hide` → `stopHiddenCompanion()` (2577): skipped when avatarOnly; else clear perch, cancel click reactions, reset detached avatar, hide teleport menu, hide Settings, stop computer control, stop samplers; (non-verification) discard screens (`companion-hidden`), cancel initiative, stop observer. Window `minimize` → hide to tray + stop samplers + reset call audio. Settings follows owner hide/minimize. - `showCompanion(focus=false)` (2627): no-op in focus mode/avatar-only/destroyed; hide chip; if renderer failed → recovery (ORC-40); restore if minimized; focus → show + focus + emit `focus-input`; else show inactive. - `restoreCompanion(focus=true)`: clear focusMode/avatarOnly, show, emit `window.focus-mode {active:false}` if it was in focus mode. - `collapseCompanionInterface()` (`capri:hide`, 2609): attached avatar → hide to tray (true); detached avatar available → (release a Settings-window perch first) `avatarOnly=true`, hide window, keep the desktop avatar (true); otherwise false. - Focus mode (`enterFocusMode`, 3166): hide chip; set flag; hide Settings; hide to tray; emit `window.focus-mode {active:true}`. Wake phrase and replies do not reveal the window while in focus mode; voice/mic keep running. Exit: tray click, tray `Show Capri`, Ctrl+Shift+Space, `window-action focus-mode false`. Not persisted (ends on exit). - Wake auto-reveal: event `microphone.wake` that is neither manual nor follow-up, with `companion.restoreFromTrayOnWake` true, not locked/shutting/quitting and window hidden → `showCompanion()` (inactive) (2216-2228). - Minimized chip (`main/minimized-chip.mjs`): 52×52 always-on-top frameless transparent restore button, bottom-right of the primary work area (16 px margins) or its remembered (session-only) position; click → `capri:chip-restore` → hide chip + `restoreCompanion()`; drag via `capri:chip-drag` actions `start/move/end/cancel` (4-px threshold, 30 s gesture limit, clamped to the display under the cursor); display changes cancel drags and re-place; labels pushed on `capri:chip-labels` `{title:'Show Capri', language, accent, background}`; hidden on lock/suspend/focus. ### ORC-14 — Tray icon and menu (P0) - Icon: Linux `assets/default/icon-source.png` (Windows `app.ico`) (6769). Initial tooltip `Capri desktop companion`. Tooltip recomputed on `microphone.settings`, `initiative.status`, `languages`: `"Capri — " + join(", ", [mic capturing ? "Microphone ()", awareness active ? "App awareness active; no screen capture"]) + (none ? "Capri desktop companion")` (all segments localized). - Left click → `restoreCompanion()`. Right click → refresh audio input list only if the window is visible (never raise it just to enumerate), then pop up the menu built at that moment (3466-3661): | Item | Type / enabled | Action | |---|---|---| | Show Capri | | restoreCompanion() | | Settings | | settings.open() | | Teleport Capri | only if animated ∧ teleport allowed ∧ (attached ∨ detached-available) | teleportToCursor() | | Return to frame | only if detached-available | returnAvatar() | | Focus mode | checkbox = focusMode | checked → enterFocusMode else restoreCompanion | | Reset to bottom-right corner | | resetPosition() (reset avatar, clear compactPlacement, place on primary, save, restore) | | Reset Capri position and zoom | | resetAvatarLayout() (default layout `{x:0.5, y:1, zoom:1.15}`) | | Window dimming… | | restore + `open-dimming` | | Voice | checkbox = voice.enabled | changeVoice(checked) | | Voice effects… / Qwen model… / Languages… / File access… / Timers and reminders… / Application access… / Initiative… (BETA) / Screen snapshot… (BETA) | | restore + `open-voice-effects` / `open-models` / `open-languages` / `open-file-access` / `open-time` / `open-applications` / `open-initiative` / `open-screen` | | Open screenshots folder | | open `data/screenshots` | | Stop screen observation | enabled iff watch capture active | capturePolicy.clear() | | Microphone () | checkbox = capturing; enabled iff ASR allowed ∧ installed ∧ backend ∈ {ready, asleep} | restore + `microphone.toggle-request` | | Microphone input ▸ | radio submenu of input devices (`Unavailable — {device}` for missing) | change device; failure → `microphone.device-error` "The microphone selection could not be saved. Reopen the menu and try again." | | Microphone settings… | | restore + `open-speech-settings` | | Always on top | checkbox = preferred value (preview-aware) | setAlwaysOnTop | | — Updates… | | restore + `open-updates` | | Reconnect | enabled iff no connect in flight ∧ not shutting down | wake or connect | | Hide to tray | | hideCompanionToTray() | | — Quit and unload models | | ORC-07 | All labels pass through `uiText(label, interfaceLanguage)`; ` (BETA)` appended to Initiative… and Screen snapshot…. ### ORC-15 — Global shortcuts and Escape (P1 toggle, P0 Escape) - `Ctrl+Shift+Space` (not in verification, 6775-6779): window visible ∧ focused → hide to tray; else restoreCompanion(). - Escape during computer control (ORC-53): `registerEscape` registers a global `Escape` shortcut and starts the native Escape watcher (`computer_watch_escape`, ≤600 s, arm timeout 3 s). If the native watcher fails to arm, everything is unregistered and registration reports false (the control session must then refuse to start — fail closed). Any Escape keydown in any Capri window while a control session or indicator exists → `emergencyComputerStop()` (3935-3946). - All shortcuts unregistered on quit. ### ORC-16 — Settings window host (P0) - One lazily created Settings window (`main/settings-window.mjs`) reused for the session (drafts survive hide). Bounds: width `min(680, workArea.w-24)`, height `min(max(400, owner.h), workArea.h-24)`, x = left of owner with 12 px gap (else right of owner), clamped 12 px inside the owner's display work area; min 400×400; frameless; skip taskbar; always-on-top mirrors the owner (and follows owner changes); not minimizable/maximizable/fullscreenable; resizable; background `#07131c`; title `Capri Settings`. "Docked" until the user moves/resizes it (>1 px); docked windows follow owner move/resize and display changes. - `open(section=null, focus=null)`: refused while quitting; marks requested; navigation revision++; after load sends `settings.navigate {section, focus}` or `settings.resume` when no section (only once per revision); presents only after native paint ∧ (loading shell ready ∨ (ready ∧ content rendered)); first presentation probes a compositor frame up to 6 times (backoff `min(attempt*60, 240)` ms, 2500 ms timeout each) before becoming visible (Electron/Windows workaround; Rust: show when first frame is ready). - Renderer lifecycle commands (Settings-only): `settings-loading` (shell painted), `settings-ready` (flush up to 50 queued events by type, then navigate), `settings-rendered` (content ready). - Close button/OS close while ready → `settings.close-request` (renderer decides: save/discard barrier). `hide()` → invalidate presentation, unrequested, `onBusy(false)`. Owner hide/minimize hides it; owner show does not re-show it unless requested. - Busy coupling: visible Settings → `interfaceBusy=true` (pauses initiative/click reactions); on hide → lock private memory and clear any live previews (ORC-17). - Help bubble: `capri:settings-help {title≤160, text 1..2000, y within window, palette}` or `null` → separate non-focusable click-through child window beside Settings (width 210..344, gap 10, height ≤800, only when it fits the work area within 96 px of the edge; fade-out 160 ms); moving/resizing Settings closes it (`settings.help-closed`). - Crash of the Settings renderer → destroyed; if it was requested emit `settings.renderer-lost` (companion notice `Settings closed unexpectedly. Open Settings to try again.`). Unresponsive → diagnostics entry. - `capri:settings-open(section)`: refused (false) in focus mode; consumes the startup intro (`skip`) and emits `startup-intro.skip`; maps `memory→dialogue`, `dimming/motion→window`, `model-context` → section `models` with focus `context`; unknown section → `general`. - Events into Settings: see ORC-23 routing. ### ORC-17 — Live settings preview (P1) `capri:settings-preview(map)` (Settings-only, 3203-3282). Allowed keys and validators: `companion` (full companion settings), `dimming`, `zoom` (validated against layout bounds 0.6..3), `alwaysOnTop` (bool), `portrait` (bool), `voiceEffects`, `interface` (language id), `languages`, `personality` (text; invalid → default), `style` (communication style id), `initiative`, `microphone` (device id → described), `speechPause` (0.5..5 s, step 0.1), `computerAppearance`, `musicListening`. Unknown key → `Invalid settings preview.` Non-empty preview is ignored (returns false) unless Settings is currently requested. Replaces the whole preview map; for each changed key emits a `preview:true` event (`companion.settings` with `customAudio`, `dimming`, `avatar.layout`, `settings.set-portrait`, `voice.effects`, `languages`) or applies directly (always-on-top layer sync, control border appearance, initiative resync, microphone restart with `microphone.device-changed {..., restart}`, speech pause reconfiguration, music publish). `live*()` getters (companion, languages, microphone, persona, music) read the preview first. Hiding Settings sends an empty preview (restores saved values everywhere). Non-preview events are rewritten to keep showing active previews (ORC-23). ### ORC-18 — Reset settings to defaults (P1) `capri:settings-reset` (Settings-only, visible, not re-entrant, 4422-4551): confirmation `Reset settings to defaults?` (detail §6.2, `Reset settings`, danger, **delayMs 3000**), aborted if Settings hides/closes/crashes. Writes, in order, with rollback of already-written items on any failure (error `Could not reset settings. Check that Capri can save its preferences and try again.`): companion, inference-startup, voice effects, speech, initiative, screen-observation, computer appearance, music listening defaults; window `alwaysOnTop=true`; `presence.pinned=false`; dimming defaults `{enabled:true, level:35, softness:140}`; avatar zoom 1.15 (position kept). Then clear previews, stop music listening, sync layer, emit `window.always-on-top`, `window.portrait`, `settings.set-portrait {active, preservePresentation:true}`, reconfigure border/initiative/mic pause, emit `companion.settings {reset:true}`, `dimming`, `voice.effects`, `speech.settings`, `initiative.settings`, `screen.settings`, `computer.appearance`, `avatar.layout`; returns the full result object. ### ORC-19 — Revision-checked settings writes (P1) Channels `capri:companion-settings`, `capri:languages`, `capri:speech-settings`, `capri:initiative` (`main/ipc.mjs:40-57`): when called from Settings the request must be `{payload, expectedRevision}` where revision = SHA-256 hex of `JSON.stringify(current saved settings)`; mismatch → `Settings changed elsewhere. Apply or discard your draft.`; writes per channel are serialized (each waits for the previous); response `{settings, revision}`. Companion-window calls pass the raw payload and get the raw result. `settingsVersions` (all four hashes) are attached to every `companion.settings`, `languages`, `speech.settings`, `initiative.settings` event and returned by `capri:settings-versions` / bootstrap. `renderer/settings-api.mjs` wraps draft methods (`setDiscordPresence, setSpeechSettings, setCompanionSettings, savePersonality, setLanguages, setVoiceEffects, setInitiative, setComputerAppearance, setMusicSettings`) so pending saves form a "leave settings" barrier and updates the stored revision of the 4 revisioned groups from responses. ### ORC-20 — Confirmations (modal choices) (P0) `main/confirmations.mjs`. One pending confirmation at a time; a second request while one is pending (or with an aborted signal) resolves `cancel` immediately. `request(opts)` → boolean (choice `confirm`); `choose({title, detail, choices?, confirmLabel?, danger?, delayMs?, signal?})` → choice id. Default choices `[cancel: Cancel, confirm: (danger?)]`; custom choices need ≥2 unique non-empty ids including `cancel`. `delayMs` integer 0..10000: non-cancel answers before `now+delay` are ignored (returns false). Auto-cancel after **180 s**. Shows the owning surface first: focus Settings if visible; else avatar-only → `restoreCompanion()`; else `showCompanion(true)` (a no-op in focus mode, see §12). Emits `confirmation.request {id, title, detail, choices, confirmLabel?, danger?, delayMs?}` and `confirmation.closed {id}`. Answer via `capri:confirmation {id, choice}`. Routed to Settings when it is visible, otherwise to the companion (never both). `cancel()` on quit. ### ORC-21 — Command admission gate (IPC security) (P0) `main/ipc.mjs`. Channel names must match `^capri:[a-z-]+$`. A call is admitted only if the sender is the main frame of the current companion window with URL exactly `capri://desktop/index.html` (role `companion`), or the main frame of the current Settings window with URL `capri://desktop/settings.html` (role `settings`) **and** the channel is in `SETTINGS_CHANNELS` (139 names, `main/settings-channels.mjs`); otherwise `Untrusted IPC sender` / `IPC channel unavailable to settings`. Handlers receive `(payload, {role, frame})`; many add role checks (§5.1). Auxiliary windows use their own owner checks (composer `owns(event)`, chip `requireOwner`). In Rust the UI is in-process, but the role split and per-command validation must be kept (§10.3). ### ORC-22 — Bootstrap snapshot (P0) `capri:bootstrap` (5694-5769); companion call sets `rendererReady=true` (enables reminders/composer dispatch). Returns: `attachmentVision`, `thinking {enabled}`, `internet {enabled}`, `time` (timers snapshot), `inference {remote, vision, setupRequired, model, providerHost?}`, `windowSettings {alwaysOnTop, focusMode, avatarOnly}`, `settingsVersions`, `screenSettings`, `spotify`, `models`, `updates`, `messages` (transcript), `companion`, `startup`, `backend`, `power {phase}`, `warning` (newline-joined: avatar install warning, `ENGLISH_VOICE_SETUP_MESSAGE` if voice not installed and speech≠off, transcript warning, reminder warning; or null), `artwork`, `activeTurnId` (chat or visual), `language` (conversation language name), `sprite` (canvas), `avatars`, `animation`, `musicArtwork`, `musicListening`, `startupIntro` (only while the gate is pending), `avatar` (selection snapshot), `avatarLayout`, `dimming`, `voice`, `speech`, `microphone` (mic snapshot + device selection + `available`), `presence {pinned}`, `voiceEffects`, `allowModelCallAudio`, `callVoiceVolume`, `languages`, `languagePacks`, `recognitionAvailability`, `speechAvailability`, `speechInstallation`, `fileAccess {scopes, warning}`, `applications`, `applicationAccess`, `initiative`, `awareness {…observer, scheduling}`, `screen`, `screenObservation`, `lastScreenshot`. Renderer failure to bootstrap → backend shown offline `Capri could not initialize.` + notice `Restart Capri to restore the connection.` ### ORC-23 — Event bus and routing (P0) `emit(event)` (2149-2265) is the single core→UI path. Processing order: 1. Call-audio diagnostics observe. `companion.settings`, `languages`, `speech.settings`, `initiative.settings` get `settingsVersions` attached. 2. `file-access` → cancel pending action approval. All events go to reminder listeners (used by spoken reminders). `conversation.cleared` → clear temporal focus. 3. `open-*` navigation events (`open-companion→appearance`, `open-voice-effects→voice`, `open-models→models`, `open-languages→languages`, `open-file-access→files`, `open-time→time`, `open-applications→applications`, `open-initiative→initiative`, `open-screen→screen`, `open-dimming→dimming`, `open-speech-settings→microphone`, `open-updates→updates`): once the Settings host exists, open Settings at that section and **stop** (not forwarded). 4. Forward to Settings unless the type is `voice.chunk`, `voice.audio`, `voice.segment`, `voice.generated`, `voice.call-started`, `microphone.partial`, or starts with `turn.`; `confirmation.request` only when Settings is visible (and then **not** forwarded to the companion). 5. `companion.settings` (non-preview) is merged with an active companion preview; side effects: `followUp=false` → drop pending follow-up; `processGraphs=false` → stop process sampler; both monitors off → stop CPU sampler; refresh detached avatar theme/presentation. 6. Non-preview `dimming`, `avatar.layout` (zoom), `voice.effects`, `languages` (interface), `settings.set-portrait` are overridden by active previews. 7. Follow-up bookkeeping (ORC-34); `voice.error`/`voice.cancelled` drop pending follow-up. 8. Wake auto-reveal (ORC-13). Mic activity (`microphone.partial` with text, `microphone.activity`, `microphone.wake`) → cancel click reactions, `lastSpeechUntil = now + 5000 ms`, initiative + observation activity. 9. Tray tooltip refresh (ORC-14). 10. Send to the companion window if alive and not crashed (channel `capri:event`). `emitChat(event)` (2274-2335) wraps turn events (ORC-26). Settings-only messages are sent with `settingsHost.send()` (queued by type, max 50, until Settings is ready). Full event inventory: §5.1.3. ### ORC-24 — Turn submission pipeline (P0) `submitMessage(value, origin='text'|'microphone')` (1151-1321), wrapped in response timing keyed by the input id. 1. Cancel avatar click reactions. `input = validateInput({...value, thinking ?? thinkingMode, internet ?? internetMode})`: id must match `^[a-f0-9-]{36}$`i; text trimmed, 1..**8000** chars, no NUL (`Enter between 1 and 8000 characters.`); `mode` absent or `computer`; `thinking`/`internet` booleans (`Invalid message` / `Invalid message mode` / …). 2. **Avatar movement command** (`desktopAvatarCommand`, before any model/tool; strips `capri/капри`, please, final punctuation): return (`return/go back/come back/teleport back to your/the frame/window` or `home`, Russian equivalents) or perch (`sit/perch on (top of) (the) (active/current) window [title]`, `sit/perch on the window`, Russian; aliases хром→chrome, блокнот→notepad, дискорд→discord, проводник→explorer; title ≤160). Busy → `A reply is already in progress.`. Executes ORC-37 and appends a synthetic completed turn (texts §6.2). 3. Gates: voice training busy → `Wait for voice training to finish, or cancel it in Languages.`; local model not set up → `Choose and prepare a language model in Settings → Language model first.`; speech install busy → `Wait for speech installation to finish, or cancel it in Languages.` 4. Activity pings (initiative, observation), drop pending follow-up, typed input cancels a follow-up listening window; remember origin + mic session id per turn (≤128 entries). Shutting down → `Capri is shutting down`. 5. **Pending approval answer**: `approvals.text(text)` — exact (lowercased, trailing `.!?` stripped) `no/cancel/нет/отмена/не надо` → reject; `yes/yes please/go ahead/allow/confirm/approve/да/давай/разрешаю/подтверждаю/подтвердить/включи` → approve (only if the proposal allows voice; else answer `Use the on-screen confirmation buttons for this action.`); any other text cancels the pending approval and continues normally. Answered → store a user+assistant pair (`Cancelled.`/confirmation/`Done.`, localized), emit `turn.started {silent:true}` + `turn.completed`. 6. **Local clock answer**: if no task is running and `temporal.read(text)` returns a verified elapsed-time reply → store pair, emit `turn.started` (assistant empty), `turn.delta`, `turn.completed`; if backend ready, `chat.inject` it with label `Verified local clock response` (errors ignored). 7. **Sleep command** → busy check; `sleepService.sleep()`; silent turn `Going to sleep. Your next message will wake me.` (ru: `Ушла спать. Разбуди меня следующим сообщением.`); returns `{ok:true, sleeping:true}`; finally stop computer control. 8. Not awake → **await wake** (ORC-06). 9. **Clip command** (`isClipCommand`: ≤200 chars, no quotes/backticks, optional leading wake phrase, `(please) clip that/this/it` or `take/save (a) screenshot/screen shot (please)`) → ORC-28 (deduplicated by input id, ≤128 jobs). 10. Backend not ready → `The local core is not ready yet.`; a chat/visual/clip task active → `A reply is already in progress.` 11. Clear voice preview request; `task = chat.send(input, emitChat)`; `currentChatTask = task`; await; post-turn health check (ORC-05); finally clear `currentChatTask` and stop computer control. Returns `{ok:true}`; errors propagate to the caller (renderer restores the draft, ORC-31). ### ORC-25 — Chat turn execution and routing (P0; detail owned by the chat spec) `ChatService.sendTurn` (`chat-service.mjs:356-1165`). Constants: `MAX_INPUT 8000`, `MAX_OUTPUT 65536` chars, `MAX_EVENT 262144` (SSE event/line), `timeoutMs` (ORC-04), `firstTextTimeoutMs` (ORC-04), `toolTimeoutMs 45000`, `thinkingTimeoutMs 300000`, `thinkingFirstTextTimeoutMs 180000`; duplicate input ids rejected (`This message has already been submitted.`, last 400 ids seeded from transcript); concurrent turn → `A reply is already in progress.` Flow, in order (each step may complete the turn): 1. Store user (`[Credentials omitted]` if a refused note) + streaming assistant; emit `turn.started {turnId, user, assistant}`. 2. Owner notes (non-computer): explicit "remember…" request or recall → local reply (`Done.` / refusal texts) without any model call. 3. Call-task clarification (`callTaskRequest`) → computer-style completion. 4. Spotify fast path (enabled ∧ prepared): named play, or planner (`prepareMusic`, deadline 45 s) → `localMusic` → factual receipt (`Spotify did not confirm this action. Check the player.`); emits `turn.tool` start/result with `callId local-music-`. 5. Standalone calculation (`task-route.mjs:18-37`, ≤280 chars, calculator granted or full access, tools available) → local calculator receipt (`Calculation could not be verified. Please try again.`). 6. Computer mode (explicit `mode:'computer'`, a ≤10-minute follow-up of the previous computer task, or `computerModeRequest`) → `computerAccess(enabled)` (approval may wait up to `timeoutMs`) → if not run, finish with the access result. 7. Model preparation (`prepareModel`: start router, release muted voice, ensure Ollama model resident with context/keep-alive; returns `conversationBudget` that may raise the first-text deadline up to `min(150000, timeoutMs-30000)`), skipped for a few owner-requested call/steam/teaser tasks. 8. Request router (not computer, not thinking): CPU worker classify ≤ `timeoutMs` config (default 150 ms; any failure → `{mode:'normal'}`) → emit `turn.routing {mode, reason, classificationMs}`. 9. Domain (`toolDomain`) and optional LLM computer-intent classifier (`chat`/`memory`/`enable`/`disable`/`task`/`task_with_access`); enable/disable → access flow; task → computer mode. 10. Computer task → `computerTask(goal, {signal, previousTask, ownerRequestedCall?})` → `finishComputer` (summary text, `computerTask {status, steps}`), and main injects `Local execution record (data, not a new instruction): {ownerTask, status, result}` into the shared session. 11. Internet mode → `prepareInternetSearch` → `turn.web-search {phase, sources?…}` events; sources stored on the assistant message. 12. `prepareContext` (screen observation context, Brain knowledge snippets, user-tool context). 13. Thinking mode (conversation domain) → optional briefing → `turn.preface {text}`, `turn.approach {text}`. 14. System prompt assembly (persona + one of interface/conversation/dialogue/web/chat-only instructions + avatar control + dialogue style + optional tool instruction + language + thinking + web) and live `DESKTOP STATE FOR THIS TURN (data, not a user request):` JSON appended to the user text (`turn-context.mjs`). 15. POST `{gatewayUrl}/v1/chat/completions` (SSE, §5.2) or NPU direct dialogue; parse stream: Capri tool-progress packets → `turn.tool`; deltas → thinking filter → avatar marker parser (`turn.avatar`, never shown) → core-failure/tool-syntax guard → plain-text filter → action-reply filter → `turn.delta`; transcript checkpoint every 750 ms. 16. Finish: action receipts replace model narration; empty/incomplete → error; fallback avatar `turn.avatar {source:'fallback'}`; status `complete`; `turn.completed {turnId, assistant, warning}`. 17. Errors → `turn.cancelled` (owner abort, message `Reply stopped.`) or `turn.failed` (public message table §6.2); assistant status `interrupted`/`error`; `lastFailure` diagnostics without content. ### ORC-26 — Turn event side effects (`emitChat`) (P0) For every turn event before it reaches `emit` (2274-2335): - Terminal event (`completed/cancelled/failed`) whose turn owns the computer-control session (or no session) → stop computer control. - `turn.completed` → initiative quiet period **45 s**. - `turn.started`/terminal → Settings receives `settings.activity {chat: started?, playback: playbackBusy}`. - `turn.failed/cancelled` → cancel pending action approval. `turn.started` → drop pending follow-up. - Follow-up decision on `turn.completed` (ORC-34). - `voice.onChat(event)` (TTS pipeline, ORC-30). - Non-silent `turn.started` with voice enabled → call-audio diagnostics request (`toCall` when a call output shares replies). - `turn.avatar`: only if it belongs to the active, non-aborted chat turn → `avatar.request(id)` → `avatar.selection {selection, turnId, source}`; never forwarded itself. - `turn.started` → forward, then `avatar.selection {selection: invalidatePending()}` (cancels in-flight image decode, keeps current face). `turn.cancelled/failed` → also invalidate pending. - Forward via `emit`. ### ORC-27 — Visual turns: screen snapshot and attachments (P1) - `submitSnapshot({previewId, png, ...input})`: requires screen vision (`Enable vision for a compatible API model before sharing images.`), preview id known and captured ≤ **60 s** ago (`Take a new snapshot first`), conversation idle (`The conversation is busy`), PNG decodable (`Snapshot could not be decoded`). - `capri:attachment-send {id, text, attachmentIds, thinking?, internet?}`: idle check; drafts taken from the same renderer frame (else `{accepted:false, message:'Attach the files again for the active model.'}`). - `submitVisualTurn` (1765-1902): remote + images → provider image capability check; persist retained attachments (`AttachmentHistory`); store user message with `origin {kind:'screen'|'attachment', …source, imageRetained}` and `attachments`; timeout **180 s** (thinking **300 s**); optional web search; `visual.generate` streams `turn.preface/approach`, avatar choice (`avatar.selection`), `turn.delta`; then `capri.visual.commit` RPC (mandatory for screen, best-effort for attachments); `turn.completed`. Failure → `turn.cancelled` (`Reply stopped.`, or the unsupported-images warning) / `turn.failed` (visual failure message); `visualResponse` diagnostics `{active, source, startedAt, timeoutMs, lastFailure{at, code, providerStatus?}, elapsedMs}`. ### ORC-28 — "Clip that" screenshot command (P2) `submitClip` (1592-1708): cancels voice; 18 s timeout; emits `turn.started {source:'clip'}` and `screen.clip-status {active:true}`; refuses when the session is locked (`Screen is locked`); reuses an already-saved screenshot with the same id; otherwise uses the active watch capture (requests a frame from the renderer, `screen.clip-request`) or the native active-display capture; saves to `data/screenshots`; writes `DS/last-screenshot.json`; reply `Clipped it.`; emits `screen.clip-saved {screenshot}`; best-effort `capri.visual.commit` (3 s). Errors → `Screenshot cancelled.` / `I could not save the screenshot.` with `turn.failed` message `The screenshot could not be saved. Check the selected source and screenshot folder.` ### ORC-29 — Interruptions and cancellation (P0) | Trigger | Effect | |---|---| | Stop button / Escape in companion (no panel open, turn active or voice busy or call speech pending) | renderer `stopReply()`: drop call speech request, stop local playback, `capri:voice-stop`, `capri:cancel(activeTurnId)`; notice `The reply could not be stopped.` on failure | | `capri:cancel(id)` (id string ≤80) | stop computer control, cancel initiative, cancel approvals, `chat.cancel(id)`, cancel visual turn with that id, `voice.cancel()`; if chat cancelled emit `avatar.selection` (invalidate); returns cancelled∨visualCancelled | | `capri:voice-stop` | cancel call voice, clear preview request, `voice.cancel()` (→ `voice.cancelled`, POST voice `/cancel`) | | New typed send while speaking | renderer stops playback + `capri:voice-stop` before `capri:send` | | Spoken wake/barge-in (`bargeIn` true) | microphone `interrupt` → chat.cancel + cancelVisual + voice.cancel, `microphone.interrupt` event (renderer stops playback) | | Spoken `stop / stop capri / stop talking / be quiet / quiet capri / стоп / хватит / замолчи` | not submitted (`microphone.sent {localCommand:true}`); interruption already happened via barge-in | | Spoken `stop listening / microphone off / turn off (the) microphone / не слушай / выключи микрофон / прекрати слушать` | microphone stops (`microphone.stop-request`) | | Microphone input during an active turn | waits for the current task to settle, then submits (serialized queue) | | Escape during computer control (global, native watcher or any Capri window) | `emergencyComputerStop()`: cancel workflows, stop control, cancel chat and visual, cancel approvals | | Lock / suspend / sleep / UI crash / quit | see ORC-41, ORC-06, ORC-40, ORC-07 | Renderer Escape priority: models panel → updates panel → (confirmation open: ignore) → companion panel → dimming → voice effects (also stops a preview) → languages → file access → applications → initiative → screen → history → stop reply. ### ORC-30 — Voice (TTS) orchestration (P1) - Voice is **off at every launch**. `capri:voice-enabled(bool)` / tray `Voice`: disabling cancels call voice; enabling without an installed voice → `ENGLISH_VOICE_SETUP_MESSAGE`; `voice.setEnabled`; enable → `connectVoice()`; disable → release muted voice process (memory). Returns voice snapshot `{enabled, ready, language, error}` (event `voice.settings`). - `connectVoice()` (2080-2135) is a no-op unless allowed ∧ (enabled ∨ preview) ∧ no installer/training/catalog busy ∧ not shutting ∧ power ∉ {sleeping, asleep} ∧ language≠off ∧ not already starting/ready. Missing speech models → `voice.fail(ENGLISH_VOICE_SETUP_MESSAGE or 'Multilingual voice is not installed. Open Languages and install multilingual speech.')`. Else start the companion voice service (external process, §5.4) then `voice.prepareLanguage()`; failure → `lastVoiceFailure` diagnostics and `voice.fail('Capri’s voice could not start. Text replies are still available.')` (or the commit-limit message). - `MutedVoiceResidency`: when voice is disabled/off and no preview needs it, terminate the voice service to free memory (serialized with starts; called before model preparation and on disable/language off). - TTS pipeline per turn (`voice-service.mjs`): `turn.started` begins a voice turn if enabled ∧ language≠off ∧ not errored; `turn.preface` (≤240 chars, once) is spoken first; deltas are split into sentences (`SentenceBuffer`), sentence over `MAX_SPEECH_SENTENCE` → `voice.error 'This sentence is too long to read aloud. The full text is still available.'`, >100 segments → `'This reply is too long to read aloud.'`; serial synthesis POST `/synthesize` (409 → retry every 50 ms up to 90 s), audio = f32le mono 24 kHz, ≤45 s per segment; emits `voice.timing` then `voice.audio {turnId, sequence, text, sampleRate:24000, pcm(base64)}`; at the end `voice.generated {turnId}`; cancel → POST `/cancel {requestId}` (2 s) + `voice.cancelled {turnId}`; language mismatch / failures → `voice.error` (texts §6.2). - `capri:voice-preview(effects?)`: busy → `Wait for the current reply or preview to finish.`; wakes if asleep; connects; emits `voice.preview-started {turnId, effects}`; speaks `VOICE_PREVIEWS[lang]` (en: `Hey choom, I am right here. How does this sound?`). - Language change (`capri:languages`, 6197-6244): refuse with `Wait for the current reply to finish before changing languages.` if behavior changes during a turn/preview/install; restart the voice service if the backend changes; recognition language change → stop mic, close worker, update ASR language/availability; speech language change → `voice.setLanguage` (+ prepare or connect), off → release residency; emit `languages`. ### ORC-31 — Reply presentation: transcript, history, subtitles, paging, auto-hide (P0) - Transcript (`storage.mjs`): `DS/transcript.json` `{schemaVersion:1, messages}`; ≤200 messages, text ≤65536, file ≤2 MiB (oldest dropped); restored `streaming` → `interrupted`; unreadable file → in-memory only + warning `The local transcript could not be restored. Capri’s shared memory is still available.` (never overwritten except by explicit clear); save failure warning `The conversation is available now, but its local transcript could not be saved.`; it is a display journal only (never replayed to the model). - Renderer: `turn.started` creates/updates message views, resets subtitle state, records paint start; first visible `turn.delta` → `capri:response-painted {id, elapsedMs}` after two animation frames; terminal events finalize the view, set status label (`Stopped`, `Response incomplete`), show `event.warning` or the failure message as a notice, and announce `Capri has replied.` (a11y live region). - Subtitles (`renderer/subtitle-controller.mjs`): cue size `max(48, min(144, floor(stageWidth/10)*3))` chars and ≤3 rendered lines; follows audio timing when the reply is being spoken, else reading-time auto-advance; status label `REPLYING` / `THINKING…` / `STOPPED` / `RESPONSE INCOMPLETE`; manual previous/next pauses auto-advance; `n / total` position. - Auto-hide (`renderer/reply-visibility.mjs`): enabled by `replyAutoHide` (default true), delay `replyAutoHideSeconds` (2..60, default 8 s); text-only replies get `max(delay, min(30 s, chars×30 ms))`; waits for speech generation and playback end; holds for hover/focus/selection/history/detached-hover; never hides errors/cancellations; manual hide/reveal sticks for the turn. - Detached bubble paging (`renderer/reply-pages.mjs`): 240-char sentence pages; history of ≤30 assistant replies, ≤16000 chars each, ≤64000 total, assistant text only. - History panel: full transcript, attachments, web sources; follow-output when within 45 px of bottom. - Input box: Enter sends, Shift+Enter newline, IME composition ignored; height 29/48/67 px for window heights ≤400/≤540/larger; typing pings `capri:activity` at most every 150 ms; `capri:draft-state` when draft/attachments non-empty toggles. - Send button disabled when: not initialized; busy (submitting, call speech pending, active turn, speech pack installing); attachments pending; backend not ready while awake (except clip/sleep commands); empty; >8000 chars. Send hidden and Stop shown during a turn; Stop also shown while voice busy. ### ORC-32 — Companion state machine and status indicator (P0) Core-side state (orchestrator) — all must exist as explicit fields in Rust: | Variable | Values | Notes | |---|---|---| | `backend.phase` | starting/ready/offline/sleeping/asleep/stopping | ORC-05 | | `power.phase` | awake/sleeping/asleep/waking/notifying/voice-awake | ORC-06 | | window mode | visible / hidden-to-tray / focus / avatar-only (+ minimized) | ORC-13 | | `sessionLocked`, `shuttingDown`, `quitting` | bool | ORC-41, ORC-07, ORC-09 | | active work | none / chat turn / visual turn / clip / sleep task / avatar command | `currentChatTask`, `chat.active`, `visualTurn`; at most one | | `voicePreviewRequest`, `callVoiceTurn` | none / preview / call speech | | | `playbackBusy` | bool (reported by UI) | gates reminders, follow-ups, roaming | | `interfaceBusy`, `draftBusy` | bool (UI) | pause initiative/reactions | | `lastSpeechUntil` | ms | mic activity + 5 s | | microphone | off/starting/arming/listening × wake waiting/command/disabled | ASR spec | | computer control | session {active, steps, deadline} / none; `controlBorder` | ORC-53 | | avatar detach phase | attached/leaving/detached/teleporting/returning | ORC-37 | | `thinkingMode`, `internetMode` | bool (session) | ORC-35 | | `pendingFollowUp` | {turnId, sessionId, generated} | ORC-34 | UI status (`renderer/presence-model.mjs`): derived each frame with precedence `backend≠ready → backend phase` > `speaking` > active turn (`replying` if text received else `thinking`) > `buffering` (voice busy, no audio yet) > `listening` (mic listening, not waiting for wake) > `input` (typing focused) > `wake` (waiting for wake word) > `online` (expanded) > `idle`. Labels/colors: starting `CONNECTING #a295ff`, idle `STANDBY #8ef5ed`, input `TEXT INPUT #8ef5ed`, listening `LISTENING #8ef5ed`, wake `SAY CAPRI #8ef5ed`, thinking `THINKING #f4ed75`, replying `RECEIVING #f4ed75`, buffering `VOICE PENDING #f4ed75`, speaking `SPEAKING #f4ed75`, online `ONLINE #8ef5ed`, offline `OFFLINE #ff5679`, stopping `DISCONNECTING #ff5679`, sleeping `GOING TO SLEEP #a295ff`, asleep `SLEEPING #a295ff`; unknown → offline. Expansion: portrait "pinned" (`presence.json`) or collapsed "core"; auto-reveal on reply text/speech when `expandOnReply`; auto-collapse after **45 s** idle unless pinned/autonomous/sleeping/turn/voice/pointer over window; wake gives 60 s voice attention; entering sleep reveals once. When detached, the label/color is pushed to the desktop avatar (`capri:avatar-status`). Status line text: active turn → `Working with Spotify…` (Spotify tool running) or `Capri is replying…`; voice busy → `Capri is speaking…`; else backend message. Reconnect button visible iff backend `offline` and not busy. ### ORC-33 — Microphone orchestration (P1; ASR internals in the speech spec) - `capri:microphone-start`: speech install busy → error; requires ASR allowed ∧ installed ∧ not shutting ∧ backend ∈ {ready, asleep} else `The selected speech recognition model is unavailable. Run setup-multilingual.cmd.`; returns `{...session snapshot, deviceId, deviceLabel…}`; if `wakeSound==='voice'` and awake and idle → prepare the cached wake voice in background (`CAPRI_VOICE_DISABLED` → `voice.warning`, else `wake.error`). - Session protocol: renderer start → `capri:microphone-ready(sessionId)` (arming→listening) → `capri:microphone-audio {sessionId, sequence, pcm ≤12800 B, multiple of 4}` (f32le 16 kHz; strictly sequential; ≥2 in flight → fail `Microphone audio could not be delivered reliably. Restart the microphone.`) → `capri:microphone-playback {sessionId, speaking, text}` (echo guard) → `capri:microphone-stop {id?, keepModelWarm?}` (closes the worker unless keepModelWarm). `capri:microphone-listen` = push-to-talk (`listenNow`, 30 s window) allowed when backend ∈ {ready, asleep}. - Device list `capri:microphone-devices` (enumerated by the UI, 2.5 s timeout, `Audio input list timed out`; never prompts) and `capri:microphone-device(id)`: if the effective device changes while capturing, stop and emit `microphone.device-changed {…, restart:true}` (renderer restarts). - Main forwards `microphone.*` events (§5.1.3); `microphone.partial final autoSend:false` text is pasted into an empty input box. ### ORC-34 — Voice follow-up listening (P1) On `turn.completed`: if `companion.followUp` ∧ turn origin `microphone` ∧ same mic session still active ∧ final assistant text ends with `?`/`?`/`؟` (optionally followed by spaces/closing punctuation/quotes) (`voice-follow-up.mjs`) → `pendingFollowUp {turnId, sessionId, generated: !voice enabled ∨ off ∨ errored}`. When `voice.generated` arrives for it and playback is idle (`capri:playback-state false`) → `microphone.continueListening(followUpSeconds×1000, sessionId)` (5..30 s, default 12; ≤3 consecutive per session; emits `microphone.wake {followUp:true}`). Cancelled by new turn, typed input, voice error/cancel, followUp disabled. ### ORC-35 — Thinking and internet modes (P1) Session-only booleans, default false. `capri:thinking-mode-set(bool)` → event `thinking.settings {settings:{enabled}}`. `capri:internet-mode-set(bool)` refused during a turn (`Wait for the current reply to finish.`) → `internet.settings`. They are defaults for inputs that omit the flags. Internet mode is read-only web search and must never grant computer control (`INTERNET_SEARCH_ONLY`). ### ORC-36 — Avatar expression two-phase commit (P1) `AvatarState` (`avatar-state.mjs`): `request(id)` sets pending + revision++ and returns a selection snapshot `{id, pose, expression, label, url, frameId, animation, returnTo, revision}`; the UI decodes the image then calls `capri:avatar-ready {id, revision}` → `acknowledge` makes it current (non-persistable choices fall back to `returnTo`/current) and persists `DS/avatar.json`; stale revisions are rejected. `capri:avatar-failed {id, revision}` → invalidate. `capri:avatar-frame-ready {id, revision, sequence}` (strictly increasing per revision) updates the hit-test mask and the detached avatar frame. ### ORC-37 — Detached avatar, perch, teleport, roaming (P2; rendering in the avatar spec) - `window-action leave-frame {frameId, rect, clip}` / `return-to-frame` (companion only; refused when shutting/locked/control border/absent; leave requires animated catalog). Phases emitted as `avatar.detach {phase}` (attached/leaving/detached/teleporting/returning). Back to `attached` clears avatar-only and perch. - Drag release outside the window (beyond 24 px margin, past the configured dead zone 0..120 px, ≥5 px) → try docking (screen edge within `avatarSnapRadius`, default 36 px, or a foreign window edge via the desktop bridge `avatar_window` query, radius ≤400 native px) else teleport to cursor. - Perch: seat on a window top edge (default dock `{edge:'top', fraction:0.66}`); follows the window via native watcher (Windows helper / own Settings window events) or a re-check every **1.8 s**; hidden when the contact point leaves the work area; ends when the window closes. - Roaming while a screen *watch* capture is active: first roam ≥20 s after the capture starts; then every 45–80 s random (35% chance perch on a window of an approved display, else random point avoiding the companion window and ≥140 px from the previous point); suppressed while busy (typing, turn, speech, control border, observation analysing, not awake). `avatarRoamAt` +60 s after a manual teleport, +90 s after return/command. ### ORC-38 — Detached input bar ("avatar composer") (P2) A small focusable window near the detached avatar (`main/avatar-composer.mjs`): compact 124×44, text mode 344×60..240 (`capri:avatar-composer-resize` 44..240), 8 px gap, proximity reveal radius 90 px, fade 180 ms, re-raised every 750 ms. The companion renderer remains the single owner of draft/attachments/send: it publishes `capri:avatar-composer-state` (sanitized snapshot: draft ≤8000, revision, canSend, canAttach, busy, attachments ≤4 {id,name}, thinking, internet, microphone {loading, listening, disabled, label}, labels, locale, status, error, theme colors); main forwards to the composer (`capri:avatar-composer-state` send). Composer actions (`edit {draft, revision}`, `submit`, `attach`, `remove {id}`, `microphone`, `keyboard`, `menu`, `thinking {enabled}`, `internet {enabled}`, `paste-files {files ≤4 {name, bytes ≤8 MiB (video ≤32 MiB)}, overflow}`) are validated and relayed to the companion as event `avatar.composer.action {id, action}`; the companion answers `capri:avatar-composer-ack {id, accepted}` (≤32 pending, 10 s timeout `The input bar could not reach Capri.`). `attach` opens a native multi-file picker owned by the composer. `menu` toggles between collapsing the companion (avatar-only) and restoring it. ### ORC-39 — Reminder delivery (P1; scheduling in the time spec) `ReminderDelivery(DS/reminder-delivery.json)` callbacks: `visual(object)` requires a ready renderer (`Reminder waits for the interface.`), emits `time.due {object}` and a desktop notification `Capri · Reminder` with body = title or `Timer finished.` (body is just `Reminder` while the session is locked), silent; click → restore + open Settings `time`. `ready()` → `busy` (renderer not ready, shutting, turn active, playback/voice generating, power sleeping/waking), `locked`, `silent` (voice disabled/off, or not ready and `wakeOnReminder` false), else `ready`. `prepare()` → if voice not ready `wakeForReminder(connectVoice)` (`The reminder voice could not start. Open Languages to check its installation.`) then `reminder.wake`. `speak` → `Choom, your reminder: {text}` or `Timer finished.` (conversation language) with turn id `reminder-`. `notify` → `reminder.delivery {state, id, error?}`. `capri:reminder-retry(id)` requires voice enabled (`Enable Capri’s voice to hear this reminder.`). Unlock → `reminders.pump()`. ### ORC-40 — UI process crash recovery (P1) Companion renderer gone (6709-6733): stop music; unless quitting → mark failed/not ready, clear drafts, reset call audio, clear busy/playback/follow-up/preview, drop regions, cancel pointer, cancel chat/visual/voice, stop mic, clear capture (`renderer-stopped`), hide to tray; reload the UI at most once per **60 s** (further attempts on tray restore). In Rust (in-process UI) the equivalent is a UI-thread panic/GPU loss: apply the same cancellation set, then recreate the window. ### ORC-41 — Session lock and suspend (P0) - Lock (6961-6974): hide recording indicator, cancel user tools and workflows, lock private memory, hide chip, stop music, stop computer control, `sessionLocked=true`, cancel click reactions, reset detached avatar, discard screens (`screen-locked`: reset call audio, cancel approvals, clear capture, clear previews, `screen.reset`), cancel visual. - Suspend: same minus `sessionLocked` (reason `system-suspended`). Unlock: `sessionLocked=false`, pump reminders. - While locked many commands refuse (private memory, Brain, memory, workflows, user tools, web source, composer, avatar moves); clip refuses if the idle state reports `locked`. ### ORC-42 — Capture/device permission gate (P0) Chromium permission handlers (6869-6938) grant only to the exact companion main frame (`capri://desktop/index.html`, origin `capri://desktop`): `media` (audio only, single type for requests) when the microphone is arming/listening or a call output is being enabled from visible Settings (checks also while listing devices); `display-capture` only while a screen capture lease, system-audio or music capture is armed; `speaker-selection` only while listing/enabling call outputs. Display media requests are consumed by music, system audio or screen policy, in that order; the OS picker is never used. Rust: capture pipelines (PipeWire/X11) may only be started by these same armed states (§7). ### ORC-43 — `capri://` resource scheme (P2 — replaced in Rust) `main/protocol.mjs` + `main/resources.mjs`: GET-only, host `desktop`, no query/hash/userinfo/port; serves an explicit file table (renderer files, shared JSON, fonts, sprites/frames/notes/intro frames, brand SVGs, pdf.js) with CSP `default-src 'none'; script-src 'self'; …` and `nosniff`, `no-store`; `/attachments//(thumb|preview).png` from AttachmentHistory with `default-src 'none'`, CORP same-origin. Rust native UI loads embedded/whitelisted assets directly; keep the "explicit allowlist, never a user path" rule for any asset loader. ### ORC-44 — Notices and user-visible errors (P0) Renderer `notice(text, severity='error'|'warning')` strips the Electron prefix `Error invoking remote method 'capri:…': (Error: )?`, localizes, shows a dismissible banner with a "report bug" button for errors (hidden for warnings; screen-image warnings forced to warning). Main never sends stack traces or private paths to the UI; errors thrown by commands are user-readable sentences (§6.2). ### ORC-45 — Diagnostics snapshot and bug report (P2) `capri:bug-report(description)` (companion-ipc.mjs:160-201): one at a time; save dialog `Save and review bug report` default `capri-diagnostics-.zip`; report built by the diagnostics module from `diagnosticSnapshot()` (artwork, chat diagnostics, inference transport, visual response, startup, backend, GitHub, updates, settings window, Discord, Spotify, confirmation pending, action broker, app grants, computer task, screen capture/observation (no source), voice, music, call audio, speech installation, voice residency/installed/allowed/last failure, languages, recognition, inference config, window bounds/scale, playback, renderer diagnostics), resource probe (`/api/ps` 2 s, 128 KiB), voice `/health` 2.5 s; written via temp file + rename; reveals file; returns `{saved, reportId, files, bytes}`. Developer panel channels read diagnostics/logs (Settings only). ### ORC-46 — Resource HUD (P2) `capri:memory-status` → `{…RAM/VRAM sample, context (session token usage, if memoryMonitor), processLoad (if processGraphs), cpu}` or null when both monitors off, window hidden/minimized, or shutting down. `capri:monitor-display('toggle'|'menu')`: toggle graphs↔monitor, or popup radio menu Circles/Bars/Graphs; persisted in companion settings (`monitor.error 'Monitor display could not be saved.'`). Interval setting `memoryIntervalSeconds` ∈ {3,5,10}. ### ORC-47 — Window dimming (P2) `capri:dimming {enabled, level 0..85, softness 0..320}` (rounded) → event `dimming`, saved to `DS/dimming.json` after 200 ms. Renderer shades either the whole 480×660 window or only the visible compact rectangles (+12 px). ### ORC-48 — Startup intro gate (P2) `StartupIntroGate`: enabled iff an animated catalog has an intro pack. `capri:startup-intro('play'|'skip')` (companion only) → `skip` when not pending; `skip` consumes; `play` returns `wait` unless the companion is visible, focused-mode off, not avatar-only, not locked/shutting, Settings not visible, URL correct — then consumes and returns `play`. Opening Settings consumes it (`startup-intro.skip`). ### ORC-49 — Updates wiring (P2; update service in its own spec) Startup check on first `ready-to-show`; `capri:update-*` delegate to UpdateService; `capri:update-install`: idle (`Wait for the current reply to finish.`), no model/Spotify/speech/HF/voice operations (`Wait for the current operation to finish.`), confirmation (managed+incremental: `Install this update?` / `Restart and update`; managed full installer or dev checkout: `Open the downloaded installer?` / `Open installer`), then `updates.install({parentPid, language, shutdown: shutdownForRestart})`; quit when managed and installed. GitHub token channels cancel the startup check. ### ORC-50 — First-run routing (P1) After window creation: API setup required → on `ready-to-show` open Settings `api` focus `api-key` (unless focus mode); else local model setup required (and not remote) → open Settings `models` focus `hf-query`. ### ORC-51 — Conversation and memory reset (P1) `capri:reset-context` / `capri:reset-memory` → `confirmReset(memory)` (5524-5564): idle required (`Wait for the current reply to finish.`), not re-entrant (`maintenance` flag also blocks memory-save/saved-memory). Confirmation (danger, `Clear`): memory → `Delete saved notes about you?`; context → `Start a new conversation?` (details §6.2). Then stop mic, cancel voice and initiative. Memory: `backend=starting 'Updating shared memory…'`, stop RPC and gateway, clear USER.md/MEMORY.md/notes (`clearSavedMemory`), reconnect. Context: RPC `sessions.reset {key, reason:'new'}`, invalidate context sampler, close viewer, clear drafts, clear transcript and attachment history, emit `conversation.cleared`. ### ORC-52 — Web source links (P2) `capri:web-source-open {turnId uuid, index 0..4}` (companion only, not locked/shutting): looks up the stored assistant message's validated `webSources[index]` and opens its URL in the default browser; anything else → `Web search is unavailable.` ### ORC-53 — Computer-control supervision (P0; executor in the computer-control spec) - Every 400 ms: `computerControl.supervise({indicatorVisible, escapeAvailable})` where escapeAvailable = session not ready ∨ global Escape registered ∨ native watcher active. It stops the session (fail closed) when an indicator is visible without a session, access was revoked, no owner turn/workflow is active, the session belongs to another turn, or a ready session has no Escape path (`computer-control.mjs:90-104`); session `begin()` throws when Escape registration fails (`computer-control.mjs:163`). - Session start requires full computer access ∧ application access ∧ an active non-aborted chat turn or a workflow turn ∧ not shutting. - `showBorder`: one indicator per display, caption `Computer control active — press Escape to stop`; demote companion layer; overlay loss → emergency stop. `hideBorder` restores the layer. Each input pulses the border (`computer.input`). - `capri:computer-preview(appearance?)`: refused during a session (`Stop computer control before previewing its effects.`); shows a preview border for 3 s. - Terminal turn events stop the session (ORC-26). `capri:computer-stop` = emergency stop. `capri:computer-task(text)` (Settings or companion) = send with `mode:'computer'` (requires application access and `Enable Full computer access in Settings → Computer control first.`). ### ORC-54 — Voice calls, system audio and music listening (P2; Windows-only in 1.0.4) All call-audio features require `process.platform === 'win32'` (`callAudioAvailable`, `musicAvailable`), so on Linux bootstrap reports `supported:false` and commands throw `Call audio requires an open Capri window.` / `Music listening could not start. Try again from Settings.` Contract kept for a future Linux port: call output on a virtual cable with optional mic mix (15 s setup timeout, rollback to off), model-selected call replies (`allowModel`, 20 s generation), owner/call routing, music detection with BPM animation. Linux mapping in §8. ### ORC-55 — Verification (test) mode (P2) `--verification` + env: `CAPRI_DESKTOP_VERIFICATION_DIR` (state), `_PORT` (gateway), `_SESSION` (session key), `_VOICE=1` (voice allowed + `voice.json`), `_ASR=1`, `_WAKE=0` (disable wake word), `_MOCK_PACKS=0|1`, `_ROUTER=1` (router enabled else disabled with 150 ms), `_SKIP_START=1` (no core start; probe `/v1/models` 5 s), `_OBSERVATION_URL`, `_CLIP_FIXTURE=1` (`clip-owned-window.txt`), `_UPDATE_CHECK=1`. Effects: no tray-shortcut, window not focusable, devtools on, no shell side effects, downloads/restarts refused. Rust: provide an equivalent `--test-mode` with fake services for integration tests (§11). ### ORC-56 — Initiative/awareness sync and avatar click reactions (P2) - `syncInitiative()`: configure initiative with live settings and enable the window observer only if level≠off ∧ companion present ∧ not shutting ∧ not verification ∧ backend ready; called at startup end, on window show, wake, initiative settings/preview changes. Initiative messages are injected into the shared session (label `Capri initiative / verified Windows {kind} at {ISO}`) then delivered as a synthetic turn `source:'initiative'` (spoken). `capri:initiative-dismiss` also cancels its speech. - Avatar taps: gap `avatarTapGapSeconds` (1..15, default 10); allowed only when idle (no turn, not typing/busy unless waking, no initiative, no observation analysis, no playback/preview/voice generation, ≥5 s after user speech); tapping a sleeping/offline Capri wakes or reconnects (deadline `timeoutMs`), selects `annoyed`; spoken cue if voice ready; reply delivered as synthetic turn `source:'avatar-click'`; events `avatar.tap {part, tone, count, pulse}`, `avatar.headpat {point}`. ### ORC-57 — Idle guards for maintenance operations (P1) `assertModelIdle({spotifyChange})`: speech install busy → `Wait for speech installation to finish, or cancel it in Languages.`; any of shutting, active turn/visual, backend connecting, updates/HF/voice catalog/voice training/models busy, Spotify busy (unless the Spotify change itself) → `Wait for the current reply or operation to finish.` `assertIdle({requireBackend=true})` → `Wait for the current reply to finish.` Used by every download/apply/restart channel (§5.1). --- ## 3. Data and persistence ### 3.1 Write discipline - All JSON state uses `writeJsonAtomic` (`packages/runtime/src/atomic-json.mjs`): `mkdir -p` parent; create `...tmp` with `O_CREAT|O_EXCL`, mode `0600`; write `JSON.stringify(value, null, 2) + "\n"`; `fsync`; close; `rename` over the target; always unlink the temp file on failure. Rust: same algorithm (`tempfile::NamedTempFile::new_in(dir)` + `persist`, or manual `OpenOptions::create_new` + `sync_all` + `rename`), permissions 0600, parent dirs 0700. - No inter-process locking: the single-instance guarantee (ORC-02) makes the desktop the only writer of `DS/`. Readers tolerate missing/corrupt files by falling back to defaults without overwriting the bad file (Preferences, transcript). - Debounced writes: window position 350 ms, avatar layout 250 ms, dimming 200 ms; all three are flushed synchronously in `before-quit`. - Every small state file is read only if < 4096 bytes (presence, dimming, avatar layout, avatar), Preferences files ≤ 16384 bytes, initiative state < 16384, transcript ≤ 2 MiB. ### 3.2 Files read/written by the orchestrator | Path | Format / schema | Writer, when | Limits & rules | |---|---|---|---| | `DS/window.json` | `{"schemaVersion":3,"x":1424,"y":402,"footprint":{"x":40,"y":380,"width":400,"height":260},"compactPlacement":{"x":1464,"y":782,"width":400,"height":260},"alwaysOnTop":true}` (footprint/compactPlacement optional) | ORC-12 | v1/v2 migrated on read; invalid → defaults | | `DS/avatar.json` | `{"schemaVersion":1,"id":"happy"}` | AvatarState acknowledge (only when the current id changes) | unknown/non-persistable id → catalog default | | `DS/avatar-layout.json` | `{"schemaVersion":1,"x":0.5,"y":1,"zoom":1.15}` | layout changes (250 ms), drag end, return-to-frame, reset | zoom 0.6..3; default `{x:0.5,y:1,zoom:1.15}` | | `DS/dimming.json` | `{"schemaVersion":1,"enabled":true,"level":35,"softness":140}` | `capri:dimming` (200 ms), reset | level 0..85, softness 0..320 | | `DS/presence.json` | `{"schemaVersion":1,"pinned":false}` | `capri:presence-pinned`, window-action portrait, reset | default false ("standby core") | | `DS/.json` Preferences | `{"schemaVersion":1,"settings":{…validated…}}` | `Preferences.set()` | invalid/oversized → defaults + warning `Saved settings could not be restored. Defaults are in use.`; file untouched until next set | | ↳ names | `companion`, `inference-startup`, `computer-control`, `voice-effects`, `languages`, `applications`, `initiative`, `music-listening`, `call-audio`, `screen-observation`, `speech`, `discord-presence` | | schemas §4 (owned specs for non-orchestrator ones) | | `DS/application-access.json` | `{"schemaVersion":1,"settings":{"enabled":true}}` | ApplicationAccess | owned by capabilities spec | | `DS/startup-times.json` | `{"core":14.2,"models":9.8,"voice":21.0}` (seconds) | StartupProgress.finish | used as ETA (clamped 1..600) | | `DS/transcript.json` | `{"schemaVersion":1,"messages":[{"id":"…uuid…","turnId":"…uuid…","role":"user","text":"Hi","status":"complete","createdAt":"2026-01-01T10:00:00.000Z"},{"id":"…","turnId":"…","role":"assistant","text":"Hello!","status":"complete","createdAt":"…","avatar":{"id":"happy","pose":"stand","expression":"happy"},"followUp":false}]}` | TranscriptStore.put on every turn event, 750 ms streaming checkpoints | ≤200 msgs; text ≤65536; file ≤2 MiB; statuses `complete/streaming/interrupted/error`; optional fields `avatar`, `followUp`, `computerTask{status,steps}`, `webSources[]` (assistant), `attachments[]`, `origin{kind,…}` (user), `localCalculation{expression,result}`; legacy sealed format opened with `DS/private-data-key.json` | | `DS/last-screenshot.json` | `{"id":"…uuid…","name":"capri-2026-01-01-100000.png","path":"data/screenshots/capri-2026-01-01-100000.png","capturedAt":1767261600000,"source":{"kind":"monitor","label":"Active display"}}` | clip success | path relative to root with `/` | | `DS/first-start.json` | `{"schemaVersion":1,"preloadModels":false}` | installer wizard | deleted when consumed | | `DS/wake-audio` | user audio copy (wav/mp3/ogg/flac/m4a) | `capri:wake-import` | ≤4 MiB, regular file | | `DS/wake-voice-<20hex>.pcm` | raw f32le mono 24 kHz | `capri:wake-prepare` | 0 < size ≤ 960000 B, size%4==0, not a symlink; key = first 20 hex of SHA-256 of `{"language","phrase","text","identity"}`; written `wx` temp + rename | | `DS/voice.json` | `{"enabled":true}` | verification fixture only | | | `DS/private-data-key.json` | sealed legacy key | read only | opens legacy sealed transcript | | `DS/initiative-state.json`, `DS/reminder-delivery.json`, `DS/conversation-attachments/`, `DS/full-computer-access.json`, `DS/file-permissions.json`, `DS/microphone.json`, … | owned by other specs | | orchestrator only passes paths | | `DS/profile/`, `DS/crashes/` | Electron profile / dumps | Electron | Rust: drop profile; keep crashes dir | | `RUN/desktop.show` | `{"show":true,"launchNonce":"0123456789abcdef0123456789abcdef"}` | CLI launcher | consumed (unlinked) by the 400 ms poll | | `RUN/desktop.stop` | any | CLI `stop` | consumed → quit | | `RUN/launch-.json` | `{"schemaVersion":1,"nonce":"…32hex…","phase":"window-ready","pid":4242,"at":1767261600000}` | ORC-02 | refuses symlinked dirs/targets | | `RUN/desktop.json` | `{"pid":4242,"startedAt":"…","executable":"…","args":["--ozone-platform=x11","…/main.mjs"],"projectRoot":"…","privateLogSchema":1}` | runtime process registry (launcher) | used by CLI to detect a running desktop; Rust launcher must write the equivalent marker for itself | | `RUN/.primed.json` | `{"pid":4243,"startedAt":"…","warmupMs":5123.4}` | startCore agent warmup | once per gateway process | | `logs/response-desktop.jsonl` | one JSON timing record per line | response timing | ≤512 KiB then rotate to `.1`; regular file with nlink 1 only | | `data/screenshots/` | PNG files | clip | owned by screen spec | | user-chosen `capri-diagnostics-.zip` | ZIP | `capri:bug-report` | temp + rename | Retention: transcript capped as above; attachments pruned whenever the transcript's attachment references change; startup ETA history unbounded but tiny; launch receipts are consumed by the launcher (not pruned by the desktop). --- ## 4. Settings read by this subsystem ### 4.1 `DS/companion.json` (`companion-settings.mjs`; unknown keys rejected) | Key | Type | Default | Allowed | Effect (orchestrator-relevant) | |---|---|---|---|---| | `expandOnReply` | bool | true | | reveal portrait on reply text/speech | | `replyAutoHide` | bool | true | | auto-collapse finished replies | | `replyAutoHideSeconds` | int | 8 | 2..60 | delay | | `detachedStyle` | enum | `character` | character/dialogue | detached avatar presentation; dialogue disables drag tether and teleport sounds | | `minimizedChip` | bool | true | | show restore chip when hidden to tray | | `restoreFromTrayOnWake` | bool | true | | wake phrase reveals the hidden window | | `wakeSound` | enum | `tone` | tone/file/voice/off | wake acknowledgement; `voice` prepares cached TTS on mic start | | `wakePhrase` | enum | `Listening.` | `Listening.` / `Yes, choom.` / `Mhm?` | text of voice acknowledgement | | `wakeVolume` | number | 0.7 | 0..1 | | | `followUp` | bool | true | | ORC-34 | | `followUpSeconds` | int | 12 | 5..30 | follow-up window | | `buttonFeedback` | bool | true | | button pulse | | `wakeOnReminder` | bool | true | | load voice to speak reminders | | `memoryMonitor` | bool | true | | RAM/VRAM HUD | | `processGraphs` | bool | true | | process graphs HUD | | `memoryStyle` | enum | `rings` | rings/bars | | | `memoryIntervalSeconds` | int | 3 | 3/5/10 | HUD poll interval | | `teleportIntensity`, `teleportJaggedness`, `teleportBranches` | int | 75, 78, 75 | 0..100 | teleport effect | | `teleportReducedFlash` | bool | false | | | | `teleportSound` | enum | `spark` | off/spark/thunder/pulse | | | `avatarTapGapSeconds` | int | 10 | 1..15 | click reaction gap | | `avatarSnapRadius` | int | 36 | 12..100 | dock snapping (DIP) | | `avatarDragTether` | bool | true | | | | `avatarDragTetherIntensity`, `avatarDragTetherChaos` | int | 45, 55 | 0..100 | | | `avatarDragTetherDeadZone` | int | 30 | 0..120 | drag distance before teleport | | `glitchEnabled` / `glitchStrength` / `glitchIntervalSeconds` / `glitchEvents` | bool/int/int/bool | true/65/35/true | strength 0..100, interval 10..120 | visual glitch | | `floatEnabled` / `floatAmplitude` / `floatPeriodSeconds` | bool/int/int | false/6/10 | amplitude 0..24, period 4..30 | window float motion | | `interfaceTheme` | object | `{preset:'capri',hue:174,saturation:84,backgroundHue:174,backgroundSaturation:40}` | preset capri/blackwall/amethyst/overdrive/custom; hue 0..359; saturation 35..100 | colors (chip, composer, viewer) | ### 4.2 Other keys | Source | Key | Type / default | Effect | |---|---|---|---| | `DS/window.json` | `alwaysOnTop` | bool, default true | companion (+Settings, viewer) pinned | | `DS/presence.json` | `pinned` | bool, default false | portrait expanded permanently | | `DS/avatar-layout.json` | `x`,`y`,`zoom` | 0.5, 1, 1.15 | portrait placement | | `DS/dimming.json` | `enabled`,`level`,`softness` | true, 35, 140 | backdrop shade | | `DS/inference-startup.json` | `skipLocalModelOnApi` | bool, default true | in API mode, do not preload the router/local chat model and unload a resident one | | `DS/speech.json` | `trailingSilenceSeconds` | 0.5..5 step 0.1, default from `config/companion-asr.json` (1) | ASR end-of-utterance pause | | `DS/languages.json` | `interface` (en), `conversation` (en), `customConversation` (''), `recognition` ('follow'), `speech` ('follow'), `autoDetect` (false) | localizes UI/tray/dialogs; resolves ASR and TTS languages | | `DS/call-audio.json` | `allowModel` (false), `callVoiceVolume` | call features (Windows) | | `config/companion-asr.json` | `language`, `trailingSilenceSeconds`, `wakeWord.enabled`, `autoSend`, `bargeIn` | mic submit/interrupt behavior | | `config/request-router.json` | `schemaVersion` 1, `enabled` bool, `timeoutMs` 25..250 (150) | invalid → router disabled | | core settings (`config/core*.json` via runtime) | `model`, `upstreamModel`, `embeddingModel`, `contextTokens`, `keepAlive` (-1), `acceleration`, `cpuThreads`, `modelCapabilities`, `modelSetupRequired`, `generation`, `resourceProfile`, `sessionKey`, `agentId`, `ollamaPort`, `preloadModels` | chat/inference wiring, first-run routing | | env | `CAPRI_LAUNCH_NONCE`, `WAYLAND_DISPLAY`, `XDG_CURRENT_DESKTOP`, `CAPRI_DESKTOP_VERIFY` (Settings devtools), verification vars (ORC-55) | | --- ## 5. External protocols ### 5.1 UI ↔ core protocol (complete IPC inventory) #### 5.1.1 Transport and roles - Electron: commands are `ipcRenderer.invoke(channel, payload)` → Promise (reject = thrown `Error.message`); events are `webContents.send('capri:event', event)`. Preloads expose frozen objects: `window.capri` (companion and Settings; 211 methods = 210 invoke wrappers + `onEvent(cb) → unsubscribe`; 211 `handle()` channels exist, `capri:menu` is not exposed), `window.capriMini` (composer), `window.capriChip` (chip), `window.capriRecording` (recording indicator). No IPC object, token or credential crosses the bridge. - `From` column: **C** companion main frame, **S** Settings main frame (channel ∈ `SETTINGS_CHANNELS`), **C!**/**S!** handler additionally requires that role, **R** = revision-checked when called from S (ORC-19). "vis" = Settings must be visible. - Rust mapping: one `Command` enum variant per channel with a typed request and `oneshot` reply `Result` (§10.3); `Event` enum variants per event type. #### 5.1.2 Commands (UI → core) | Channel (`capri:` prefix omitted) | From | Request → Response | Gates / notes | Src (main.mjs unless noted) | |---|---|---|---|---| | **Lifecycle, window, presence** ||||| | `bootstrap` | C+S | – → Bootstrap (ORC-22) | C sets rendererReady | 5694 | | `settings-versions` | C+S | – → `{companion,languages,speech,initiative}` sha256 hex | | 4400 | | `quit` | C+S | – → void | ORC-07 | 6179 | | `reconnect` | C | – → `{phase,message}` | turn active → error | 6375 | | `hide` | C | – → bool | ORC-13 collapse | 6381 | | `menu` | (not exposed) | – → true | popup tray menu on window — dead channel | 6382 | | `window-action` | C+S | `{action, value}` → true / bool | `leave-frame`(C!, geometry) / `return-to-frame`(C!) / `always-on-top`(bool) / `reset-position` / `reset-avatar` / `reconnect` / `hide` / `focus-mode`(bool?) → focusMode / `portrait`(bool → persist + `settings.set-portrait`; undefined → `settings.toggle-portrait`) / `microphone` (→ `microphone.toggle-request`) / `quit` / `sleep` (confirm `Unload models and sleep?`); else `Unsupported window action` | 4571 | | `startup-intro` | C! | `play`/`skip` → `play`/`skip`/`wait` | ORC-48 | 5690 | | `activity` | C | – → true | initiative+observation activity | 5903 | | `interface-busy` | C | bool → true | busy = v ∨ Settings visible; true cancels initiative and taps | 5923 | | `draft-state` | C | bool → true | true cancels taps, pings activity | 5932 | | `playback-state` | C | bool → true | playbackBusy; `settings.activity`; false → resume follow-up | 5908 | | `response-painted` | C | `{id, elapsedMs}` (exact keys) → bool | timing ack | 5771 | | `regions` | C | `{controls[], sprite, footprint?}` → true | ORC-11; clamps on footprint change | 6387 | | `drag-start` / `drag-end` | C | – → true | window drag | 6462/6466 | | `presence-pinned` | C+S | bool → bool | persist + `window.portrait` | 6271 | | `dimming` | C+S | Dimming → Dimming | ORC-47 | 6386 | | `monitor-display` | C | `toggle`/`menu` → bool | false if hidden/minimized | 4348 | | `memory-status` | C | – → HUD sample / null | ORC-46 | 4381 | | `glitch-preview` | C+S | subset of 4 glitch keys → true | emits `glitch.preview` | 4615 | | `glitch-frame` | C | `{start,timestamp,eventAt,settings}` → bool | timestamp within ±2 s; relays `settings.glitch` to S | 4629 | | `avatar-layout` | C+S | `{x,y,zoom}` → layout | C keeps preview zoom and only notifies S; S emits `avatar.layout`; save 250 ms | 6405 | | **Conversation** ||||| | `send` | C | `{id,text,mode?,thinking?,internet?}` → `{ok,sleeping?}` | ORC-24 | 5770 | | `cancel` | C | turnId (≤80) → bool | ORC-29 | 6185 | | `thinking-mode-set` | C | bool → `{enabled}` | | 5776 | | `internet-mode-set` | C | bool → `{enabled}` | refused during a turn | 5783 | | `action-respond` | C | `{id, accepted}` → `{ok, confirmation?, cancelled?…}` | expired → `That permission request has expired. Ask again.` | 4692 | | `confirmation` | C+S | `{id, choice}` → bool | ORC-20 | 5332 | | `attachment-add` / `attachment-remove` | C | file / id → draft state | bound to sender frame | 5813/5814 | | `attachment-send` | C | `{id,text,attachmentIds,thinking?,internet?}` → `{ok}` / `{accepted:false,message}` | ORC-27 | 5815 | | `attachment-open` | C | uuid → bool | fullscreen viewer | 5829 | | `web-source-open` | C! | `{turnId,index}` → true | ORC-52 | 5791 | | `computer-task` | C+S | text → send result | ORC-53 | 5184 | | `reset-context` / `reset-memory` | C+S | – → bool | ORC-51 | companion-ipc.mjs:158-159 | | **Voice and speech** ||||| | `voice-enabled` | C+S | bool → `{enabled,ready,language,error}` | ORC-30 | 6196 | | `voice-stop` | C | – → true | | 6272 | | `voice-preview` | C+S | effects? → bool | | 6250 | | `voice-effects` | C+S | VoiceEffects → saved | emits `voice.effects` | 6245 | | `languages` | C+S R | Languages → saved | ORC-30 | 6197 | | `speech-settings` | C+S R | `{trailingSilenceSeconds}` → saved | reconfigures mic; `speech.settings` | 6154 | | `speech-availability` | C+S | – → `{lang:bool}` | | 5830 | | `speech-install-status` / `-install` / `-install-cancel` | C+S | selection → snapshot | install refused in verification or when busy | 5833-5851 | | `voice-catalog` / `voice-model-select` / `voice-model-install` / `voice-model-install-cancel` | C+S | selection → snapshot | select/install: `assertModelIdle`; select recomputes voice availability and reconnects | 4975-4990 | | `voice-training-status` / `-import` / `-start` / `-cancel` / `-preview` / `-apply` | C+S | – / selection | import opens a folder picker; idle guards | 4991-5020 | | `wake-import` | C+S | – → companion snapshot / null | audio picker; >4 MiB → error | companion-ipc.mjs:63 | | `wake-audio` | C | – → `{bytes,pcm,sampleRate:24000,text?}` / null | | companion-ipc.mjs:102 | | `wake-prepare` | C+S | – → true | idle; single-flight; `wake.audio-ready` | companion-ipc.mjs:156 | | **Microphone and call/music audio** ||||| | `microphone-start` / `-ready` / `-listen` / `-stop` / `-audio` / `-playback` | C | ORC-33 | | 5942, 6160-6181 | | `microphone-devices` / `microphone-device` | C+S | – / deviceId → selection | | 5970/5971 | | `system-audio-prepare` / `-cancel` | C | `{id,wake}` / id | Windows | 5972/5975 | | `call-audio-devices` | C+S | – → `[{deviceId,label,groupId?}]` | C gets [] unless enabling/ready | 6027 | | `call-audio-command` | S! | `{action: state/system-on/system-off/output-on/output-off/allow-model/share-replies/voice-volume, deviceId?, wakeFromSystem?, mixMic?, enabled?, volume 0..100?}` → call snapshot | strict key validation (`main/call-audio.mjs`) | 6032 | | `call-audio-setup` | S! vis | `state/connect/install/website/license` → setup snapshot | website https://vb-audio.com/Cable/, license https://vb-audio.com/Services/licensing.htm | 6052 | | `call-audio-state` | C | call state → void | relays `settings.call-audio` | 6069 | | `call-audio-speak` | C | `{id,text,model?}` → bool | ORC-54 | 6076 | | `music-status` | C+S | – → snapshot | | 5976 | | `music-settings` / `music-command` | S! (command: vis) | settings / `start`/`stop` → snapshot | 15 s timeout | 5977/5982 | | `music-audio-start` / `-ready` / `-packet` / `-stop` / `-prepare` / `-cancel` | C | music spec | | 6015-6026 | | **Avatar** ||||| | `avatar-ready` / `avatar-failed` | C | `{id,revision}` → bool | ORC-36 | 6278/6369 | | `avatar-frame-ready` | C | `{id,revision,sequence}` → bool | | 6284 | | `avatar-reply` | C! | `{text≤512, turnId≤128, fullText?≤16000, autoCollapsed?}` → bool | false while attached | 6304 | | `avatar-mouth` | C! | `closed`/`small`/`round`/`wide` → bool | | 6332 | | `avatar-status` | C! | `{text 1..100, color #rrggbb}` → bool | adds `sleeping` + reply labels | 6342 | | `avatar-drag-start` / `avatar-drag-end` | C | `{frameId,sprite,point}` / `{click,point?,drop?}` → bool | ORC-37 | 6420/6433 | | `avatar-composer-state` / `avatar-composer-ack` | C! | state / `{id,accepted}` | ORC-38 | 4332/4339 | | **Settings host and companion settings** ||||| | `settings-open` / `settings-close` | C+S | section? / – → bool | ORC-16 | 4401/4413 | | `settings-preview` | S! | preview map → bool | ORC-17 | 4417 | | `settings-reset` | S! vis | – → result / false | ORC-18 | 4422 | | `settings-ready` / `settings-loading` / `settings-rendered` | S! | – → true | | 4552-4570 | | `settings-help` | S! | `{title,text,y,palette}` / null → bool | | 4562 | | `companion-settings` | C+S R | CompanionSettings → `{…, customAudio}` | emits `companion.settings` | companion-ipc.mjs:37 | | `personality-get` / `-save` / `-open` | C+S | – / text / – | save requires idle; open creates the file and reveals it | companion-ipc.mjs:47-62 | | `communication-style` | C+S | style id | | companion-ipc.mjs:52 | | `community-link` | C+S | link id | unknown → error | companion-ipc.mjs:43 | | `bug-report` | C+S | description → result / false | ORC-45 | companion-ipc.mjs:160 | | `initiative` | C+S R | settings → saved | sync; failure → `initiative.error` | 5878 | | `initiative-dismiss` / `-restore` / `-test` | C+S | – | dismiss cancels its speech | 5894/5899/4611 | | `screen-settings` | C+S | observation options → saved | | 4795 | | `screen-form-command` | C+S | `{action: state/refresh/select/start/stop/capture/ask, sourceId≤300, interval 15..300, duration 0.5..120, question≤8000}` → companion `capriRunScreenCommand` result | renderer must be ready | 4640 | | `screen-form-state` | C | form state (`main/screen-form-state.mjs`) → true | relays `settings.screen-state` | 4669 | | **Models and inference** ||||| | `models-status` / `models-refresh` / `models-cancel` | C+S | | | 4843/4903/4904 | | `models-folder` | S! | kind → result | | 4844 | | `models-prepare` | C+S | id | refused when any operation busy | 4905 | | `models-apply` / `context-apply` / `model-devices-apply` | C+S | – / tokens / selection → bool | ORC-08 | 5195/5240/4867 | | `model-devices` | C+S | – → devices | | 4852 | | `huggingface-status` / `-search` / `-inspect` / `-plan` / `-cancel` / `-install` / `-repair` / `-remove` / `-token-save` / `-token-remove` | C+S | | install/repair/remove: idle; remove confirms `Remove downloaded model?` | 4937-4974 | | `inference-api-status` | C+S | – → status + `{localModel, localResidency, startup}` | | 5034 | | `inference-startup-set` | S! vis | `{skipLocalModelOnApi}` → status | | 5035 | | `inference-api-save` / `-test` / `-use` / `-remove` | C+S | profile / id | ORC-08; remove confirms `Remove API connection?` | 5041-5150 | | **Updates and GitHub** ||||| | `update-status` / `update-settings` / `update-check` / `update-download` / `update-cancel` / `update-install` | C+S | | ORC-49 | 5269-5331 | | `update-remind-later` | C | | | 5270 | | `github-status` / `-connect` / `-remove` / `-token-page` | C+S | | | 5271-5288 | | **Capabilities** ||||| | `computer-access-status` / `-set` / `computer-task-status` / `computer-appearance` / `-appearance-set` / `computer-preview` / `computer-stop` | C+S | | ORC-53 | 5151-5183, 6182 | | `application-access` | C+S | undefined → snapshot; bool → set | | 4709 | | `applications` | C+S | `{notepad,calculator}` → saved | `applications` event | access-ipc.mjs:49 | | `file-folder-add` / `-write` / `-revoke` / `file-folders-clear` | C+S | – / `{id,write}` / id≤80 / – → file access snapshot | `file-access` event | access-ipc.mjs:19-48 | | `app-catalog` / `-add` / `-update` / `app-discover` (`{query,refresh}`) / `app-discover-grant` / `desktop-journal` / `file-recovery` | C+S | | add opens an executable picker | 4697-4751 | | `file-purge-recovery` / `file-restore` | C+S | id `^[a-zA-Z0-9:_-]{1,160}$` | confirmations (purge: danger, 3 s delay) | 4752/4775 | | `workflow` | S! (vis except status) | `{action: status/record/stop/save/remove/run, workflow?, id?, variables?}` | locked → `Open Task training in Settings.` | 5382 | | `user-tool` | S! (vis except status) | `{action: status/open/refresh/enable/settings/inputs/stop/test/example, id?, enabled?, parameters?, settings?}` | | 5344 | | `spotify-status` / `spotify-check` / `spotify-access` | C+S | – / – / bool | access: ORC-08 | 4798-4842 | | `discord-status` / `discord-configure` / `discord-portal` | C+S | | portal opens https://discord.com/developers/applications | 5190-5194 | | **Memory** ||||| | `private-memory` | S! (vis except status) | `{action: status/lock/create/unlock/list/add/remove/password/chat, password?, oldPassword?, text?, id?, allowApi?}` | not locked | 5441 | | `brain` | S! (vis except status) | `{action: status/open/refresh/search/configure, enabled?, shareWithApi?, query?}` | | 5474 | | `memory-save` / `saved-memory` | S! vis | text / none | not during reset; generic errors only | 5500/5512 | | **Screen** ||||| | `screen-sources` / `screen-prepare` / `screen-watch-prepare` / `-sample` / `-frame` / `-stop` / `-ask` / `screen-finish` / `screen-release` / `screen-cancel` / `screen-close` / `screen-ask` | C | screen spec | lease rechecked on every call | screen-ipc.mjs:66-155 | | `screen-monitor-frames` | C! | id | | screen-ipc.mjs:75 | | `screen-select-source` | C! | – → sourceId / null | native popup menu `Monitor: …` / `Window: …` | 4714 | | `clip-frame` / `clip-sound` / `clip-open` / `clip-folder` | C | | sound: `data/sounds/screenshot.mp3` else bundled (≤2 MiB, no symlinks) | screen-ipc.mjs:32-65 | | **Time** ||||| | `time-status` / `time-action` / `reminder-retry` / `stopwatch-select` | C+S | | cancel also cancels delivery; stopwatch must exist | 4673-4691 | | **Diagnostics** ||||| | `developer-diagnostics` / `developer-log` / `developer-open-logs` | S! | – / id / – | | 4853-4866 | | **Auxiliary windows (own owner checks)** ||||| | `avatar-composer-bootstrap` / `-resize` (44..240) / `-hide` / `-action` | composer | ORC-38 | refused in focus mode/locked/shutting; hide/action need the bar visible | 4214-4331 | | `chip-restore` / `chip-drag` | chip | – / `start/move/end/cancel` → `{active,moved,cancelled}` | | minimized-chip.mjs:38-49 | | `recording-stop` | recording indicator | – → true | stops workflow recording | 6604-6616 | Allowlist anomalies: `capri:models-select` is in `SETTINGS_CHANNELS` but has no handler; `capri:menu` has a handler but no preload method. Drop both in Rust. #### 5.1.3 Events (core → UI, channel `capri:event`, `{type, …}`) | Type | Payload | Emitter | To | |---|---|---|---| | `turn.started` | `{turnId, user?, assistant, source?: clip/screen/attachment/initiative/avatar-click, silent?}` | chat/visual/main | C | | `turn.delta` | `{turnId, text}` | " | C | | `turn.completed` | `{turnId, assistant, warning?}` | " | C | | `turn.failed` / `turn.cancelled` | `{turnId, assistant, message, warning?}` | " | C | | `turn.preface` / `turn.approach` | `{turnId, text}` | chat/visual | C | | `turn.routing` | `{turnId, mode: fast/normal, reason, classificationMs}` | chat | C | | `turn.tool` | `{turnId, tool, phase: start/result, callId}` | chat | C | | `turn.web-search` | `{turnId, phase, sources?, …}` | chat/visual | C | | `turn.avatar` | internal only (consumed by emitChat) | chat | – | | `avatar.selection` | `{selection{id,pose,expression,label,url,frameId,animation,returnTo,revision}, turnId?, source?}` | main | C+S | | `backend` | `{phase, message}` | main | C+S | | `power.state` | `{phase}` | sleep service | C+S | | `startup.progress` | `{started, stages[], finished}` | startup | C+S | | `voice.settings` | `{enabled, ready, language, error}` | voice | C+S | | `voice.audio` | `{turnId, sequence, text, sampleRate:24000, pcm(base64 f32le)}` | voice | C | | `voice.timing` | `{turnId, sequence, elapsedMs, requestMs, tokenMs, decoderMs}` | voice | C+S | | `voice.generated` | `{turnId}` | voice | C | | `voice.cancelled` | `{turnId}` | voice/main | C+S | | `voice.error` | `{message}` | voice | C+S | | `voice.preview-started` | `{turnId, effects?}` | main | C+S | | `voice.call-started` | `{turnId, route, reply?}` | main | C | | `voice.warning` / `wake.error` | `{message}` | main | C+S | | `wake.audio-ready` | `{}` | companion-ipc | C+S | | `microphone.settings` | mic snapshot + `stoppedSessionId?`, `available?` | mic | C+S | | `microphone.partial` | `{sessionId, text, final, utterance, autoSend}` | mic | C | | `microphone.activity` / `microphone.interrupt` / `microphone.stop-request` | `{}` | mic | C+S | | `microphone.wake` | `{sessionId, utterance?, followUp?, manual?}` | mic | C+S | | `microphone.error` | `{message}` | mic | C+S | | `microphone.sent` | `{utterance?, localCommand?}` | mic | C+S | | `microphone.toggle-request` | `{}` | main | C+S | | `microphone.device-changed` | `{deviceId, deviceLabel, …, restart?, preview?}` | main | C+S | | `microphone.device-error` | `{message}` | main | C+S | | `companion.settings` | `{settings, preview?, reset?, settingsVersions}` | main | C+S | | `languages` / `speech.settings` / `initiative.settings` | `{settings, settingsVersions, preview?}` | main | C+S | | `dimming` / `voice.effects` / `screen.settings` / `computer.appearance` | `{settings, preview?}` | main | C+S | | `thinking.settings` / `internet.settings` | `{settings:{enabled}}` | main | C+S | | `avatar.layout` | `{layout, preview?}` | main | C+S | | `avatar.detach` | `{phase}` | main | C+S | | `avatar.tap` | `{part, tone, count, pulse}` | main | C+S | | `avatar.headpat` | `{point}` | main | C+S | | `avatar.reply-hover` | `{hovered}` | main | C+S | | `avatar.composer.action` | `{id, action}` | main (direct send) | C | | `window.focus-mode` / `window.always-on-top` / `window.portrait` | `{active, preview?}` | main | C+S | | `settings.set-portrait` | `{active, preservePresentation?, preview?}` | main | C+S | | `settings.toggle-portrait` | `{}` | main | C+S | | `focus-input` | `{}` | main | C+S | | `open-*` (12 types) | `{}` | main | C before Settings exists; else converted to Settings navigation | | `confirmation.request` | `{id, title, detail, choices[{id,label,danger?}], confirmLabel?, danger?, delayMs?}` | confirmations | S if visible else C | | `confirmation.closed` | `{id}` | confirmations | C+S | | `action.approval` | `{proposal{id,title,detail,kind,expiresAt,voice} or null}` | approvals | C+S | | `time.changed` | `{objects}` | time | C+S | | `time.due` | `{object}` | reminders | C+S | | `time.hud-selected` | `{id}` | main | C+S | | `reminder.wake` | `{}` | reminders | C+S | | `reminder.delivery` | `{state, id, error?}` | reminders | C+S | | `models.status`, `updates.status`, `speech-install.status`, `huggingface.status`, `voice-catalog.status`, `voice-training.status`, `music.status` | service snapshot spread | services | C+S | | `speech-components` | `{speechAvailability, recognitionAvailability}` | main | C+S | | `spotify.settings` / `discord.presence` / `application.access` / `computer-access` / `brain.status` / `private-memory.status` / `workflow.status` / `file-access` / `applications` | `{settings}` | services/main | C+S | | `computer.control` | `{active, steps, deadline}` | computer control | C+S | | `computer.input` | `{action}` | computer control | C+S | | `computer.task` | computer agent state | agent | C+S | | `screen.status` / `screen.observation` | `{settings}` | screen | C+S | | `screen.reset` | `{}` | main | C+S | | `screen.clip-request` | `{requestId, captureId}` | clip frames | C+S | | `screen.clip-status` | `{active}` | main | C+S | | `screen.clip-saved` | `{screenshot}` | main | C+S | | `initiative.activity` / `initiative.status` | `{settings}` | initiative/observer | C+S | | `initiative.error` / `monitor.error` | `{message}` | main | C+S | | `call-audio.reset` | `{}` | main | C+S | | `call-audio.policy` | `{allowModel, callVoiceVolume}` | main | C+S | | `glitch.preview` | `{settings}` | main | C+S | | `conversation.cleared` | `{}` | main | C+S | | `startup-intro.skip` | `{}` | main | C+S | | `settings.renderer-lost` | `{}` | main | C+S | | `voice.chunk`, `voice.segment` | legacy names in the Settings filter, no emitter | – | – | #### 5.1.4 Settings-only messages (`settingsHost.send`) `settings.activity {chat, playback}`, `settings.call-setup {state}`, `settings.call-audio {state}`, `settings.screen-state {state}`, `settings.glitch {start,timestamp,eventAt,settings}`, `settings.navigate {section, focus}`, `settings.resume`, `settings.close-request`, `settings.visibility {visible}`, `settings.help-closed`, and `microphone.device-changed` (selection unchanged). #### 5.1.5 Auxiliary window messages - Composer: core → `capri:avatar-composer-state` `{…sanitized state, mode: compact/text/expanded, composerVisible}`. - Chip and recording indicator: core → `capri:chip-labels` (chip `{title, language, accent, background}`; indicator `{text:'RECORDING ACTIONS · ESC', title:'Stop recording', language, direction: rtl for ar/he/fa/ur/ps}`). #### 5.1.6 Core → UI scripted calls (Electron `executeJavaScript`; in Rust become direct UI commands) | Target | Call | Purpose / timeout | |---|---|---| | companion | `navigator.mediaDevices.enumerateDevices()` (audio inputs) | device list, 2.5 s `Audio input list timed out` | | companion | enumerate outputs incl. groupId | call outputs, 2.5 s `Call output devices could not be listed.` | | companion | `window.capriRunCallAudioCommand(cmd)` | call audio, 15 s `Call audio setup timed out.`; on failure of `*-on` send the matching `*-off` | | companion | `window.capriRunScreenCommand(cmd)` | Settings screen form proxy (user-gesture preserved) | | companion | `window.capriRunMusicCommand('start'/'stop')` | 15 s; failure stops listening | | companion | `globalThis.capriAvatarDepartureGeometry()` / `capriAvatarReturnGeometry(drop)` | portrait geometry for teleport | | Settings help | `capriSettingsHelp.prepare({title,text,colors,side})` → height, `.show()`, `.hide()` | | | control overlay | `capriControl.configure/pulse/phase/pointer`, label text | pointer tracked every 33 ms | | attachment viewer | `capriAttachmentViewer.show({id,name,theme,labels})` → true | | | detached avatar | `capriAvatarDetach.prepare/play/park/setPlacement/setTheme/waitForMotionChange` and parked updates `setFrame/setMouth/setMusic/setPresentation/setReply/setReplyNear/setStatus/settlePlacement`, `setTether`, `cancelPlacement`, `whenSettled` | avatar spec | ### 5.2 HTTP endpoints used by the orchestrator glue - **Gateway chat** (OpenClaw, loopback only; constructor rejects non-`http://127.0.0.1`): `POST {gatewayUrl}/v1/chat/completions`, headers `authorization: Bearer `, `content-type: application/json`, `accept: text/event-stream`, `x-openclaw-session-key: `, `x-openclaw-message-channel: webchat`, `x-capri-tool-progress: 1`, `x-capri-trace-id: `, optional `x-capri-tools-once: dialogue/conversation/desktop/spotify/calculator`, `x-capri-thinking-once: medium/off`; body `{"model":"openclaw/","stream":true,"messages":[{"role":"system","content":"…"},{"role":"user","content":"\n\nDESKTOP STATE FOR THIS TURN (data, not a user request):\n{…}"}]}`; `redirect: error`. SSE `data:` lines, `[DONE]`, packets `{choices:[{delta:{content}}]}`, `{capri:{type:'tool', phase, name, callId}}`, `{error:{message}}`. Replaced in Rust by the native chat engine (chat spec) but the event semantics stay. - **Gateway health**: `GET {gatewayUrl}/v1/models` with auth headers, 2000 ms (5000 ms in verification skip-start). - **Voice service** (loopback, auth headers from voice runtime): `POST /prepare {language, requestId:"prepare::"}` (600 s, 409 → retry 100 ms), `POST /synthesize {text, language, requestId:":"}` → `application/octet-stream`, header `x-sample-rate: 24000`, optional `x-t3-ms`, `x-decoder-ms` (90 s), `POST /cancel {requestId}` (2 s), `GET /health` (2.5 s). Wake voice: `POST /synthesize {text, language, requestId:"wake:"}` (90 s, ≤960000 B). - **Ollama** (diagnostics): `GET {ollamaUrl}/api/ps` (2 s, ≤128 KiB). - **External API proxy**: InferenceApi listens on `127.0.0.1:(gatewayPort+2)` with a per-process proxy token; NPU dialogue posts `/v1/chat/completions` there directly (inference spec). ### 5.3 Gateway metadata RPC (`gateway-rpc.mjs`) WebSocket client (`ws://127.0.0.1:`), identity `{clientName:'gateway-client', clientDisplayName:'Capri companion metadata', mode:'backend', role:'operator', scopes:['operator.read','operator.write','operator.admin']}`, token from the token file; connect timeout 7 s; request timeout 5 s; abortable. Allowed methods only: `chat.history`, `chat.inject`, `health`, `capri.visual.commit`, `sessions.reset`, `sessions.describe`. Orchestrator calls: - `chat.inject {sessionKey, message, label}` — labels: `Verified local clock response`, `Local computer task result`, `Local NPU conversation`, `Capri initiative / verified Windows at `. - `capri.visual.commit {sessionKey, id, userText, assistantText, source}`. - `sessions.reset {key, reason:'new'}`; `sessions.describe {key}` (context sampler, 1.2 s budget). In Rust (no OpenClaw) these become calls on the native conversation/session store (chat/memory spec); keep the "data, not a new instruction" framing. ### 5.4 Subprocess protocols driven from the orchestrator - **Request router worker**: `/.runtime/router-venv/Scripts/python.exe -u -m integrations.request_router.worker` (Windows path; Linux venv path is an open question §12), cwd root, minimal env + `PYTHONUTF8=1, PYTHONIOENCODING=utf-8, TOKENIZERS_PARALLELISM=false, HF_HUB_OFFLINE=1, TRANSFORMERS_OFFLINE=1, OMP_NUM_THREADS=4`; stdout NDJSON (≤8192 B buffered): `{"type":"ready","protocol":1,"provider":"cpu"}` within 15 s; stdin `{"request":,"text":"…","context":["≤400 chars","…"]}`; reply `{"type":"result","request":,"mode":"fast|normal","reason":"≤40 chars","elapsedMs":}`; one request at a time; timeout/malformed/exit → disabled (`normal`) until `pause()` re-allows a restart (wake). stderr discarded. - **KWin cursor helper** (FWS-LINUX-BRIDGE): `/usr/bin/python3 -I integrations/desktop-actions/native/linux/capri-cursor`, env limited to HOME, LANG, XDG_RUNTIME_DIR, DBUS_SESSION_BUS_ADDRESS, WAYLAND_DISPLAY; stdout lines `x,y`; stdin EOF terminates it; restarted after 2 s, at most 5 times. - **Escape watcher**: desktop-actions bridge executable (Linux: `capri-desktop-actions` → `capri_linux/main.py`), stdin single line `{"action":"computer_watch_escape","parentPid":,"durationMs":600000}`, stdout NDJSON `{"ok":true,"event":"armed|escape|parent_exit|expired"}` (≤4096 B total; any stderr byte, invalid JSON, `ok≠true`, or exit = failure); arm timeout 3 s; lifetime `durationMs+1000`. - **Desktop bridge `avatar_window`**: `{action:'avatar_window', title?, windowId?, processId?, startedAtTicks?, nearX?, nearY?, nearRadius 1..400, ignoreProcessId:, allowedWindowId:}` → `{ok, windowId, processId, startedAtTicks, x, y, width, height}` (native px); results are rejected unless ids are decimal and the geometry is integer; own-process windows only for the visible Settings window. Linux impl: `capri_linux/main.py:739-794`. - **Companion voice service**: started/stopped through the voice runtime (`startCompanionVoice({language, signal})`, `stopManaged('companion-voice')`) — external Python process (voice spec). - **Relaunch**: `Capri.exe` or `node packages/runtime/bin/capri.mjs desktop`. ### 5.5 Desktop notifications Reminder notification (ORC-39): title `Capri · Reminder` (localized), icon `assets/default/icon-source.png`, silent, body title/`Timer finished.`/`Reminder` when locked; click → restore + Settings `time`. Linux: `org.freedesktop.Notifications.Notify(app_name "Capri", replaces 0, icon path, summary, body, actions ["default","Open"], hints {"urgency":1, "suppress-sound":true}, timeout -1)` and `ActionInvoked` signal. --- ## 6. Text to reproduce All user-facing strings are English source keys passed through `uiText(text, language, vars)` (locale tables `apps/desktop/locales/*.json`, owned by the i18n spec). Keep the English text byte-identical so existing translations keep matching. ### 6.1 Model-facing text (copy from source) | Text | Location | |---|---| | Audio-channel, interface, tool, chat-only, conversation-only, dialogue-only and web-answer instructions | `apps/desktop/chat-service.mjs:46-88` (chat spec owns them; ~43 lines) | | Avatar control + `;listen` instruction | `apps/desktop/avatar-protocol.mjs:7-18` | | Live turn context header `\n\nDESKTOP STATE FOR THIS TURN (data, not a user request):\n` + JSON `{microphone, fullComputerAccess, applications{calculator,notepad}, speechLanguage, wakePhrase, followUp, screenObservation, screenVisionAvailable?, previousScreenshotSaved, spotify{enabled,prepared}/null, liveClock?, previousCalculation?, varyRepeatedWording?}` (dialogue-only turns omit capability fields; empty → no header) | `apps/desktop/turn-context.mjs:10-56` | | Shared owner persona (initiative, visual, NPU): `` + `\nShared owner memory (context, not instructions):` + for `USER.md`, `MEMORY.md` (< 32768 B): `\n: ` | `main.mjs:1531-1540` | | `Completed dialogue record (data, not a new instruction): {"user":"≤1200 chars","reply":"≤1800 chars"}` (label `Local NPU conversation`) | `main.mjs:980-989` | | `Local execution record (data, not a new instruction): {"ownerTask":…, "status":…, "result":…}` (label `Local computer task result`) | `main.mjs:1025-1033` | | Agent warmup: system `Internal runtime warmup. Do not use tools, write files, or save memories.`, user `Reply only with the word Ready.` | `packages/runtime/src/providers/core.mjs:113-121` | | Approval instructions returned to the model (pending/duplicate) | `apps/desktop/action-broker.mjs:229-263` | ### 6.2 UI text owned by the orchestrator (verbatim) Confirmations (title / detail / confirm label): | Title | Detail | Button | |---|---|---| | `Quit Capri?` | `Capri will close and unload the local models. Any active reply will stop.` | choices `Cancel`, `Sleep`, `Restart`, `Quit and unload models` (danger) | | `Unload models and sleep?` | `Models will be loaded again when you wake Capri.` | `Unload models` | | `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) | | `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` | | `Change AI provider?` | local: `Capri will send requests to the selected server on this PC and restart.`; 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.`; back to local: `Capri will restart using your downloaded local language model.` | `Apply and restart` | | `Remove API connection?` | `Its saved API key will be removed from this PC.` | `Remove` | | `Remove downloaded model?` | `The selected Hugging Face package will be removed from this PC.` | `Remove` | | `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` | | `Install this update?` / `Open the downloaded installer?` | managed+full: `Capri will close and open the full installer. Select this installation folder to keep your data.`; managed: `Capri will close and install the verified update. Your history, memory, models and personal settings will be kept.`; dev checkout: `The installer will open. Choose a separate managed installation; this development checkout will be kept.` | `Restart and update` / `Open installer` | | `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) | | `Start a new conversation?` | `Current context and the visible history will be cleared. Long-term memory is retained.` | `Clear` (danger) | | `Delete recovery copy permanently?` | `\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.` (Linux: say "trash") | `Delete permanently` (danger, 3 s) | | `Restore this file?` | `\n\nThe current folder write permission is required. Existing files are never overwritten.` | `Confirm` | Approval cards created by the orchestrator (`main.mjs:4014-4128`): `Replace existing file?` (detail `\n\nBefore:\n…\n\nAfter:\n…`, buttons only); `Allow this application?` / `Allow Capri to open {application}, bring it to the front and read its accessible controls. Revoke this grant in Application access.` → `Application access enabled.`; `Open the required controls?` / `Choose the exact window or monitor and observation duration. Screen access will not begin until you select a source.` or `Review and apply this setting in its dedicated panel.` → results `Show Capri from the tray to open these settings.`, `Choose a window or monitor in Screen snapshot, then press Start observation. Capture has not started yet.`, `Opened Application access. Enable Spotify there to connect it.`, `Opened Languages. Choose the languages, then press Apply languages. No language was changed yet.`, `Opened Language model. Choose and prepare a model, then apply it. The current model has not changed.`; unsupported → `Unsupported setting.` Local replies: `Cancelled.`, `Done.`, `Going to sleep. Your next message will wake me.` (ru `Ушла спать. Разбуди меня следующим сообщением.`), `Clipped it.`, `Screenshot cancelled.`, `I could not save the screenshot.`, `I’m back in my frame.` (ru `Я снова в рамке.`), `I couldn’t get back to my frame.` (ru `Не получилось вернуться.`), `I’m perched on the window.` (ru `Я на краю окна.`), `I couldn’t find an open window to perch on.` (ru `Не нашла подходящего открытого окна.`), `Choom, your reminder: {text}`, `Timer finished.` Errors thrown by commands (selection; exact): `A reply is already in progress.` · `The local core is not ready yet.` · `Capri is shutting down` · `Wait for the current reply to finish.` · `Wait for the current reply or operation to finish.` · `Wait for the current operation to finish.` · `Wait for the current reply or preview to finish.` · `Wait for the current reply to finish before changing languages.` · `Wait for voice training to finish, or cancel it in Languages.` · `Wait for speech installation to finish, or cancel it in Languages.` · `Choose and prepare a language model in Settings → Language model first.` · `Enable Capri’s voice first.` · `The voice is unavailable. Enable it and retry.` · `The local voice service could not start.` · `Enable Capri’s voice to hear this reminder.` · `The selected speech recognition model is unavailable. Run setup-multilingual.cmd.` · `Invalid turn` · `Invalid message` · `Enter between 1 and 8000 characters.` · `Invalid settings preview.` · `Settings frame required` · `Companion frame required.` · `Untrusted IPC sender` · `IPC channel unavailable to settings` · `Unsupported window action` · `Input bar unavailable.` · `The input bar is busy.` · `The input bar could not reach Capri.` · `Capri is not ready.` · `Screen interface is not ready.` · `Open Capri to choose a screen source.` · `Take a new snapshot first` · `The conversation is busy` · `Enable a call output in Voice calls first.` · `Enable model-selected replies in Voice calls first.` · `Call audio requires an open Capri window.` · `Wait for VB-CABLE setup to finish before closing or restarting Capri.` · `Prepare the selected model first.` · `Enable Full computer access in Settings → Computer control first.` · `Stop computer control before previewing its effects.` · `Computer control indicator is already open.` · `Escape emergency stop is unavailable.` · `Web search is unavailable.` · `Open Settings to change model startup.` · `Could not reset settings. Check that Capri can save its preferences and try again.` · `Saved memories could not be loaded. Try again.` · `A diagnostic report is already being collected.` · `The wake voice is already being prepared.` · `Choose an audio file smaller than 4 MB.` · `Reminder waits for the interface.` · `The reminder voice could not start. Open Languages to check its installation.` · `Music listening could not start. Try again from Settings.` Status/notice text: `Starting local core…`, `Ready`, `Freeing model memory…`, `Sleeping. Send a message to wake Capri.`, `Stopping Capri and freeing model memory…`, `Preparing to restart Capri...`, `Switching language model...`, `Applying Spotify access...`, `Preparing Spotify integration...`, `Updating shared memory…`, `The local core is unavailable. Reconnect to try again.`, `Reconnect to try again.`, `Some services could not be stopped. Use stop.cmd or try again.` (Linux: name the CLI stop command), `Some models could not be unloaded. Reconnect to try again.`, `Spotify access could not be applied. Reconnect to try again.`, `The model could not be changed. Reconnect to try again.`, `Choose a language model in Settings → Language model.`, `API connections`, `Capri is replying…`, `Working with Spotify…`, `Capri is speaking…`, `Capri has replied.`, `Capri could not initialize.`, `Restart Capri to restore the connection.`, `Your message could not be sent. Reconnect or try again.`, `The reply could not be stopped.`, `Could not reconnect. Check the local core.`, `Could not teleport Capri.`, `Could not save Capri’s placement.`, `Could not save Capri’s presence setting.`, `Screen dimming could not be updated.`, `Audio playback failed. Try unmuting Capri again.`, `An expression could not be loaded. Keeping the current sprite.`, `An animation frame could not be loaded. Keeping the current pose.`, `The microphone could not start.`, `Settings closed unexpectedly. Open Settings to try again.`, `App awareness could not start.`, `App awareness could not start. Apply its settings to try again.`, `Monitor display could not be saved.`, `The microphone selection could not be saved. Reopen the menu and try again.`, `Reminder voice unavailable.`, `The screenshot could not be opened.`, `The screenshot folder could not be opened.`, fatal dialog `Capri could not start.` / `Your saved data has been preserved. Repair Capri with the installer and try again.` Voice texts: `Capri’s voice could not start. Text replies are still available.`, `Multilingual voice is not installed. Open Languages and install multilingual speech.`, `English voice is not installed. Open Languages and choose Install and enable. Capri downloads and installs everything automatically.`, `This sentence is too long to read aloud. The full text is still available.`, `This reply is too long to read aloud.`, `This sentence could not be spoken. Voice is still ready.`, `Capri’s voice is unavailable. Text replies are still available.`, `The English voice cannot read this response language. Choose the matching conversation and voice language in Languages. Text replies remain available.`, `The selected voice could not start. Text replies remain available. Check setup-multilingual.cmd.`, preview phrases `VOICE_PREVIEWS` (`apps/desktop/language-context.mjs:27-…`). Chat failure messages (`chat-service.mjs:174-193, 1146-1160`): `Reply stopped.`; `API model returned no text.`; `Lemonade could not generate a reply. Check that the selected model responds in Lemonade, then try again.`; `The action could not be completed after repeated attempts. Check Application access or try a larger language model.`; `The local model could not load. Free some memory or choose a smaller Qwen model, then try again.`; `Conversation context could not be compacted. Your history is preserved. Try a larger model or clear the current context in settings.`; `Capri took too long to respond. You can try again.`; `The local core rejected authentication. Check its configuration.`; `The local core is busy. Please wait and try again.`; `The local model could not finish this response. Please try again.`; `The response could not be completed. Check the local core or reconnect.`; `Capri could not finish the Spotify reply in time. Check the player before trying again.` Window/overlay captions: `Capri`, `Capri Settings`, `Capri Settings help`, `Capri Avatar`, `Capri · Preview`, `Computer control active — press Escape to stop`, `Computer control // Preview · 3 s`, `RECORDING ACTIONS · ESC`, `Stop recording`, `Show Capri`, `Teleport Capri`, tray labels (ORC-14), dialog titles `Choose a short wake sound (up to 10 seconds)`, `Save and review bug report`, `Choose an application`, `Choose input files`, `Choose reviewed Capri recordings (metadata.csv and WAV)`, `Choose a folder Capri may read`, monitor menu `Circles`/`Bars`/`Graphs`, screen source menu `Monitor: