### SettingsClient usage example Source: https://github.com/ayangweb/bongocat Shows how to use SettingsClient to inspect a model source directory and start a model import, handling different source content types (Mver, Package, Folder). Also demonstrates opening a model's location. ```rust use bongocat_ui_protocol::{ SettingsClient, SettingsModelImportRequest, SettingsMverMode, }; let client = SettingsClient::bounded(32).0; // 1. 检查用户选择的目录内容 let content = client.inspect_model_source("/path/to/model".into()).await?; match content { bongocat_ui_protocol::SettingsModelSourceContent::Mver { modes } => { // 界面据此显示转换选项复选框 let operation = client.start_model_import(SettingsModelImportRequest { title: "模型".into(), source_root: "/path/to/model".into(), selected_mver_modes: if modes.contains(&SettingsMverMode::Keyboard) { vec![SettingsMverMode::Keyboard] } else { vec![] }, }).await?; let _ = operation.final_result_blocking(); } bongocat_ui_protocol::SettingsModelSourceContent::Package => { /* 直接导入 */ } bongocat_ui_protocol::SettingsModelSourceContent::Folder { models } => { /* 让用户选子目录 */ } } // 2. 打开某模型的位置 client.open_model_location_blocking(model_key).ok(); ``` -------------------------------- ### Usage example: UpdateRuntime with observer for install progress Source: https://github.com/ayangweb/bongocat Shows how to use UpdateRuntime::for_current_build with Production environment and version "2.4.1". Checks availability and performs update check. On Available, installs with an observer that prints download progress, download finished, and signature verification events. After successful install, calls runtime.restart() which does not return on success. ```rust use bongocat_config::BuildEnvironment; use bongocat_update::{UpdateEvent, UpdateRuntime, UpdateDiagnosticsTracker}; let runtime = UpdateRuntime::for_current_build( BuildEnvironment::Production, "2.4.1", UpdateDiagnosticsTracker::default(), ); if !runtime.is_available() { println!("unavailable: {:?}", runtime.unavailability()); return Ok(()); } match runtime.check()? { bongocat_update::UpdateOutcome::UpToDate => println!("已是最新"), bongocat_update::UpdateOutcome::Available { release } => { // 用户确认后安装,观察每步事件 let outcome = runtime.install_with_observer(|event| match event { UpdateEvent::Progress(progress) => { println!("下载 {} / {:?}", progress.downloaded_bytes, progress.total_bytes); } UpdateEvent::DownloadFinished => println!("下载完成"), UpdateEvent::Verified => println!("签名验证通过"), }); match outcome { Ok(bongocat_update::UpdateOutcome::Installed { version }) => { runtime.restart().ok(); // 成功后不返回 } _ => {} } } bongocat_update::UpdateOutcome::Installed { .. } => unreachable!(), } ``` -------------------------------- ### PluginService start and client usage example Source: https://github.com/ayangweb/bongocat Shows how to start the plugin service worker, read the center snapshot, send an action, and shut down. The worker only reads installed packages in Production semantics. After a successful action, cards no longer carry interaction failures. shutdown() joins all plugin processes before returning. ```rust use bongocat_plugin_service::{PluginService, PluginServiceStartError}; fn run_service(storage_root: &std::path::Path) -> Result<(), PluginServiceStartError> { // 启动 worker(Production 语义:只读已安装的包) let (service, overlay) = PluginService::start(storage_root, 64)?; let client = service.client(); // 读取插件中心状态 let snapshot = client.read_center_blocking()?; for card in &snapshot.cards { eprintln!("{} v{} enabled={}", card.id, card.version.as_deref().unwrap_or("-"), card.enabled); } // 向运行中的插件发送一个 action let after = client.action_blocking("com.bongocat.pomodoro", "toggle")?; // 成功后卡片不再携带交互失败 let failed = after.cards.iter().filter(|c| c.interaction_failure.is_some()).count(); if failed > 0 { eprintln!("{failed} 个卡片的交互失败"); } // 关闭:join 所有插件进程后才返回 service.shutdown()?; Ok(()) } ``` -------------------------------- ### install(bytes, expected_sha256) Source: https://github.com/ayangweb/bongocat Installs a plugin from raw bytes with a SHA-256 digest check. Returns the installed package information or an error. ```APIDOC ## install(bytes, expected_sha256) ### Description Installs a plugin from raw bytes with a SHA-256 digest check. ### Method Method ### Parameters - **bytes** (&[u8]) - Required - The plugin package bytes. - **expected_sha256** (&str) - Required - The expected SHA-256 digest of the package. ### Returns - `Result` - The installed package or an error. ``` -------------------------------- ### Rust usage example for PluginManager Source: https://github.com/ayangweb/bongocat Shows how to use bongocat_plugin_manager to discover plugins, install verified bytes, enable, tick, and shutdown. Requires a valid SHA-256 digest from the signed catalog. The package_bytes placeholder is empty in the example. ```rust use bongocat_plugin_manager::{PluginManager, PluginSource}; fn main() -> Result<(), bongocat_plugin_manager::PluginManagerError> { let mut manager = PluginManager::new(std::env::temp_dir().join("plugins"))?; // 发现已安装包(Production 从不读本地构建目录) let found = manager.discover_plugins()?; println!("discovered {found} plugins"); // 从验证过的字节安装(digest 由签名 catalog 提供) let package_bytes: &[u8] = &[]; let installed = manager.install_verified(package_bytes, "")?; println!("installed {} at {}", installed.manifest.metadata.id, installed.root.display()); // 启动、tick、关闭 manager.enable_plugin("com.bongocat.pomodoro")?; let outputs = manager.tick(200); for (id, output) in outputs { println!("{id} published {} errors", output.errors.len()); } manager.shutdown()?; Ok(()) } ``` -------------------------------- ### Application 结构体定义与 start 方法签名 Source: https://github.com/ayangweb/bongocat 定义 Application 结构体及其 start 方法签名。start 负责启动装配,包括 config store、settings worker、runtime、audio、renderer、overlay、plugin service、update service 和应用日志等子系统。 ```rust pub struct Application { /* 各子系统 owner */ } impl Application { // 启动装配:config store、settings worker、runtime、audio、renderer、 // overlay、plugin service、update service、应用日志等 pub fn start(/* 入口参数 */) -> Result; // 运行与关闭:run() 进入 GPUI 循环;shutdown 顺序由 main.rs 持有 } ``` -------------------------------- ### Run model source picker smoke example with --expect-selected-any --kind archive Source: https://github.com/ayangweb/bongocat/blob/master/docs/adr/0036-model-archive-import-boundary.md Command to run the model_source_picker_smoke example on macOS, expecting any selection and specifying archive kind. This verifies the real NSOpenPanel path for selecting a zip. ```bash cargo run -p bongocat-platform --example model_source_picker_smoke -- --expect-selected-any --kind archive ``` -------------------------------- ### Usage example: start runtime, send commands, wait, and shutdown Source: https://github.com/ayangweb/bongocat Shows a minimal assembly without rendering/audio (RuntimeOwner::start(false, 64)). Sends commands like SetOverlayVisible, SetOverlaySettings, ResetInput, SetMaximumFps, and SetExpression; waits for command processing via wait_for_command and checks RuntimeState::Ready. toggle_repeated_expression causes repeated triggers to turn off the current expression. Shuts down with a 2-second timeout. ```rust use bongocat_runtime::{RuntimeCommand, RuntimeOwner, OverlaySettings, RuntimeState}; use bongocat_input::InputResetReason; let owner = RuntimeOwner::start(false, 64); // 无渲染/音频的最小装配 let client = owner.client(); client.send(RuntimeCommand::SetOverlayVisible(true))?; client.send(RuntimeCommand::SetOverlaySettings(OverlaySettings::default()))?; client.send(RuntimeCommand::ResetInput(InputResetReason::SystemForegroundChanged))?; // 等待命令生效(等待某个 sequence 已处理) let sequence = client.send(RuntimeCommand::SetMaximumFps(120))?; let snapshot = client.wait_for_command(sequence); if !matches!(snapshot.state, RuntimeState::Ready) { eprintln!("runtime 未就绪: {:?}", snapshot.state); } // 表达式切换:toggle_repeated_expression 开启时重复触发会关掉当前表情 client.send(RuntimeCommand::SetExpression(ExpressionId::new("live2d_expression0.exp3.json")?))?; // 关闭(超时 2 秒) owner.shutdown(std::time::Duration::from_secs(2))?; ``` -------------------------------- ### Settings client usage example Source: https://github.com/ayangweb/bongocat Shows how to create a bounded client, read a snapshot, and write settings with config revision checking. Handles SnapshotOutdated errors by re-reading. ```rust use bongocat_ui_protocol::{SettingsClient, SettingsTheme, SettingsError, SettingsErrorCode}; let (client, _endpoint) = SettingsClient::bounded(64); // 服务端持有 endpoint,窗口持有 client // 初始化:读取快照 let snapshot = client.read_snapshot().await?; // 配置写入必须携带期望的 config revision;过期则失败 let result = client.set_appearance_theme(snapshot.config_revision.unwrap(), SettingsTheme::Dark).await; match result { Ok(snapshot) => /* 新的 config_revision 已在快照中 */, Err(SettingsError::new(SettingsErrorCode::SnapshotOutdated)) => { // 设置已在别处改动:重读并让用户复核 let fresh = client.read_snapshot().await?; } Err(error) => { let code = error.code(); // 窗口把 code 映射为本地化文案 } } ``` -------------------------------- ### start Source: https://github.com/ayangweb/bongocat 进程启用时发送,用于载入配置与持久状态。插件必须载入配置与状态,若返回 Err 则拒绝启动。 ```APIDOC ## start ### Description 进程启用时发送,用于载入配置与持久状态。插件必须载入配置与状态,若返回 Err 则拒绝启动。 ### Message Type `start` ### Payload - `config` (Configuration) - Required - 插件配置 - `state` (Vec) - Required - 持久化状态 ### Response #### Success Response 返回 `PluginOutput`,包含模型、设置、配置、状态和错误列表。 #### Error Response 返回 `Err` 拒绝启动。 ``` -------------------------------- ### install_verified(bytes, expected_sha256) Source: https://github.com/ayangweb/bongocat Installs a plugin with full transaction verification: digest check, manifest validation, version compatibility, and immutability. Returns the installed package or an error. ```APIDOC ## install_verified(bytes, expected_sha256) ### Description Installs a plugin with full transaction verification: digest check, manifest validation, version compatibility, and immutability. ### Method Method ### Parameters - **bytes** (&[u8]) - Required - The plugin package bytes. - **expected_sha256** (&str) - Required - The expected SHA-256 digest of the package. ### Returns - `Result` - The installed package or an error. ### Transaction Steps 1. If `sha256_of(bytes) != expected_sha256`, returns `UnsafeManifest("package digest does not match the catalog")`. 2. Unpack and check manifest; if `app_versions` mismatch, returns `UnsafeManifest("plugin excludes this application version")`. 3. If same version already installed, returns `UnsafeManifest("installed versions are immutable; publish a newer version")`. 4. If running, suspend first; on failure rollback. Atomic switch of `current` pointer; on registration/Start/language negotiation failure, fallback to old version or full uninstall. ``` -------------------------------- ### Usage example: worker thread and polling loop with UpdateClient Source: https://github.com/ayangweb/bongocat Shows how to create a bounded channel, spawn a worker thread that blocks on recv_blocking, and poll the client snapshot to react to download progress, install completion, or failure. The example uses the ? operator, so it expects a Result context; it sleeps 200 ms between polls. ```rust use bongocat_ui_protocol::{UpdateClient, UpdatePhase, UpdateCommand}; // 更新窗口启动:bounded 创建两端的同一对话 let (client, endpoint) = UpdateClient::bounded(8); // worker 线程持有 endpoint: std::thread::spawn(move || loop { match endpoint.recv_blocking() { Ok(UpdateCommand::Check) => { /* 让 UpdateRuntime::check 跑起来 */ } Ok(UpdateCommand::Install) => { /* UpdateRuntime::install_with_observer(...) */ } Ok(UpdateCommand::Restart) => { /* UpdateRuntime::restart */ } Ok(UpdateCommand::Shutdown) | Err(_) => break, } }); // 窗口侧:发布状态后轮询渲染 client.request_check()?; loop { let snapshot = client.snapshot(); match snapshot.phase { UpdatePhase::Downloading { progress, .. } => { println!("下载 {}%", progress.percent().unwrap_or(0)); } UpdatePhase::Installed { restart_required, .. } => { if restart_required { client.request_restart()?; } break; } UpdatePhase::Failed { stage, code, .. } => { eprintln!("失败于 {}: {}", stage.as_str(), code.as_str()); break; } _ => {} } std::thread::sleep(std::time::Duration::from_millis(200)); } ``` -------------------------------- ### PluginManager install, uninstall, reset, and data methods Source: https://github.com/ayangweb/bongocat Methods for installing, uninstalling, resetting plugins, and accessing data roots and installed versions. Note that uninstall removes the package but keeps data, while reset removes data but keeps the package. ```rust pub fn install(&mut self, bytes: &[u8], expected_sha256: &str) -> Result pub fn install_verified(&mut self, bytes: &[u8], expected_sha256: &str) -> Result pub fn uninstall(&mut self, id: &str) -> Result // 删包,保留数据 pub fn reset(&mut self, id: &str) -> Result // 删数据,保留包 pub fn data_root(&self, id: &str, create: bool) -> Result pub fn installed_version(&self, id: &str) -> Option ``` -------------------------------- ### run Source: https://github.com/ayangweb/bongocat Entry point for a plugin process. Call this in `fn main` after implementing the `Plugin` trait to start the plugin loop communicating with the host over stdin/stdout. ```APIDOC ## run ### Description Entry point for a plugin process. Call this in `fn main` after implementing the `Plugin` trait to start the plugin loop communicating with the host over stdin/stdout. ### Method run ### Parameters None ### Response No return value. ``` -------------------------------- ### ModelStore usage example with import, delete, and replace_cover Source: https://github.com/ayangweb/bongocat Example of using ModelStore to inspect a source, import a package or mver with observer, delete a model, and replace its cover. Requires a ModelId and cancellation flag. ```rust use bongocat_model::{ModelId, ModelPackageLimits}; use bongocat_model_store::ModelStore; let store = ModelStore::new("/tmp/models", "/tmp/models.lock", ModelPackageLimits::default())?; // 检查用户选择的源 let content = store.inspect_source("/path/to/source")?; match content { bongocat_model_store::ModelSourceContent::Package => { store.import("/path/to/source", "我的猫".to_owned())?; } bongocat_model_store::ModelSourceContent::Mver { modes } if modes.contains(&bongocat_model_store::MverInputMode::Keyboard) => { store.import_mver_with_observer( "/path/to/source", "我的猫".to_owned(), /* 模式选择 */, |progress| println!("{}: {} files", progress.stage, progress.files_copied), || cancelled.load(std::sync::atomic::Ordering::Relaxed), )?; } bongocat_model_store::ModelSourceContent::Mver { .. } | bongocat_model_store::ModelSourceContent::Folder { .. } => { // 界面需要进一步选择 } } // 删除与封面 let id = ModelId::parse("some-uuid")?; let _ = store.delete(&id); let cover_path = store.replace_cover(&id, png_bytes)?; ``` -------------------------------- ### UpdateRuntime::install_with_observer Source: https://github.com/ayangweb/bongocat Installs the update with an observer callback for progress events. ```APIDOC ## UpdateRuntime::install_with_observer ### Description Installs the update with an observer callback for progress events. The observer runs on the calling thread and receives events: `UpdateEvent::Progress(UpdateProgress)`, `UpdateEvent::DownloadFinished`, `UpdateEvent::Verified`. No cancellation hook is provided. ### Method install_with_observer ### Parameters - `observe` (impl Fn(UpdateEvent)) - Required - The observer callback. ### Returns - `Result` - The update outcome or an error. ``` -------------------------------- ### UpdateRuntime struct and methods Source: https://github.com/ayangweb/bongocat Runtime for update checks and installation. install on Windows NSIS terminates process; Installed only observable on macOS. install_with_observer runs observer on calling thread with events Progress, DownloadFinished, Verified; no cancellation. Manifest fetched from proxy prefixes then official GitHub, with respective timeouts. ```rust pub struct UpdateRuntime { /* configuration + current_version + diagnostics */ } impl UpdateRuntime { pub fn new(configuration: ReleaseConfiguration, current_version: &'static str, diagnostics: UpdateDiagnosticsTracker) -> Self pub fn for_current_build(environment: BuildEnvironment, current_version: &'static str, diagnostics: UpdateDiagnosticsTracker) -> Self pub fn channel(&self) -> ReleaseChannel pub fn is_available(&self) -> bool pub fn unavailability(&self) -> Option // DevelopmentChannel | SigningKeyMissing pub fn diagnostics(&self) -> &UpdateDiagnosticsTracker pub fn check(&self) -> Result pub fn release_page_url(&self, version: &str) -> Option pub fn install(&self) -> Result pub fn install_with_observer(&self, observe: impl Fn(UpdateEvent)) -> Result pub fn restart(&self) -> Result // 成功不返回 } ``` -------------------------------- ### Usage example with SettingsClient and SettingsOverlay Source: https://github.com/ayangweb/bongocat Shows how to read snapshots, poll for revisions, and update overlay settings with a revision guard. Uses SettingsClient::bounded(32) and SettingsOverlay with always_on_top set to false. ```rust use bongocat_ui_protocol::{SettingsClient, SettingsOverlay}; let client = SettingsClient::bounded(32).0; let snapshot = client.read_snapshot().await?; // 轮询:只取 revision,变化后再取全量快照 let mut last = client.read_snapshot_revision().await?; loop { let revision = client.read_snapshot_revision().await?; if revision != last { last = revision; let full = client.read_snapshot().await?; // 渲染 full } tokio::time::sleep(std::time::Duration::from_millis(200)).await; } // 修改 overlay 设置(带 revision 守卫) let overlay = SettingsOverlay { always_on_top: false, ..Default::default() }; client.set_overlay_settings(snapshot.config_revision.unwrap(), overlay).await?; ``` -------------------------------- ### UpdateRuntime::install Source: https://github.com/ayangweb/bongocat Installs the update and returns the outcome. ```APIDOC ## UpdateRuntime::install ### Description Installs the update and returns the outcome. On Windows, the NSIS installation path terminates the process; `Installed` is only observable on macOS. ### Method install ### Returns - `Result` - The update outcome or an error. ``` -------------------------------- ### installed_version(id) Source: https://github.com/ayangweb/bongocat Returns the installed version of a plugin by ID, or None if not installed. This is a simple getter. ```APIDOC ## installed_version(id) ### Description Returns the installed version of a plugin by ID, or None if not installed. ### Method Method ### Parameters - **id** (&str) - Required - The plugin ID. ### Returns - `Option` - The installed version string, or `None` if not installed. ``` -------------------------------- ### PluginService::start Source: https://github.com/ayangweb/bongocat Starts the plugin service with default source (InstalledOnly) and no input activity. Returns the service and overlay handles. ```APIDOC ## PluginService::start ### Description Starts the plugin service with default source (InstalledOnly) and no input activity. Returns the service and overlay handles. ### Method start ### Signature ```rust pub fn start(storage_root: &Path, capacity: usize) -> Result<(Self, PluginOverlayHandles), PluginServiceStartError> ``` ### Parameters - **storage_root** (&Path) - Required - Root path for plugin storage. - **capacity** (usize) - Required - Command channel capacity (must be > 0). ### Returns - `Result<(Self, PluginOverlayHandles), PluginServiceStartError>` - Service instance and overlay handles, or an error. ``` -------------------------------- ### PluginServiceClient::install_available_blocking Source: https://github.com/ayangweb/bongocat Sends an InstallAvailable command to install an available plugin and returns the updated plugin center snapshot. ```APIDOC ## PluginServiceClient::install_available_blocking ### Description Sends an InstallAvailable command to install an available plugin and returns the updated plugin center snapshot. ### Method install_available_blocking ### Signature ```rust pub fn install_available_blocking(&self, id: PluginId) -> Result ``` ### Parameters - **id** (PluginId) - Required - Plugin identifier. ### Returns - `Result` - The updated plugin center snapshot or an error. ``` -------------------------------- ### ModelStore::list Source: https://github.com/ayangweb/bongocat Lists all installed models in the store. ```APIDOC ## ModelStore::list ### Description Lists all installed models in the store. ### Method Query ### Signature ```rust pub fn list(&self) -> Result ``` ### Returns - **Result** - The catalog of installed models or an error. ``` -------------------------------- ### PluginService::start_with_source Source: https://github.com/ayangweb/bongocat Starts the plugin service with a specified plugin source and optional input activity callback. Returns the service and overlay handles. ```APIDOC ## PluginService::start_with_source ### Description Starts the plugin service with a specified plugin source and optional input activity callback. Returns the service and overlay handles. ### Method start_with_source ### Signature ```rust pub fn start_with_source( storage_root: &Path, capacity: usize, source: PluginSource, input_activity: Option InputActivity + Send>>, ) -> Result<(Self, PluginOverlayHandles), PluginServiceStartError> ``` ### Parameters - **storage_root** (&Path) - Required - Root path for plugin storage. - **capacity** (usize) - Required - Command channel capacity (must be > 0). - **source** (PluginSource) - Required - Plugin source to use. - **input_activity** (Option InputActivity + Send>>) - Optional - Callback to provide input activity. ### Returns - `Result<(Self, PluginOverlayHandles), PluginServiceStartError>` - Service instance and overlay handles, or an error. ``` -------------------------------- ### PluginManager::install_verified Source: https://github.com/ayangweb/bongocat Installs a plugin from verified bytes. The digest is provided by the signed catalog. ```APIDOC ## PluginManager::install_verified ### Description Installs a plugin from verified bytes. The digest is provided by the signed catalog. ### Method Method ### Parameters - **package_bytes** (&[u8]) - Required - The plugin package bytes - **sha256_hex** (&str) - Required - The SHA-256 digest in hexadecimal ### Returns - `Result` - The installed plugin information ### Example ```rust let package_bytes: &[u8] = &[]; let installed = manager.install_verified(package_bytes, "")?; println!("installed {} at {}", installed.manifest.metadata.id, installed.root.display()); ``` ``` -------------------------------- ### UpdateClient::request_install Source: https://github.com/ayangweb/bongocat Sends an Install command to the update service. Returns an error if the channel is closed. ```APIDOC ## UpdateClient::request_install ### Description Sends an Install command to the update service. Returns an error if the channel is closed. ### Method request_install ### Returns - **Result<(), UpdateServiceClosed>** - Ok if sent, Err if channel closed. ``` -------------------------------- ### SettingsClient::start_model_import Source: https://github.com/ayangweb/bongocat Starts a model import operation with the given request. Returns an operation handle that can be monitored and cancelled. ```APIDOC ## SettingsClient::start_model_import ### Description Starts a model import operation with the given request. Returns an operation handle that can be monitored and cancelled. ### Method Async method ### Parameters - **request** (SettingsModelImportRequest) - Required - The import request containing title, source root, and selected mver modes. ### Returns - **operation** (SettingsModelImportOperation) - The operation handle. ### Example ```rust let operation = client.start_model_import(SettingsModelImportRequest { title: "我的猫".into(), source_root, selected_mver_modes: vec![], }).await?; ``` ``` -------------------------------- ### ModelStore::load Source: https://github.com/ayangweb/bongocat Loads an installed model by its ID. ```APIDOC ## ModelStore::load ### Description Loads an installed model by its ID. ### Method Query ### Signature ```rust pub fn load(&self, id: &ModelId) -> Result ``` ### Parameters - **id** (&ModelId) - Required - The ID of the model to load. ### Returns - **Result** - The loaded model or an error. ``` -------------------------------- ### SettingsClient::start_model_import Source: https://github.com/ayangweb/bongocat Starts a model import operation with the given request parameters. Returns an operation handle that can be used to wait for the final result. ```APIDOC ## SettingsClient::start_model_import ### Description Starts a model import operation with the given request parameters. Returns an operation handle that can be used to wait for the final result. ### Method Rust method (async) ### Endpoint `client.start_model_import(request: SettingsModelImportRequest) -> Result` ### Parameters #### Request Body - **title** (String) - Required - Title of the model. - **source_root** (String) - Required - Path to the model source directory. - **selected_mver_modes** (Vec) - Required - Selected Mver modes for conversion. ### Response #### Success Response Returns an operation handle with a `final_result_blocking()` method to wait for the import result. ### Request Example ```rust let operation = client.start_model_import(SettingsModelImportRequest { title: "模型".into(), source_root: "/path/to/model".into(), selected_mver_modes: if modes.contains(&SettingsMverMode::Keyboard) { vec![SettingsMverMode::Keyboard] } else { vec![] }, }).await?; let _ = operation.final_result_blocking(); ``` ``` -------------------------------- ### InstalledModel::list Source: https://github.com/ayangweb/bongocat Lists all installed model catalog entries. ```APIDOC ## InstalledModel::list ### Description Lists all installed model catalog entries. ### Method list ### Signature pub fn list(&self) -> Result, ModelError>; ### Returns - **Result, ModelError>** - The list of catalog entries or an error. ``` -------------------------------- ### RuntimeCommand::StartMotion Source: https://github.com/ayangweb/bongocat Starts a motion with a given priority. Plays once; loop declarations do not cause continuous playback. Duplicate requests of the same motion at the same priority are no-ops while running. Can be replaced or restarted after completion. ```APIDOC ### Description Starts a motion with a given priority. Plays once; loop declarations do not cause continuous playback. Duplicate requests of the same motion at the same priority are no-ops while running. Can be replaced or restarted after completion. ### Method StartMotion ### Parameters - `motion` (MotionId) - Required - The motion to start. - `priority` (MotionPriority) - Required - The priority of the motion. ``` -------------------------------- ### Generate and host zipsign keys Source: https://github.com/ayangweb/bongocat/blob/master/docs/update-signing-guide.md Installs zipsign, generates a key pair, and copies the private key to the clipboard for storage as a GitHub Secret. The public key is 32 bytes of raw data to be embedded at compile time. ```sh cargo install zipsign zipsign gen-key release.key release.pub && chmod 600 release.key base64 -i release.key | pbcopy # 存进 GitHub Secret ``` -------------------------------- ### RuntimeOwner constructor methods Source: https://github.com/ayangweb/bongocat Constructors for RuntimeOwner that start the runtime worker with optional injected audio, rendering, and clock dependencies. The basic start uses default implementations; the with_* variants allow parameterized injection. ```rust pub fn start(initial_overlay_visible: bool, command_capacity: usize) -> Self pub fn start_with_audio(initial_overlay_visible: bool, command_capacity: usize, audio: MotionAudioClient) -> Self pub fn start_with_rendering(initial_overlay_visible: bool, command_capacity: usize, renderer: impl RenderConsumer) -> Self pub fn start_with_rendering_and_audio(...) -> Self pub fn start_with_rendering_and_clock(initial_overlay_visible: bool, command_capacity: usize, renderer: impl RenderConsumer, clock: impl MonotonicClock) -> Self pub fn start_with_rendering_audio_and_clock(...) -> Self ``` -------------------------------- ### PluginService::start_with_events Source: https://github.com/ayangweb/bongocat Starts the plugin service with a specified plugin source and a plugin input events handler. Returns the service and overlay handles. ```APIDOC ## PluginService::start_with_events ### Description Starts the plugin service with a specified plugin source and a plugin input events handler. Returns the service and overlay handles. ### Method start_with_events ### Signature ```rust pub fn start_with_events( storage_root: &Path, capacity: usize, source: PluginSource, events: Box, ) -> Result<(Self, PluginOverlayHandles), PluginServiceStartError> ``` ### Parameters - **storage_root** (&Path) - Required - Root path for plugin storage. - **capacity** (usize) - Required - Command channel capacity (must be > 0). - **source** (PluginSource) - Required - Plugin source to use. - **events** (Box) - Required - Plugin input events handler. ### Returns - `Result<(Self, PluginOverlayHandles), PluginServiceStartError>` - Service instance and overlay handles, or an error. ``` -------------------------------- ### MotionAudioService::start Source: https://github.com/ayangweb/bongocat Starts the audio service, opening the default output device. Returns a service instance or an error if the device cannot be opened or the worker thread fails to spawn. ```APIDOC ## MotionAudioService::start ### Description Starts the audio service, opening the default output device. ### Method start ### Parameters None ### Returns - `Result` - The service instance or an error. ### Errors - `MotionAudioStartError::DeviceOpenFailed` - Failed to open the default output device. - `MotionAudioStartError::ThreadSpawnFailed` - Failed to spawn the worker thread. ### Example ```rust let service = MotionAudioService::start()?; ``` ``` -------------------------------- ### start_model_import Source: https://github.com/ayangweb/bongocat Starts a model import operation. This method corresponds to the ImportModel command and returns the import operation. ```APIDOC ## start_model_import ### Description Starts a model import operation. ### Method start_model_import(&self, request: SettingsModelImportRequest) ### Parameters - `request` (SettingsModelImportRequest) - Required - The import request. ### Returns `SettingsModelImportOperation` ``` -------------------------------- ### InstalledModel::root Source: https://github.com/ayangweb/bongocat Returns the root path of the installed model catalog. ```APIDOC ## InstalledModel::root ### Description Returns the root path of the installed model catalog. ### Method root ### Signature pub fn root(&self) -> &Path; ### Returns - **&Path** - The root path. ``` -------------------------------- ### PluginManager::discover_plugins Source: https://github.com/ayangweb/bongocat Discovers installed plugins. In production, this never reads local build directories. ```APIDOC ## PluginManager::discover_plugins ### Description Discovers installed plugins. In production, this never reads local build directories. ### Method Method ### Returns - `Result` - The number of discovered plugins ### Example ```rust let found = manager.discover_plugins()?; println!("discovered {found} plugins"); ``` ``` -------------------------------- ### RuntimeOwner::start_with_audio Source: https://github.com/ayangweb/bongocat Starts the runtime worker with a custom audio client. This allows injecting a MotionAudioClient for audio handling. ```APIDOC ## RuntimeOwner::start_with_audio ### Description Starts the runtime worker with a custom audio client. This allows injecting a MotionAudioClient for audio handling. ### Method start_with_audio ### Signature ```rust pub fn start_with_audio(initial_overlay_visible: bool, command_capacity: usize, audio: MotionAudioClient) -> Self ``` ### Parameters - `initial_overlay_visible` (bool) - Required - Initial visibility of the overlay. - `command_capacity` (usize) - Required - Capacity of the runtime command queue. - `audio` (MotionAudioClient) - Required - Audio client to use for motion audio. ### Returns - `Self` - A new RuntimeOwner instance. ``` -------------------------------- ### RuntimeOwner::start_with_rendering_audio_and_clock Source: https://github.com/ayangweb/bongocat Starts the runtime worker with custom rendering, audio, and clock. This allows injecting all three dependencies. ```APIDOC ## RuntimeOwner::start_with_rendering_audio_and_clock ### Description Starts the runtime worker with custom rendering, audio, and clock. This allows injecting all three dependencies. ### Method start_with_rendering_audio_and_clock ### Signature ```rust pub fn start_with_rendering_audio_and_clock(...) -> Self ``` ### Parameters - `initial_overlay_visible` (bool) - Required - Initial visibility of the overlay. - `command_capacity` (usize) - Required - Capacity of the runtime command queue. - `renderer` (impl RenderConsumer) - Required - Render consumer to use for rendering. - `audio` (MotionAudioClient) - Required - Audio client to use for motion audio. - `clock` (impl MonotonicClock) - Required - Monotonic clock to use for timing. ### Returns - `Self` - A new RuntimeOwner instance. ``` -------------------------------- ### RuntimeOwner::start_with_rendering_and_audio Source: https://github.com/ayangweb/bongocat Starts the runtime worker with custom rendering and audio. This allows injecting both a render consumer and an audio client. ```APIDOC ## RuntimeOwner::start_with_rendering_and_audio ### Description Starts the runtime worker with custom rendering and audio. This allows injecting both a render consumer and an audio client. ### Method start_with_rendering_and_audio ### Signature ```rust pub fn start_with_rendering_and_audio(...) -> Self ``` ### Parameters - `initial_overlay_visible` (bool) - Required - Initial visibility of the overlay. - `command_capacity` (usize) - Required - Capacity of the runtime command queue. - `renderer` (impl RenderConsumer) - Required - Render consumer to use for rendering. - `audio` (MotionAudioClient) - Required - Audio client to use for motion audio. ### Returns - `Self` - A new RuntimeOwner instance. ``` -------------------------------- ### 构建与打包命令:just build 等 Source: https://github.com/ayangweb/bongocat/blob/master/AGENTS.md just 是唯一构建入口,build recipe 转发参数给 crates/bongocat-packaging。支持指定 target、environment 和 formats。manifest 合并、发布说明合成、密钥生成、版本号和 schema 生成均有对应命令。 ```text just build # Production,本机 target,全部产物 just build --target x86_64-apple-darwin # 指定 target just build --environment development --formats app # 只要 Development .app just manifest target/package target/package/*.json # 合并 per-target manifest fragment just release-notes release-notes.md # 从两份 changelog 合成发布说明 just keygen ~/.bongocat/release.key # 一次性生成更新签名密钥对 just version # 唯一产品版本号来源 just schema # 从 Rust 类型生成当前 JSON Schema ``` -------------------------------- ### Error handling with PluginCommandError and retry Source: https://github.com/ayangweb/bongocat Demonstrates matching on PluginCommandError variants, such as NotFound, and using code() to get a stable string. The example attempts to enable a missing plugin and prints a message for NotFound. ```rust use bongocat_plugin_service::{PluginCommandError, PluginService}; use bongocat_plugin_sdk::ConfigValue; let (service, _) = PluginService::start(root, 8)?; let client = service.client(); match client.set_enabled_blocking("com.example.missing", true) { Err(PluginCommandError::NotFound) => println!("catalog 中没有这个插件"), Err(code) => println!("stable code: {}", code.code()), Ok(snapshot) => { /* 成功:快照已是最新 */ } } ``` -------------------------------- ### Usage example: manual validation and language resolution Source: https://github.com/ayangweb/bongocat Shows how to manually validate a config document using serde_json and NativeConfig. Includes a JSON document with all config sections, deserialization, validation, and language resolution with fallback handling. ```rust use bongocat_config::{NativeConfig, OverlayConfig, Language, Theme}; use serde_json::json; // 读取:唯一严格解析入口由 ConfigStore 提供(见 config-store 页) // 手工校验一个文档的示例: let document = json!({ "schema_version": 1, "appearance": { "theme": "system", "language": "zh-CN" }, "overlay": { "click_through": false, "always_on_top": true, "scale_percent": 100, "opacity_percent": 100, "maximum_fps": 60, "corner_radius_percent": 0, "hide_on_pointer_hover": false, "hide_on_pointer_hover_delay_seconds": 0, "hide_on_idle": true, "hide_on_idle_delay_seconds": 10, "keep_inside_screen": true }, "input": { "gamepad": { "stick_dead_zone": 0.15, "trigger_dead_zone": 0.0 }, "mouse": { "force_move": false } }, "logging": { "level": "info", "retention_days": 7 }, "model": { "selected_model": null, "imported_models": [], "built_in_models": [], "mirror": false, "mirror_pointer_tracking_horizontal": false, "mirror_pointer_tracking_vertical": false, "play_motion_audio": false, "ignore_keyboard": false, "ignore_gamepad": false, "ignore_pointer": false, "random_behavior": { "mode": "off", "interval_seconds": 30 }, "gamepad_auto_switch": { "enabled": false, "connected_model": null, "disconnected_model": null }, "remember_last_expression": false, "last_expressions": [], "behavior_names": [] }, "shortcuts": { "commands_enabled": true, "model_behaviors_enabled": false, "command_bindings": [], "model_behavior_bindings": [] }, "system": { "show_taskbar_icon": false, "show_dock_icon": false, "show_status_icon": true }, "updates": { "check_automatically": false, "check_interval_hours": 24 }, }); let config: NativeConfig = serde_json::from_value(document)?; if config.appearance.language != Language::ChineseSimplified { eprintln!("unexpected language fallback"); } config.validate()?; let resolved = Language::System.resolve(Language::from_system_locale("zh-Hans-CN")); match resolved { Language::ChineseSimplified => { /* 简体中文目录 */ } other => eprintln!("resolved to {:?}", other), } ``` -------------------------------- ### SettingsClient window state helper methods Source: https://github.com/ayangweb/bongocat Direct &self methods for tracking settings window geometry and reporting overlay window geometry. ```rust pub fn track_window_state(&self, placement: Option) -> SettingsWindowState pub fn update_overlay_window_placement(&self, x: i32, y: i32, width: u32, height: u32) -> Result<(), SettingsServiceClosed> ``` -------------------------------- ### Run smoke test for startup permission Source: https://github.com/ayangweb/bongocat/blob/master/docs/adr/0032-startup-permission-prompt-boundary.md Command to verify startup permission smoke test. Before authorization outputs 'missing', after authorization outputs 'available'. Does not show dialog or write product state. ```bash cargo run -p bongocat-app -- --startup-permission-smoke ``` -------------------------------- ### Release action sequence Source: https://github.com/ayangweb/bongocat/blob/master/docs/changelog-conventions.md Steps to release: update the version in `[workspace.package].version`, change `## Unreleased` to `## 2.0.0 - ` in both changelogs, commit with the exact title, then tag and push. Verify locally with `just release-notes` before pushing. ```sh # 1. 版本号只有一个来源,改它:[workspace.package].version # 2. 两份 changelog 的 `## Unreleased` 改成 `## 2.0.0 - ` # 3. 提交,标题逐字为 `chore: release v2.0.0` git commit -m "chore: release v2.0.0" # 4. 打 tag 并推送,流水线按 tag 触发 git tag -a v2.0.0 -m "Release 2.0.0" git push origin master && git push origin v2.0.0 ``` ```sh just release-notes release-notes.md ``` -------------------------------- ### Rust: Use ConfigStore, WindowStateStore, and Shortcut Parsing Source: https://github.com/ayangweb/bongocat Shows opening a storage layout, loading or creating a default config, committing with revision-based optimistic concurrency, handling revision conflicts, and using window state and shortcut parsing. Requires the bongocat_config crate and a writable storage path. ```rust use bongocat_config::{ BuildEnvironment, ConfigStore, NativeConfig, StorageLayout, WindowStateStore, }; // 打开存储 let layout = StorageLayout::under("/tmp/bongocat-data", BuildEnvironment::Development); let store = ConfigStore::new(layout.clone())?; // 首次加载(缺失 -> 默认),之后带 revision 提交 let outcome = store.load_or_default()?; let mut config = outcome.config; config.overlay.scale_percent = 125; let new_revision = store.commit(&config)?; // 乐观并发写:revision 冲突被拒绝 match store.commit_if_revision(&config, outcome.revision) { Ok(r) => println!("committed revision {}", r.value()), Err(bongocat_config::ConfigError::RevisionConflict { actual, .. }) => { // 重读并合并 let fresh = store.load_or_default()?; } Err(e) => eprintln!("{:?}", e.write_failure_reason()), } // window state 与快捷键解析 let window_store = WindowStateStore::new(layout); let result = window_store.load_or_default(); let _state = result.state; let chord = bongocat_config::ShortcutChord::parse("Ctrl+Alt+A")?; let command = bongocat_config::ShortcutCommand::parse("toggle_overlay")?; ```