166 KiB
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 modeCAPRI_DESKTOP_VERIFICATION_DIRmust resolve insideroot/.runtime/else throwVerification state must be inside this project’s .runtime directory. State dir =$DIR/desktop, otherwiseDS(root/data/desktop).- App name
Capri(orCapri Verification). Windows-only AppUserModelIDOveryx.Capri.<sha256(lowercased root)[0..16]>. - Chromium userData/session →
DS/profile, crash dumps →DS/crashes(Electron-only; Rust: keepDS/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 forcedskipTaskbaron show/hide/minimize/restore (ORC-11).
- After toolkit ready: Linux bridge
installLinuxCursor(screen)(KDE Wayland only, §8.2), theninitializeDesktop()(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-inputevent) (6795). - The CLI launcher (
capri desktop,packages/runtime/src/desktop-launcher.mjs) refuses when.runtime/updates/active.jsonexists, when arch ≠ x64, whenconfig/core.local.jsonis missing; if a manageddesktopprocess exists it writesRUN/desktop.show={"show":true,"launchNonce":<CAPRI_LAUNCH_NONCE or null>}and reportsalreadyRunning; otherwise deletes staleRUN/desktop.stopandRUN/desktop.show, unsetsELECTRON_RUN_AS_NODE, and starts Electron with--ozone-platform=x11on Linux (forces XWayland). - Control poll every 400 ms (
controlTimer, 6994-7019, unref'd; the two file checks are skipped in verification):RUN/desktop.stopexists → unlink →app.quit()(goes through ORC-09 only; services are stopped by the CLIstopcommand, not by the desktop).RUN/desktop.showexists → readlaunchNonce(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 ofRUNis a symlink or target exists and is not a regular file; writes atomicallyRUN/launch-<nonce>.json={schemaVersion:1, nonce, phase:"window-ready", pid, at:<ms epoch>}. Also published once on firstready-to-showwith envCAPRI_LAUNCH_NONCE.
ORC-03 — Startup sequence and service wiring (P0)
Ordered; "await" = blocking. Source main.mjs:333-4212 (construction) and 6862-7068 (ready phase).
- Response-timing log →
logs/response-desktop.jsonl(bounded 512 KiB, rotate to.1). - Runtime context
rt(gateway port, URLs, token path, workspace, logPrefixcapri). Verification overrides: stateDir$DIR/openclaw, workspace$DIR/workspace, gatewayPortCAPRI_DESKTOP_VERIFICATION_PORT(default 18790), logPrefixdesktop-verification. - await legacy private storage key (
DS/private-data-key.json, OS-sealed) — used only to open legacy sealed transcripts. - 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'). rt.inferenceUrl = remote ? http://127.0.0.1:(gatewayPort+2) : ollamaUrl. Auxiliary runner params{num_ctx: contextTokens, ...local runner options}(frozen).- Validate
gatewayPortinteger 1024..65535 else throwInvalid local Gateway port. mkdirDS,DS/profile,DS/crashes;initialize(rt)(runtime config files). - Avatar catalog load (
loadInstalledAvatar), startup intro pack (if animated),StartupIntroGate; restoreDS/presence.json,DS/dimming.json,DS/avatar-layout.json,DS/avatar.json(each read only if < 4096 bytes andschemaVersion===1);AvatarState; alpha-mask LRU (max 20 entries). - Window prefs
DS/window.jsonwith migration (ORC-12).TranscriptStore(DS/transcript.json);AttachmentHistory(DS/conversation-attachments)+ immediate prune. - 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. - ScreenshotFiles (
data/screenshots),DS/last-screenshot.json; RequestRouter;responsiveness(); WebSearch; ChatService (wiring in ORC-25). - Voice:
voiceEnabled=false(speech is opt-in per session; only verification withCAPRI_DESKTOP_VERIFICATION_VOICE=1readsDS/voice.json);voiceAvailable = companionVoiceInstalled(); VoiceService(url, headers, enabled = allowed && enabled, language = available ? resolved speech language : 'off'). - ASR config from
config/companion-asr.json(mutated in memory: trailingSilenceSeconds fromDS/speech.json, language from languages prefs); MicrophoneService(ASRWorker) withinterrupt= chat.cancel + cancelVisual + voice.cancel andsubmit= wait for current task thensubmitMessage(value,'microphone'). - 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, Escapebefore-input-eventhook, CompanionActions (approvals broker, time, files, apps, Spotify), TimeConversation, ReminderDelivery →reminders.start(). - Register
second-instance,before-quit(ORC-09),window-all-closed→ quit. - Ready phase (async):
brain.start()(not in verification); awaituserTools.refresh()(on failure warnUser tools could not be listed. Open Settings to retry.); install permission handlers (ORC-42); registercapriprotocol handler; awaitcompanionActions.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). - First-run routing (ORC-50);
discordPresence.start(); windowminimize→ resetCallAudio; power monitor handlers (ORC-41); windowshow→syncInitiative(); startcontrolTimer(ORC-02/ORC-53). - Model services (ORC-04) await
startModelServices(...);startup.finish(); awaitsyncInitiative()(error other than AbortError → eventinitiative.error"App awareness could not start."). - Any exception in 15-17 →
Desktop startup failed: <msg>on stderr andapp.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+ (modelsif preload) + (recognitionif preload ∧ !verification ∧ ASR allowed ∧ installed ∧ microphone capture active ∧ language≠off) + (voiceif preload ∧ !verification ∧ voice.enabled ∧ language≠off). Because voice is disabled and the microphone is off at process start, a cold start only warmscore/models; voice/recognition warm only on wake (ORC-06). startModelServices({core, recognition, voice, sequential, voiceFirst, shouldContinue}): voiceFirst → run voice alone first, stop withModel startup cancelledifshouldContinue()false, then the rest;sequential(low-memory) → run core, recognition, voice in order, break when core rejected orshouldContinue()false; else all in parallel (allSettled). Result order[core, recognition, voice].shouldContinue = !shuttingDown && power ≠ 'sleeping'.- Each optional stage is wrapped:
begin(key), on successend(key), on errorend(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 defaultscore 15, models 12, recognition 8, voice 25; measured durations (seconds, float, ≥1) saved toDS/startup-times.jsonatfinish(); every change emitsstartup.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 ∨ resourceProfileminimal∨ accelerationcpu.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 logsCapri local core: <phase>and emitsbackend(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); throwsCapri is shutting downwhen 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 → awaitinferenceApi.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 forCAPRI_OLLAMA_BUNDLE_INCOMPLETE, else the generic message; rethrow. Abortable viabackendController.startCoreorder (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 <name> is missing. Run scripts/pull-models.mjs.) → gateway → stagecoreready → 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/<logPrefix>.primed.json) → stagemodelsready/failed.- Post-turn health check: if the last stored message has status
error, GET{gatewayUrl}/v1/modelswith 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(throwsWait 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 emitspower.state {phase}(suppressed afterclose()).
| 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; thensyncInitiative(); finallystartup.finish().- Sleep command (
isSleepCommand, 18-31): NFKC, lowercase, normalize quotes, strip leadinghey/эй,capri/капри+ punctuation, stripplease/пожалуйста; 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 choiceSleepandwindow-action sleep(confirmationUnload models and sleep?) also sleep. visuallySleeping(power, backend): false if power ∈ {notifying, voice-awake}; true if power ∈ {sleeping, asleep} or backend ∈ {offline, stopping}.avatarTapsSleepingadditionally true for powerwakingor backend ∈ {sleeping, asleep}.- Sleep caption (renderer):
sleepCaption(ms): tick = floor(ms/500); mask = floor(tick/3) % 8; three letters, bit i set →Zelsez, then 1-3 dots (tick % 3 + 1).
ORC-07 — Quit and unload (P0)
- Entry: close button (
capri:quit), trayQuit 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.; awaitcomputerControl.stop(). - Confirmation (multi-choice, ORC-20): title
Quit Capri?, detailCapri will close and unload the local models. Any active reply will stop., choicescancel: Cancel,sleep: Sleep,restart: Restart,confirm: Quit and unload models (danger).- cancel → return; sleep →
sleepService.sleep(); restart → ORC-08shutdownForRestart('Preparing to restart Capri...')+ relaunch + quit (on error:shuttingDown=false, offlineReconnect 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: logShutdown failed:,shuttingDown=false, restart avatar pointer, offlineSome services could not be stopped. Use stop.cmd or try again.
- cancel → return; sleep →
- 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 <message>; await pending; stopCore. Failure →shuttingDown=false, offlineReconnect to try again., rethrow.queueDesktopRelaunch(): relaunchroot/Capri.exeif present elsenode 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; titleCapri; 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 viacapri:regions(≤32 control rects, sprite rect with optionalenabled,sourcecrop (unit box),lens {rect, curve 0..0.06}, optionalfootprint); 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 compactfootprint(visible sub-rectangle) is published, the window may extend off-screen as long as the footprint stays inside the work area (placeVisibleInWorkArea);compactPlacementremembers 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 usingsetBounds(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, updatecompactPlacementif 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.jsonv3 ={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).footprintkept only if it validates against 480×660;compactPlacementkept 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 writesalwaysOnTop: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 runstopHiddenCompanion(); unless focus/locked/shutting/quitting and ifcompanion.minimizedChip !== falseshow 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. Windowminimize→ 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 + emitfocus-input; else show inactive.restoreCompanion(focus=true): clear focusMode/avatarOnly, show, emitwindow.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; emitwindow.focus-mode {active:true}. Wake phrase and replies do not reveal the window while in focus mode; voice/mic keep running. Exit: tray click, trayShow Capri, Ctrl+Shift+Space,window-action focus-mode false. Not persisted (ends on exit). - Wake auto-reveal: event
microphone.wakethat is neither manual nor follow-up, withcompanion.restoreFromTrayOnWaketrue, 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 viacapri:chip-dragactionsstart/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 oncapri: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(Windowsapp.ico) (6769). Initial tooltipCapri desktop companion. Tooltip recomputed onmicrophone.settings,initiative.status,languages:"Capri — " + join(", ", [mic capturing ? "Microphone (<Language name>)", 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):
registerEscaperegisters a globalEscapeshortcut 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: widthmin(680, workArea.w-24), heightmin(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; titleCapri 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 sendssettings.navigate {section, focus}orsettings.resumewhen 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 (backoffmin(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}ornull→ 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 noticeSettings 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 emitsstartup-intro.skip; mapsmemory→dialogue,dimming/motion→window,model-context→ sectionmodelswith focuscontext; 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: <confirmLabel or 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:
- Call-audio diagnostics observe.
companion.settings,languages,speech.settings,initiative.settingsgetsettingsVersionsattached. file-access→ cancel pending action approval. All events go to reminder listeners (used by spoken reminders).conversation.cleared→ clear temporal focus.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).- Forward to Settings unless the type is
voice.chunk,voice.audio,voice.segment,voice.generated,voice.call-started,microphone.partial, or starts withturn.;confirmation.requestonly when Settings is visible (and then not forwarded to the companion). 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.- Non-preview
dimming,avatar.layout(zoom),voice.effects,languages(interface),settings.set-portraitare overridden by active previews. - Follow-up bookkeeping (ORC-34);
voice.error/voice.cancelleddrop pending follow-up. - Wake auto-reveal (ORC-13). Mic activity (
microphone.partialwith text,microphone.activity,microphone.wake) → cancel click reactions,lastSpeechUntil = now + 5000 ms, initiative + observation activity. - Tray tooltip refresh (ORC-14).
- 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 withsettingsHost.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.
- 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.);modeabsent orcomputer;thinking/internetbooleans (Invalid message/Invalid message mode/ …). - Avatar movement command (
desktopAvatarCommand, before any model/tool; stripscapri/капри, please, final punctuation): return (return/go back/come back/teleport back to your/the frame/windoworhome, Russian equivalents) or perch (sit/perch on (top of) (the) (active/current) window [title],sit/perch on the <name> 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). - 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. - 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. - 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 answerUse 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), emitturn.started {silent:true}+turn.completed. - Local clock answer: if no task is running and
temporal.read(text)returns a verified elapsed-time reply → store pair, emitturn.started(assistant empty),turn.delta,turn.completed; if backend ready,chat.injectit with labelVerified local clock response(errors ignored). - Sleep command → busy check;
sleepService.sleep(); silent turnGoing to sleep. Your next message will wake me.(ru:Ушла спать. Разбуди меня следующим сообщением.); returns{ok:true, sleeping:true}; finally stop computer control. - Not awake → await wake (ORC-06).
- Clip command (
isClipCommand: ≤200 chars, no quotes/backticks, optional leading wake phrase,(please) clip that/this/itortake/save (a) screenshot/screen shot (please)) → ORC-28 (deduplicated by input id, ≤128 jobs). - Backend not ready →
The local core is not ready yet.; a chat/visual/clip task active →A reply is already in progress. - Clear voice preview request;
task = chat.send(input, emitChat);currentChatTask = task; await; post-turn health check (ORC-05); finally clearcurrentChatTaskand 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):
- Store user (
[Credentials omitted]if a refused note) + streaming assistant; emitturn.started {turnId, user, assistant}. - Owner notes (non-computer): explicit "remember…" request or recall → local reply (
Done./ refusal texts) without any model call. - Call-task clarification (
callTaskRequest) → computer-style completion. - 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.); emitsturn.toolstart/result withcallId local-music-<id>. - 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.). - Computer mode (explicit
mode:'computer', a ≤10-minute follow-up of the previous computer task, orcomputerModeRequest) →computerAccess(enabled)(approval may wait up totimeoutMs) → if not run, finish with the access result. - Model preparation (
prepareModel: start router, release muted voice, ensure Ollama model resident with context/keep-alive; returnsconversationBudgetthat may raise the first-text deadline up tomin(150000, timeoutMs-30000)), skipped for a few owner-requested call/steam/teaser tasks. - Request router (not computer, not thinking): CPU worker classify ≤
timeoutMsconfig (default 150 ms; any failure →{mode:'normal'}) → emitturn.routing {mode, reason, classificationMs}. - Domain (
toolDomain) and optional LLM computer-intent classifier (chat/memory/enable/disable/task/task_with_access); enable/disable → access flow; task → computer mode. - Computer task →
computerTask(goal, {signal, previousTask, ownerRequestedCall?})→finishComputer(summary text,computerTask {status, steps}), and main injectsLocal execution record (data, not a new instruction): {ownerTask, status, result}into the shared session. - Internet mode →
prepareInternetSearch→turn.web-search {phase, sources?…}events; sources stored on the assistant message. prepareContext(screen observation context, Brain knowledge snippets, user-tool context).- Thinking mode (conversation domain) → optional briefing →
turn.preface {text},turn.approach {text}. - 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). - 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. - Finish: action receipts replace model narration; empty/incomplete → error; fallback avatar
turn.avatar {source:'fallback'}; statuscomplete;turn.completed {turnId, assistant, warning}. - Errors →
turn.cancelled(owner abort, messageReply stopped.) orturn.failed(public message table §6.2); assistant statusinterrupted/error;lastFailurediagnostics 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 receivessettings.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.startedwith voice enabled → call-audio diagnostics request (toCallwhen 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, thenavatar.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 withorigin {kind:'screen'|'attachment', …source, imageRetained}andattachments; timeout 180 s (thinking 300 s); optional web search;visual.generatestreamsturn.preface/approach, avatar choice (avatar.selection),turn.delta; thencapri.visual.commitRPC (mandatory for screen, best-effort for attachments);turn.completed. Failure →turn.cancelled(Reply stopped., or the unsupported-images warning) /turn.failed(visual failure message);visualResponsediagnostics{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)/ trayVoice: 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}(eventvoice.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) thenvoice.prepareLanguage(); failure →lastVoiceFailurediagnostics andvoice.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.startedbegins a voice turn if enabled ∧ language≠off ∧ not errored;turn.preface(≤240 chars, once) is spoken first; deltas are split into sentences (SentenceBuffer), sentence overMAX_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; emitsvoice.timingthenvoice.audio {turnId, sequence, text, sampleRate:24000, pcm(base64)}; at the endvoice.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; emitsvoice.preview-started {turnId, effects}; speaksVOICE_PREVIEWS[lang](en:Hey choom, I am right here. How does this sound?).- Language change (
capri:languages, 6197-6244): refuse withWait 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; emitlanguages.
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); restoredstreaming→interrupted; unreadable file → in-memory only + warningThe local transcript could not be restored. Capri’s shared memory is still available.(never overwritten except by explicit clear); save failure warningThe 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.startedcreates/updates message views, resets subtitle state, records paint start; first visibleturn.delta→capri:response-painted {id, elapsedMs}after two animation frames; terminal events finalize the view, set status label (Stopped,Response incomplete), showevent.warningor the failure message as a notice, and announceCapri has replied.(a11y live region). - Subtitles (
renderer/subtitle-controller.mjs): cue sizemax(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 labelREPLYING/THINKING…/STOPPED/RESPONSE INCOMPLETE; manual previous/next pauses auto-advance;n / totalposition. - Auto-hide (
renderer/reply-visibility.mjs): enabled byreplyAutoHide(default true), delayreplyAutoHideSeconds(2..60, default 8 s); text-only replies getmax(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:activityat most every 150 ms;capri:draft-statewhen 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} elseThe selected speech recognition model is unavailable. Run setup-multilingual.cmd.; returns{...session snapshot, deviceId, deviceLabel…}; ifwakeSound==='voice'and awake and idle → prepare the cached wake voice in background (CAPRI_VOICE_DISABLED→voice.warning, elsewake.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 → failMicrophone 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) andcapri:microphone-device(id): if the effective device changes while capturing, stop and emitmicrophone.device-changed {…, restart:true}(renderer restarts). - Main forwards
microphone.*events (§5.1.3);microphone.partial final autoSend:falsetext 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 asavatar.detach {phase}(attached/leaving/detached/teleporting/returning). Back toattachedclears 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 bridgeavatar_windowquery, 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-<uuid>. 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(reasonsystem-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/<uuid>/(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-<ISO with :. → ->.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); sessionbegin()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, captionComputer control active — press Escape to stop; demote companion layer; overlay loss → emergency stop.hideBorderrestores 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 withmode:'computer'(requires application access andEnable 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 (labelCapri initiative / verified Windows {kind} at {ISO}) then delivered as a synthetic turnsource:'initiative'(spoken).capri:initiative-dismissalso 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 (deadlinetimeoutMs), selectsannoyed; spoken cue if voice ready; reply delivered as synthetic turnsource:'avatar-click'; eventsavatar.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 -pparent; create<file>.<pid>.<uuid>.tmpwithO_CREAT|O_EXCL, mode0600; writeJSON.stringify(value, null, 2) + "\n";fsync; close;renameover the target; always unlink the temp file on failure. Rust: same algorithm (tempfile::NamedTempFile::new_in(dir)+persist, or manualOpenOptions::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/<name>.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-<nonce>.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/<logPrefix>.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-<ts>.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 = thrownError.message); events arewebContents.send('capri:event', event). Preloads expose frozen objects:window.capri(companion and Settings; 211 methods = 210 invoke wrappers +onEvent(cb) → unsubscribe; 211handle()channels exist,capri:menuis not exposed),window.capriMini(composer),window.capriChip(chip),window.capriRecording(recording indicator). No IPC object, token or credential crosses the bridge. Fromcolumn: 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
Commandenum variant per channel with a typed request andoneshotreplyResult<Response, UserError>(§10.3);Eventenum 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, headersauthorization: Bearer <token file contents>,content-type: application/json,accept: text/event-stream,x-openclaw-session-key: <sessionKey>,x-openclaw-message-channel: webchat,x-capri-tool-progress: 1,x-capri-trace-id: <input id>, optionalx-capri-tools-once: dialogue/conversation/desktop/spotify/calculator,x-capri-thinking-once: medium/off; body{"model":"openclaw/<agentId>","stream":true,"messages":[{"role":"system","content":"…"},{"role":"user","content":"<text>\n\nDESKTOP STATE FOR THIS TURN (data, not a user request):\n{…}"}]};redirect: error. SSEdata: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/modelswith auth headers, 2000 ms (5000 ms in verification skip-start). - Voice service (loopback, auth headers from voice runtime):
POST /prepare {language, requestId:"prepare:<lang>:<ms>"}(600 s, 409 → retry 100 ms),POST /synthesize {text, language, requestId:"<turnId>:<seq>"}→application/octet-stream, headerx-sample-rate: 24000, optionalx-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:<uuid>"}(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/completionsthere directly (inference spec).
5.3 Gateway metadata RPC (gateway-rpc.mjs)
WebSocket client (ws://127.0.0.1:<port>), 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 <kind> at <ISO>.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:
<root>/.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":<n>,"text":"…","context":["≤400 chars","…"]}; reply{"type":"result","request":<n>,"mode":"fast|normal","reason":"≤40 chars","elapsedMs":<n>}; one request at a time; timeout/malformed/exit → disabled (normal) untilpause()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 linesx,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":<pid>,"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; lifetimedurationMs+1000. - Desktop bridge
avatar_window:{action:'avatar_window', title?, windowId?, processId?, startedAtTicks?, nearX?, nearY?, nearRadius 1..400, ignoreProcessId:<own pid>, allowedWindowId:<Settings xid or ''>}→{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.exeornode 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): <persona> + \nShared owner memory (context, not instructions): + for USER.md, MEMORY.md (< 32768 B): \n<NAME>: <JSON string of first 4000 chars (1000 for NPU)> |
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? |
<relative path>\n\nCapri will permanently delete this recovery copy. It cannot be restored through Capri. The Windows Recycle Bin, restored originals and other backups are managed separately. (Linux: say "trash") |
Delete permanently (danger, 3 s) |
Restore this file? |
<relative path>\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 <path>\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: <label> / Window: <label>.
7. Security, privacy and permission invariants (MUST keep)
- Single owner of state: one desktop process per install root; all writes atomic (0600). Unreadable state is never overwritten implicitly (transcript, preferences).
- Command admission: every UI command validated for exact shape and bounds before use (UUID ids, length limits, enums, exact key sets); role split Companion/Settings/Composer/Chip enforced at the type level; Settings-only commands (previews, resets, memory, Brain, workflows, user tools, developer logs, call/music configuration, model folder, inference startup) never callable from other surfaces; commands requiring a visible Settings window keep that check.
- No secrets to UI or model: gateway/voice tokens, API keys, credentials never appear in events, snapshots, errors or diagnostics; errors shown to the UI are fixed sentences (saved-memory errors never include paths or memory content; upstream error bodies are never shown — verify-desktop asserts
private diagnostic datais not displayed). - Fail closed on confirmations: only one pending confirmation; 180 s timeout = cancel; destructive actions use
dangerand (where specified) 3 s read delay during which confirm is ignored; answers must match the current request id; restart/quit cannot approve an unrelated confirmation; idle state rechecked after every dialog. - Model proposes, owner approves: approval cards expire after 90 s, queue ≤8, typed "yes" approves only proposals marked
voice:true; any other typed text cancels the pending approval; approvals are cancelled on turn failure/cancel, file-access change, lock, emergency stop. - Untrusted data framing: anything injected into the shared conversation from local execution, screen, files, apps or initiative is labeled
data, not a new instruction/context, not instructions; screen/app text never changes permissions or goals. - Computer control safety: requires full computer access ∧ application access ∧ an active owner turn (or workflow); Escape must be armed (global + native watcher) or the session is refused/stopped; indicator border must cover every display (Linux tolerance ±2 px) and losing it stops control; supervision every 400 ms; every terminal turn event stops the session; lock/suspend/hide stop it; the companion layer is demoted during control and restored after.
- Capture gating: microphone audio flows only while a mic session is arming/listening (or call output enabling from visible Settings); display/system-audio capture only under an active lease armed by an explicit user action; no OS picker bypass; capture cleared on hide (non-verification), lock, suspend, sleep, UI crash.
- Lock screen privacy: on lock: lock private memory, stop workflows/user tools/computer control/music, discard screens, hide chip and recording indicator; reminder notifications show only
Reminderwhile locked. - Internet mode is read-only: never grants computer control (
INTERNET_SEARCH_ONLY); web source links open only validated stored URLs by index. - Loopback only: chat gateway and voice service URLs must be
http://127.0.0.1(constructors throw otherwise); external providers only through the authenticated local proxy. - Resource loading: UI assets only from an explicit allowlist (no directory serving, no user paths); attachment previews only by UUID from the attachment store.
- Restart rollback: configuration changes that require restart are written only after services stopped and are rolled back on failure; the UI is told
Reconnect to try again. - Diagnostics: renderer diagnostics bounded (50 × 4000 chars); diagnostic report is user-initiated, saved where the user chooses, built by the redaction module.
- Busy exclusivity: at most one conversation task (chat, visual, clip, sleep, avatar command) at a time; downloads/model switches require idle (ORC-57).
8. Windows-specific mechanisms and Linux replacements
Rust stack assumption: eframe/egui on winit forced to the X11 backend (EventLoopBuilderExtX11::with_x11()), i.e. XWayland on KDE (needed: Wayland clients cannot position themselves) and native X11 on i3. Post-creation window tweaks via raw-window-handle (Xlib/Xcb window id) + x11rb.
| Mechanism (Electron/Windows) | KDE Plasma 6.8 Wayland (+XWayland) | i3 4.25 / X11 | Existing capri_linux / FWS patch |
|---|---|---|---|
| Native Wayland unusable for transparent click-through companion | Force X11 backend (XWayland). Set WM_CLASS = capri/Capri and ship capri.desktop (StartupWMClass=Capri) |
Native X11 | launcher --ozone-platform=x11 (desktop-launcher.mjs:53-55, ~/.local/bin/capri) |
Global cursor position (screen.getCursorScreenPoint) |
XWayland only knows the pointer over X11 windows → load a persistent KWin script that callDBuses workspace.cursorPos on cursorPosChanged (throttle 4 ms) to a D-Bus object owned by Capri (zbus), unload on exit/crash recovery; fallback to X11 QueryPointer |
x11rb QueryPointer on root (always global) |
main/linux-cursor.mjs, capri_linux/cursor.py (same script; name org.capri.cursor.p<pid>, plugin capri-cursor) |
Click-through setIgnoreMouseEvents(true,{forward}) + 16 ms polling |
Prefer X11 SHAPE input region (shape::rectangles kind INPUT) = union of control rects + sprite alpha-mask rectangles; recompute on capri:regions/frame change; keep cursor polling only for hover features |
same SHAPE input region (works without compositor) | FWS patch re-enabled Electron pass-through on Linux using the KWin cursor (main/secure-window.mjs:44-47) |
| Transparency | KWin compositor: ARGB visual (ViewportBuilder::with_transparent(true)) |
Needs a compositor (user runs picom from i3 config). Detect _NET_WM_CM_S0 owner; if absent apply SHAPE bounding region from alpha mask (1-bit edges) |
— |
Always-on-top levels (normal, screen-saver) |
_NET_WM_STATE_ABOVE; overlays (control border, detached avatar, composer) as override-redirect or _NET_WM_STATE_ABOVE + re-raise every 750 ms (ConfigureWindow stack_mode Above) |
i3 ignores ABOVE; make windows floating (+sticky) via i3 IPC [id=<xid>] floating enable, sticky enable, border pixel 0; full-screen overlays as override-redirect (unmanaged, always above) |
main/control-overlay.mjs:150-157 (±2 px tolerance) |
| skipTaskbar | _NET_WM_STATE_SKIP_TASKBAR + _NET_WM_STATE_SKIP_PAGER (re-assert on map) |
no taskbar; harmless | main/tray-only-windows.mjs |
| Window type | _NET_WM_WINDOW_TYPE_UTILITY (companion, Settings), _NOTIFICATION/override-redirect for overlays |
UTILITY makes i3 float it (user config has for_window [window_type="utility"] floating enable); still send the IPC command for robustness |
— |
Work area (display.workArea) |
_NET_WORKAREA (KWin publishes for X11 clients) intersected with RandR monitor rects |
i3 does not publish _NET_WORKAREA: use i3 IPC GET_WORKSPACES visible workspace rect per output (excludes bars) |
kwin.py/x11.py expose outputs |
| Display add/remove/metrics events | RandR ScreenChangeNotify/CrtcChange via x11rb |
same (+ i3 output IPC event) |
— |
| Global shortcut Ctrl+Shift+Space | KGlobalAccel D-Bus: doRegister([comp,action,"Capri","Show or hide Capri"]), setShortcutKeys(…, [[0x06000020,0,0,0]] /* Qt CTRL∣SHIFT∣Key_Space */, flags), listen globalShortcutPressed on /component/<comp>; or XDG GlobalShortcuts portal (consent dialog) |
XGrabKey on root for Ctrl+Shift+space (all lock-modifier combinations) via x11rb; document optional bindsym alternative |
capri_linux/escape.py shows the KGlobalAccel pattern |
| Escape emergency stop (global) | KGlobalAccel registration of Escape for the control session only, always unregistered (also stale entries) | XQueryKeymap polling every 20 ms (or XGrabKey Escape during session) |
capri_linux/escape.py, main.py:822-842; native watcher enabled on Linux by FWS patch (main.mjs:3767) |
Tray (Tray, app.ico, popUpContextMenu) |
StatusNotifierItem via ksni (KDE host native); icon PNG assets/default/icon-source.png; menu via dbusmenu (ksni) |
i3bar is XEmbed-only: run snixembed (installed on host) or implement XEmbed; document requirement |
FWS patch uses PNG on Linux (main.mjs:6769) |
| Notifications | org.freedesktop.Notifications (KDE) |
same (dunst installed) | — |
powerMonitor lock/unlock/suspend, getSystemIdleState('locked') |
logind: Session.Lock/Unlock signals, LockedHint property; Manager.PrepareForSleep(bool); also org.freedesktop.ScreenSaver.ActiveChanged |
logind signals (screen lockers like i3lock do not set LockedHint unless integrated via xss-lock; treat org.freedesktop.ScreenSaver / xss-lock as best effort) |
— |
Single-instance lock + second-instance |
D-Bus well-known name org.capri.Companion.i<hash(root)> with method Show(nonce); or abstract Unix socket |
same | — |
RUN/desktop.show/stop polling |
keep (CLI compatibility), 400 ms | same | — |
shell.openPath/openExternal/showItemInFolder/trashItem |
xdg-open (or open crate); org.freedesktop.FileManager1.ShowItems; trash crate (FreeDesktop trash) |
same | — |
| Native dialogs | rfd with xdg-portal backend (pure Rust, zbus) — KDE portal FileChooser |
portal may be unavailable → rfd gtk3 backend (pkg-config, no bindgen) |
— |
| AppUserModelID, Capri.exe branding | N/A (WM_CLASS + .desktop) | N/A | — |
app.relaunch() |
spawn current_exe with original args after full shutdown; new process retries the instance lock for up to ~5 s |
same | — |
| Explorer desktop context verb "Teleport Capri" + native window watcher | No shell hook: tray item + optional KGlobalAccel action; perch tracking via KWin script on frameGeometryChanged/windowRemoved or 1.8 s re-query (avatar_window) |
i3 IPC SUBSCRIBE ["window"] (move/close/focus) + 1.8 s re-query |
capri_linux/main.py:739-794 (avatar_window), kwin.py, x11.py |
| Chromium media permission handlers | N/A — enforce by only starting capture pipelines in the armed states (§7.8) | same | — |
enumerateDevices (mic/call outputs) |
PipeWire/Pulse via pactl -f json list sources/sinks (external, read-only) or cpal ALSA names (audio spec) |
same | — |
| VB-CABLE call output (Windows) | P2: PipeWire null sink + loopback via pactl load-module module-null-sink sink_name=capri_call (external) |
same | — |
| System audio loopback (music, call review) | P2: capture <default sink>.monitor via pw-record/parec subprocess (no pipewire-rs: bindgen) |
same | — |
| DIP coordinates | Fractional scaling: XWayland clients may see physical px while KWin scripts report logical px — convert with the output scale (open question §12) | scale = Xft.dpi/96 | — |
9. Interfaces with other subsystems
9.1 Consumed (traits the orchestrator needs; names from source)
| Subsystem | Calls used by the orchestrator | Events it emits onto the bus |
|---|---|---|
| Runtime/core (Ollama + chat backend) | start_core(opts{preload, voice_expected, voice_ready, on_stage, cancel}), stop_core(companion=false), health(), ensure_model_ready(params, cancel), responsiveness(), context_sampler.sample/peek/invalidate, settings (model, contextTokens, …) |
stage callbacks → startup.progress |
| Chat engine | send(input, emit), cancel(id?), active, diagnostics(), assert_tool_allowed(tool,args), record_tool_result, computer_progress(), computer_approval(pending); needs callbacks interface_state(), prepare_context(), prepare_model(), computer_task(), computer_access(), local_calculation(), local_music(), persona() |
turn.* |
| Session/memory store (replaces gateway RPC) | inject(session, message, label), visual_commit(...), reset(session), describe(session), clear_saved_memory(), save_owner_note, read_saved_memory, personality read/save |
— |
| Voice (TTS) | snapshot/diagnostics, enabled/ready/language/error/turn/running/generating, set_enabled, set_language, prepare_language, set_ready, fail, close, cancel, preview(turn,text), on_chat(event); process start/stop; residency release |
voice.* |
| Speech recognition | microphone session API (ORC-33), continue_listening, cancel_continuation, configure_pause, worker start/close/language, audio input settings |
microphone.* |
| Avatar/animation | catalog (sprites, frames, canvas, intro), AvatarState, alpha masks, detached avatar controller (leave/hop/return/updateFrame/followFrame/send*), composer, click reactions |
avatar.* |
| Screen | capture policy, observation, clip frames, screenshots, visual service | screen.* |
| Computer control | control session, agent, requests, workflows, escape watcher, overlay | computer.*, workflow.status |
| Capabilities | application access, full computer access, file permissions, desktop catalog, companion actions (approvals, time, files, apps, Spotify), user tools, Brain, private memory | action.approval, time.changed, file-access, applications, application.access, computer-access, brain.status, private-memory.status |
| Time/reminders | ReminderDelivery callbacks (ORC-39), TimeConversation.read/observe/context |
time.due, reminder.* |
| Models/updates/HF/voice catalog/training/speech install/Spotify/Discord/inference API | delegated command handlers (§5.1.2), busy(), close() |
*.status |
| Initiative/awareness | configure, activity({quietMs}), cancel, close, tick, dismiss/restore, observer start/stop |
initiative.* |
| i18n | ui_text(key, lang, vars), language names, locale direction |
— |
| Diagnostics | timing log, report builder, developer diagnostics | — |
| Platform (this spec, §8) | windows, tray, shortcuts, notifications, lock/suspend, single instance, dialogs, open/reveal/trash, cursor, work areas | display/lock events |
9.2 Provided by the orchestrator
EventBus::emit(Event)with routing (ORC-23) and Settings-onlysend_settings(SettingsMessage).Confirmations::{request, choose, respond, cancel}(ORC-20); approval UI routing.- Read-only
CompanionStatesnapshot:backend_phase,power_phase,companion_present(),session_locked,shutting_down,playback_busy,interface_busy,draft_busy,last_speech_until,active_turn_id,focus_mode,avatar_only,renderer_ready. interface_state()for the chat engine:{applications (masked by access), spotify{…, enabled ∧ access}, applicationAccess, fullComputerAccess (∧ access), followUp (setting ∧ mic listening), languages (live), microphone (listening), microphoneLanguage, wakePhrase ('Capri / Hey, Capri' or null), screenObservation (context), screenVisionAvailable, modelToolsAvailable, recentScreenshot, temporalContext}(main.mjs:946-966).prepare_context(input)= screen context +knowledgeContext+userToolContext;prepare_model()(router start, voice residency release, model readiness, conversation budget).- Lifecycle:
submit_message(input, origin),connect_backend(),sleep()/wake()/wake_for_reminder(),shutdown_for_restart(msg),queue_relaunch(),quit_and_unload(),emergency_computer_stop(),open_settings(section, focus),show/hide/restore companion,companion_display()geometry. - Computer-control hooks:
register_escape/unregister_escape,show_border/hide_border,capture()(active display PNG scaled to ≤1280×720),call_focus_window()(only Capri/Settings windows).
10. Recommended Rust design
10.1 Crates / modules
capri/ (bin) argv, single instance, logging, tokio runtime, eframe main loop
crates/capri-protocol/ Command, Response, Event, SettingsMessage, Surface, UserError (serde)
crates/capri-core/ orchestrator actor, state machines, startup/shutdown, event routing,
preferences + atomic JSON, transcript store, confirmations, timers
crates/capri-ui/ egui views: companion, settings, composer, chip, recording, overlays,
viewer; presence model, subtitles, reply pages, reply visibility
crates/capri-platform/ linux: x11 (x11rb props, SHAPE, RandR, keygrab), kwin (zbus scripts,
kglobalaccel), i3 (IPC socket), logind, notifications, tray (ksni),
dialogs (rfd), open/reveal/trash, cursor provider
(+ subsystem crates from the other specs: chat, voice, asr, avatar, screen, computer, …)
10.2 Concurrency model
- Main thread: winit/eframe event loop (all windows as egui viewports). Core: tokio multi-thread runtime; the orchestrator is a single actor task owning
CoreState(noMutexaround global state). - UI → core:
mpsc::Sender<Envelope { surface: Surface, cmd: Command, reply: oneshot::Sender<Result<Response, UserError>> }>. Core → UI:broadcast::Sender<Arc<Event>>drained each frame +egui::Context::request_repaint()wake-up; Settings-only messages on a separate queue that buffers (latest per type, ≤50) until the Settings view reports ready. - Cancellation:
tokio_util::sync::CancellationTokenper turn/visual/backend start/voice start;AbortSignal.any([...])⇒ child tokens +tokio::time::timeout. Serialized operations (sleep/wake, router, voice residency) as small actors with apending: Option<Shared<…>>join handle (futures::future::Shared). - Timers:
controlTimer400 ms interval task; pointer/hover 16 ms only when needed (SHAPE-based hit testing removes most polling); debounced saves viatokio::time::sleep+ generation counter.
10.3 Key types (sketch)
pub enum Surface { Companion, Settings, Composer, Chip, RecordingIndicator }
pub enum Role { Companion, Settings } // admission (ORC-21)
pub enum BackendPhase { Starting, Ready, Offline, Sleeping, Asleep, Stopping }
pub struct BackendState { pub phase: BackendPhase, pub message: TextKey }
pub enum PowerPhase { Awake, Sleeping, Asleep, Waking, Notifying, VoiceAwake }
pub enum WindowMode { Visible, Tray, Focus, AvatarOnly }
pub enum ActiveWork { Chat(TurnId), Visual { id: TurnId, kind: VisualKind }, Clip(TurnId), Sleep, AvatarCommand(TurnId) }
pub struct TurnInput { pub id: Uuid, pub text: String /*1..=8000*/, pub mode: Option<Mode>, pub thinking: Option<bool>, pub internet: Option<bool> }
pub enum Origin { Text, Microphone { session: Uuid } }
#[non_exhaustive] pub enum Command {
Bootstrap, SettingsVersions, Send(TurnInput), Cancel(String), Quit, Reconnect, Hide,
WindowAction(WindowAction), Regions(Regions), DragStart, DragEnd, PresencePinned(bool),
CompanionSettings(Revisioned<CompanionSettings>), Languages(Revisioned<Languages>),
SpeechSettings(Revisioned<SpeechSettings>), Initiative(Revisioned<InitiativeSettings>),
SettingsPreview(PreviewMap), SettingsReset, SettingsOpen(Option<String>), SettingsClose,
Confirmation { id: Uuid, choice: String }, ActionRespond { id: Uuid, accepted: bool },
VoiceEnabled(bool), VoiceStop, VoicePreview(Option<VoiceEffects>), /* … one per §5.1.2 row … */
}
pub struct Revisioned<T> { pub payload: T, pub expected_revision: Option<String> } // Some = from Settings
#[non_exhaustive] pub enum Event { TurnStarted{..}, TurnDelta{turn_id, text}, TurnCompleted{..},
TurnFailed{..}, TurnCancelled{..}, Backend(BackendState), PowerState(PowerPhase), /* … §5.1.3 … */ }
impl Event { pub fn route(&self, settings_visible: bool) -> Route { /* ORC-23 rules */ } }
pub struct UserError { pub key: TextKey, pub vars: Vec<(String, String)> } // localized on display
- Settings revision:
sha2::Sha256over the canonical serialization. Note: JSJSON.stringifykey order = insertion order; Rust must serialize the struct in a fixed field order (serde struct order) — revisions only need to be self-consistent within the Rust app. Preferences<T>:{schemaVersion:1, settings:T}, size limit 16 KiB,validate()trait, warning on load failure, atomic write.- Window creation:
egui::ViewportBuilder::default().with_transparent(true).with_decorations(false).with_resizable(false).with_taskbar(false).with_window_level(WindowLevel::AlwaysOnTop).with_inner_size([480.,660.]).with_position(..).with_visible(false); then platform hookplatform::configure_window(xid, WindowRole::Companion)(WM_CLASS, window type, skip-taskbar/pager, ABOVE, i3 floating, SHAPE). - Text/i18n:
TextKey= English source string; translation at the UI boundary.
10.4 Crates (no bindgen)
tokio, tokio-util, futures, serde, serde_json, uuid (v4), sha2, hex, thiserror, anyhow, tracing, tracing-subscriber, tracing-appender, time (RFC 3339), reqwest (rustls, stream) + eventsource-stream (SSE), eframe/egui (glow or wgpu; x11 feature), raw-window-handle, x11rb (features shape, randr, xtest), zbus (KWin scripting, KGlobalAccel, logind, notifications, FileManager1, single instance), ksni (tray), notify-rust (zbus backend) or plain zbus, rfd (xdg-portal; gtk3 fallback via pkg-config), open, trash, image (PNG decode for alpha masks), tempfile, fs-err. Avoid pipewire/libspa (bindgen); audio pipelines belong to the audio specs (cpal/subprocess).
10.5 Startup/shutdown in Rust
- Parse args (
--test-mode,--show, nonce env) → compute root → acquire instance nameorg.capri.Companion.i<sha256(root)[..16]>; if taken callShow(nonce)and exit 0. - Logging; tokio runtime; construct services in ORC-03 order (blocking steps preserved); spawn orchestrator; create windows; start
controlTimer; schedule model warmup (ORC-04). - Run eframe; quit requests come from the orchestrator (
ViewportCommand::Closeon all viewports after ORC-07/09 cleanup). - Exit: run the
before_quitsequence (ORC-09) synchronously on the core with a bounded timeout, flush debounced files, release instance name; for restart spawn the new process last.
11. Test plan
11.1 Capri tests worth porting (behavior to assert)
| Test | Asserts |
|---|---|
tests/desktop-boundaries.test.mjs |
IPC rejects subframes, stale windows, foreign senders; Settings channel allowlist; resource scheme allows only exact allowlisted GETs; hit testing ignores opaque decoration, drags expire after 30 s; only opaque sprite presses start gestures; transparent window drag never drifts in size |
tests/desktop-startup-order.test.mjs |
private paths/protocol registered before ready; runtime and stores initialized inside the async ready phase |
tests/settings-confirmations.test.mjs |
restart is an explicit choice and cannot approve another confirmation; read delay; cancellation; draft writes keep revision; expired approvals close the UI |
tests/sleep-service.test.mjs |
sleep/wake serialization, wake once, failed wake retryable, close prevents resurrection, sleep command grammar, caption sequence |
tests/model-startup.test.mjs |
first-launch preload consumed once; low-memory sequential order; failed core stops queued voice; optional recognition failure tolerated |
tests/startup-intro-gate.test.mjs |
one presentation per process, wait vs consume semantics |
tests/desktop-presence.test.mjs |
presence state derivation, pin/collapse, sleep reveal once, burst rules |
tests/settings-window.test.mjs |
Settings inherits pin, shows after paint+content, survives hide with drafts, intent sent once, close/crash handling |
tests/control-window-layer.test.mjs, tests/window-topmost.test.mjs, tests/tray-only-windows.test.mjs |
layer demotion/restore without saving; topmost policy; skip-taskbar enforcement |
tests/minimized-chip.test.mjs |
chip owner check, drag threshold/clamp, remembered position, recording indicator channel |
tests/avatar-composer-bridge.test.mjs, tests/avatar-composer.test.mjs |
composer action/state validation, placement around HUD |
tests/desktop-screen-ipc.test.mjs, tests/call-audio-ipc.test.mjs |
lease rechecks on every call; companion-only monitor frames; call command validation |
tests/native-escape-stop.test.mjs |
watcher arming, timeouts, failure handling |
tests/request-router.test.mjs, tests/conversation-route.test.mjs, tests/task-domain.test.mjs |
router fallbacks/cancellation; social-route regexes; domain selection |
tests/desktop-chat.test.mjs (55 cases) |
turn state machine: dedupe/concurrency, cancellation releases the turn, first-text and tool deadlines, stream parsing limits, receipts, error mapping, transcript restore (streaming→interrupted) |
tests/reply-pages.test.mjs, tests/reply-visibility.test.mjs, tests/desktop-subtitles.test.mjs |
paging bounds, auto-hide timing, subtitle/voice sync |
tests/desktop-avatar-commands.test.mjs, tests/desktop-window.test.mjs |
avatar command grammar; work-area placement and footprint clamping |
tests/managed-shutdown.test.mjs, tests/desktop-launcher.test.mjs, tests/startup-update-check.test.mjs, tests/inference-startup-settings.test.mjs |
process markers, stop/show files, launcher refusal rules, startup update check, inference-startup validation |
tools/verify/verify-desktop.mjs (+ verify-settings.mjs, verify-avatar-only-mode.mjs, verify-control-emergency-stop.mjs, verify-companion-voice.mjs) |
end-to-end with a fake gateway: session key header, exactly 2 messages (system + user), AVATAR CONTROL in system prompt, no [avatar: leakage, expressions from model, offline + reconnect flow, private upstream text never shown, subtitle paging indices, history panel toggling, window inside work area and sandbox flags |
11.2 New Rust tests
- Unit: each validator (input, regions, preview map, call command, composer action, settings),
Preferencesload/save/migration,window.jsonv1/v2→v3 migration, atomic write (crash between write and rename leaves old file), revision conflict and serialization, confirmation delay/timeout/choices, approval text parsing, sleep/wake FSM (tokiotime::pause), backend phase transitions (fake core), startup stage scheduling, event routing table (golden test per event type → C/S), follow-up decision, presence derivation, tray menu enablement matrix. - Integration (
--test-mode, fake chat/voice/core services): send → started/delta/completed ordering; stop during stream →turn.cancelled, voice cancelled, computer control stopped; busy rejection; local intercepts (approval yes/no, clock, sleep, clip, avatar command) produce silent/visible synthetic turns; quit dialog choices; restart rollback on injected write failure; lock/suspend cancellation set; UI crash recovery throttle. - Platform (optional CI under Xvfb + i3 headless, and manual KDE checklist): WM_CLASS,
_NET_WM_STATE_SKIP_TASKBAR/ABOVE, window type, SHAPE input region matches published rects, i3 floating via IPC, tray item registered on SNI watcher, KGlobalAccel registration/unregistration (also after crash), logind lock signal handling. Never inject input on the developer host.
12. Open questions
- Follow-up trigger: code (
voice-follow-up.mjs) opens follow-up listening when the final reply ends with a question mark; the prompt anddocs/companion-controls.mddescribe a model-chosen[avatar:ID;listen]flag, which is parsed and stored (assistant.followUp) but never consulted. Which rule should the Rust version implement (or both)? - Router worker on Linux: the Python path is
.runtime/router-venv/Scripts/python.exe(Windows layout), so the CPU router is silently disabled on the current Linux adaptation. Port the MiniLM classifier (e.g.,candle), keep a Python subprocess with a Linux venv path, or drop it? - OpenClaw removal:
chat.inject,capri.visual.commit,sessions.reset/describeand context-usage sampling need a native session store contract from the chat/memory spec (labels and "data, not instruction" framing must be preserved). - Call audio / music listening / system audio are Windows-only in 1.0.4; port in v1 (PipeWire null-sink + monitor capture via
pactl/pw-record) or keepsupported:false? - Desktop "Teleport Capri" shell verb and native perch watchers have no direct Linux equivalent; confirm tray item + KWin script / i3 IPC subscription is acceptable.
- Fractional scaling under XWayland (KDE "apply scaling themselves" vs "scaled by the system"): coordinate spaces of KWin cursor reports,
_NET_WORKAREA, and savedwindow.jsonpositions must be verified on the target machine. - Global Escape grab on KDE via KGlobalAccel steals Escape from all apps during computer control; acceptable, or use the GlobalShortcuts portal (requires a consent dialog)?
- i3 without compositor: bounding-shape fallback has hard edges; require picom (present on the host) or support both?
- Legacy sealed transcript (Windows-sealed key in
DS/private-data-key.json) cannot be opened on Linux; drop legacy support and show the existing "could not be restored" warning? RUN/desktop.stoponly quits the UI (services are stopped by the CLI); in a single Rust binary that manages Ollama itself, should the stop file also unload models?- Instance identity: Electron's lock is per profile directory (per install). Confirm the Rust lock should be per install root so two installs can coexist.
- Dead/legacy items to drop:
capri:models-select(allowlisted, no handler),capri:menu(no preload method),voice.chunk/voice.segmentevent names, Settings compositor-retry logic. - Confirmations in focus mode:
Confirmations.show()callsshowCompanion(true), which is a no-op in focus mode, so a confirmation raised from the tray while in focus mode (e.g. Quit) is emitted to a hidden window and auto-cancels after 180 s. Rust should leave focus mode (or use a standalone dialog) when a confirmation needs the owner. queueDesktopRelaunchunder Linux usesnode …/capri.mjs desktop; the Rust relaunch must re-acquire the instance lock after the old process exits — define the retry window (proposed 5 s).