v0.1.0-pre.046

This commit is contained in:
2026-07-25 19:45:35 +02:00
parent 01764a485a
commit 417536e4c4
17 changed files with 1491 additions and 57 deletions

View File

@@ -0,0 +1,119 @@
// file: kb-app-demo-desktop/src/app_state.rs
// version: 1
//! Shared Tauri application state and startup initialization.
/// Shared state managed by Tauri for the desktop demo application.
pub(crate) struct AppState {
config_path: std::string::String,
app_config: kb_config::AppConfig,
active_profile: kb_config::ProfileConfig,
logging_guard: std::sync::Mutex<kb_logging::LoggingGuard>,
}
impl crate::AppState {
/// Initializes configuration, logging and shared runtime state.
pub(crate) fn initialize() -> kb_core::Result<crate::AppState> {
let config_path = resolve_config_path();
let app_config = match kb_config::read_config_json_file(&config_path) {
std::result::Result::Ok(config) => config,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let active_profile = match kb_config::active_profile(&app_config) {
std::result::Result::Ok(profile) => profile.clone(),
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let logging_config = convert_logging_config(&active_profile.logging);
let logging_guard = match kb_logging::init_logging(&logging_config) {
std::result::Result::Ok(guard) => guard,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
return std::result::Result::Ok(crate::AppState {
config_path: config_path.display().to_string(),
app_config,
active_profile,
logging_guard: std::sync::Mutex::new(logging_guard),
});
}
/// Returns the path used to load the configuration file.
pub(crate) fn config_path(&self) -> &str {
return self.config_path.as_str();
}
/// Returns the complete parsed application configuration.
pub(crate) fn app_config(&self) -> &kb_config::AppConfig {
return &self.app_config;
}
/// Returns the active profile selected from the configuration.
pub(crate) fn active_profile(&self) -> &kb_config::ProfileConfig {
return &self.active_profile;
}
/// Returns the number of logging routes held by the logging guard.
pub(crate) fn logging_route_count(&self) -> usize {
let lock_result = self.logging_guard.lock();
let guard = match lock_result {
std::result::Result::Ok(guard) => guard,
std::result::Result::Err(_) => return 0,
};
return guard.route_count();
}
}
fn convert_logging_config(config: &kb_config::LoggingConfig) -> kb_logging::LoggingConfig {
let mut targets = std::vec::Vec::<kb_logging::LogTargetConfig>::new();
for target in &config.targets {
targets.push(kb_logging::LogTargetConfig {
name: target.name.clone(),
enabled: target.enabled,
sink: target.sink.clone(),
level: target.level.clone(),
path: target.path.clone(),
rotation: target.rotation.clone(),
format: target.format.clone(),
ansi: target.ansi,
targets: target.targets.clone(),
});
}
let mut target_filters = std::vec::Vec::<kb_logging::LogTargetFilterConfig>::new();
for filter in &config.target_filters {
target_filters.push(kb_logging::LogTargetFilterConfig {
target: filter.target.clone(),
level: filter.level.clone(),
});
}
return kb_logging::LoggingConfig {
default_level: config.default_level.clone(),
targets,
target_filters,
};
}
fn resolve_config_path() -> std::path::PathBuf {
let configured = std::env::var("KB_CONFIG_PATH").ok();
return resolve_config_path_from_value(configured.as_deref());
}
fn resolve_config_path_from_value(value: std::option::Option<&str>) -> std::path::PathBuf {
if let std::option::Option::Some(configured) = value {
let trimmed = configured.trim();
if !trimmed.is_empty() {
return std::path::PathBuf::from(trimmed);
}
}
return crate::workspace_root_dir().join("config/example.config.json");
}
#[cfg(test)]
mod tests {
#[test]
fn resolve_config_path_uses_workspace_example_by_default() {
let path = super::resolve_config_path_from_value(std::option::Option::None);
assert_eq!(
path.file_name().and_then(std::ffi::OsStr::to_str),
std::option::Option::Some("example.config.json")
);
}
}

View File

@@ -0,0 +1,72 @@
// file: kb-app-demo-desktop/src/frontend_log.rs
// version: 1
//! Frontend logging bridge used by Tauri WebView scripts.
use ts_rs::TS; // rust-rules: derive-import
/// Log payload sent by frontend scripts.
#[derive(Clone, Debug, serde::Deserialize, TS)]
#[ts(
export,
export_to = "../frontend/ts/bindings/kb_app_demo_desktop/frontend_log/FrontendLogPayload.ts"
)]
pub(crate) struct FrontendLogPayload {
/// Lowercase tracing level.
pub(crate) level: std::string::String,
/// Explicit frontend tracing target.
pub(crate) target: std::string::String,
/// Rendered frontend message.
pub(crate) message: std::string::String,
}
pub(crate) fn emit_frontend_log(payload: crate::FrontendLogPayload) {
let target = normalize_frontend_target(payload.target.as_str());
match payload.level.trim().to_ascii_lowercase().as_str() {
"trace" => {
tracing::trace!(target: crate::TRACING_TARGET, action = "frontend_log", frontend_target = target, "{}", payload.message)
},
"debug" => {
tracing::debug!(target: crate::TRACING_TARGET, action = "frontend_log", frontend_target = target, "{}", payload.message)
},
"warn" => {
tracing::warn!(target: crate::TRACING_TARGET, action = "frontend_log", frontend_target = target, "{}", payload.message)
},
"error" => {
tracing::error!(target: crate::TRACING_TARGET, action = "frontend_log", frontend_target = target, "{}", payload.message)
},
_ => {
tracing::info!(target: crate::TRACING_TARGET, action = "frontend_log", frontend_target = target, "{}", payload.message)
},
}
}
fn normalize_frontend_target(target: &str) -> std::string::String {
let trimmed = target.trim();
if trimmed == "kb-app-demo-desktop.frontend.main" {
return trimmed.to_string();
}
if trimmed == "kb-app-demo-desktop.frontend.splash" {
return trimmed.to_string();
}
return "kb-app-demo-desktop.frontend".to_string();
}
#[cfg(test)]
mod tests {
#[test]
fn normalize_frontend_target_uses_default_for_unknown_target() {
assert_eq!(
super::normalize_frontend_target("other.frontend"),
"kb-app-demo-desktop.frontend"
);
}
#[test]
fn normalize_frontend_target_keeps_main_target() {
assert_eq!(
super::normalize_frontend_target("kb-app-demo-desktop.frontend.main"),
"kb-app-demo-desktop.frontend.main"
);
}
}

View File

@@ -1,5 +1,5 @@
// file: kb-app-demo-desktop/src/lib.rs
// version: 2
// version: 3
//! Tauri desktop demo application for `khadhroony-bot3`.
@@ -7,13 +7,26 @@
#![deny(unreachable_pub)]
#![warn(missing_docs)]
mod app_state;
mod constants;
mod frontend_log;
mod main_window;
mod splash;
mod tauri;
/// Runs the desktop demo application.
pub use self::tauri::run;
/// Shared application state managed by Tauri.
pub(crate) use self::app_state::AppState;
/// Frontend logging payload.
pub(crate) use self::frontend_log::FrontendLogPayload;
/// Emits one normalized frontend log event.
pub(crate) use self::frontend_log::emit_frontend_log;
/// Loads the project README for the main window.
pub(crate) use self::main_window::load_project_readme;
/// Returns the workspace root directory.
pub(crate) use self::main_window::workspace_root_dir;
/// Delay after fade-out before destroying the splash window.
pub(crate) use self::splash::SPLASH_CLOSE_WAIT_MS;
/// Splash fade duration.
@@ -26,6 +39,7 @@ pub(crate) use self::splash::SplashOrder;
pub(crate) use self::splash::emit_splash_order;
/// Waits for the minimum splash duration.
pub(crate) use self::splash::wait_until_minimum;
// Keep the canonical tracing target as the final facade export.
/// Canonical tracing target for the desktop demo application.
pub(crate) use self::constants::TRACING_TARGET;

View File

@@ -0,0 +1,68 @@
// file: kb-app-demo-desktop/src/main_window.rs
// version: 1
//! Main-window helpers and workspace README loading.
pub(crate) fn workspace_root_dir() -> std::path::PathBuf {
let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
return match manifest_dir.parent() {
std::option::Option::Some(parent) => parent.to_path_buf(),
std::option::Option::None => manifest_dir,
};
}
pub(crate) fn load_project_readme() -> kb_core::Result<std::string::String> {
let path = crate::workspace_root_dir().join("README.md");
let content = match std::fs::read_to_string(&path) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::io(format!(
"cannot read project README '{}': {error}",
path.display()
)));
},
};
return std::result::Result::Ok(strip_readme_metadata_comments(content.as_str()));
}
fn strip_readme_metadata_comments(content: &str) -> std::string::String {
let mut output = std::string::String::new();
let mut leading_metadata = true;
for line in content.lines() {
let trimmed = line.trim();
if leading_metadata && is_readme_metadata_comment(trimmed) {
continue;
}
leading_metadata = false;
output.push_str(line);
output.push('\n');
}
return output;
}
fn is_readme_metadata_comment(line: &str) -> bool {
if line.starts_with("<!-- file:") || line.starts_with("<!--- file:") {
return true;
}
if line.starts_with("<!-- version:") || line.starts_with("<!--- version:") {
return true;
}
return false;
}
#[cfg(test)]
mod tests {
#[test]
fn strip_readme_metadata_comments_removes_workspace_header_lines() {
let content = "<!-- file: README.md -->\n<!-- version: 7 -->\n# Title\nBody\n";
let cleaned = super::strip_readme_metadata_comments(content);
assert_eq!(cleaned, "# Title\nBody\n");
}
#[test]
fn strip_readme_metadata_comments_keeps_later_html_comments() {
let content = "<!-- file: README.md -->\n# Title\n<!-- normal comment -->\nBody\n";
let cleaned = super::strip_readme_metadata_comments(content);
assert_eq!(cleaned, "# Title\n<!-- normal comment -->\nBody\n");
}
}

View File

@@ -1,5 +1,5 @@
// file: kb-app-demo-desktop/src/splash.rs
// version: 1
// version: 2
//! Splash-window payloads and startup sequencing helpers.
@@ -15,7 +15,10 @@ pub(crate) const SPLASH_CLOSE_WAIT_MS: u64 = 3100;
/// Command sent from Rust to the splash frontend.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, TS)]
#[ts(export, export_to = "../frontend/ts/bindings/kb_app_demo_desktop/splash/SplashOrder.ts")]
#[ts(
export,
export_to = "../frontend/ts/bindings/kb_app_demo_desktop/splash/SplashOrder.ts"
)]
pub(crate) struct SplashOrder {
/// Command name.
pub(crate) order: std::string::String,
@@ -77,8 +80,8 @@ mod tests {
#[test]
fn splash_timing_is_ordered() {
assert!(super::SPLASH_MINIMUM_MS > 0);
assert!(super::SPLASH_FADE_MS > 0);
assert!(super::SPLASH_CLOSE_WAIT_MS >= u64::from(super::SPLASH_FADE_MS));
assert!(crate::SPLASH_MINIMUM_MS > 0);
assert!(crate::SPLASH_FADE_MS > 0);
assert!(crate::SPLASH_CLOSE_WAIT_MS >= u64::from(crate::SPLASH_FADE_MS));
}
}

View File

@@ -1,13 +1,36 @@
// file: kb-app-demo-desktop/src/tauri.rs
// version: 1
// version: 3
//! Tauri runtime assembly and private command wrappers.
use tauri::Manager; // rust-rules: trait-import
/// Runs the desktop demo application.
#[cfg_attr(mobile, tauri::mobile_entry_point)]
#[allow(clippy::question_mark_used)]
pub fn run() -> kb_core::Result<()> {
let builder = tauri::Builder::default().setup(|app| {
let rustls_result = install_default_rustls_provider();
if let std::result::Result::Err(error) = rustls_result {
return std::result::Result::Err(error);
}
let app_state = match crate::AppState::initialize() {
std::result::Result::Ok(state) => state,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
tracing::info!(
target: crate::TRACING_TARGET,
config_path = app_state.config_path(),
active_profile = app_state.active_profile().name.as_str(),
logging_routes = app_state.logging_route_count(),
"starting desktop demo application"
);
let tracing_builder = tauri_plugin_tracing::Builder::new();
let mut builder = tauri::Builder::default();
builder = builder.manage(app_state);
builder =
builder.invoke_handler(tauri::generate_handler![emit_frontend_log, load_project_readme,]);
builder = builder.plugin(tracing_builder.build::<tauri::Wry>());
builder = builder.setup(|app| {
let splash_window = match app.get_webview_window("splash") {
std::option::Option::Some(window) => window,
std::option::Option::None => {
@@ -66,8 +89,38 @@ pub fn run() -> kb_core::Result<()> {
let run_result = builder.run(tauri::generate_context!());
return match run_result {
std::result::Result::Ok(()) => std::result::Result::Ok(()),
std::result::Result::Err(error) => std::result::Result::Err(kb_core::Error::tauri(format!(
"cannot run desktop demo application: {error:?}"
))),
std::result::Result::Err(error) => std::result::Result::Err(kb_core::Error::tauri(
format!("cannot run desktop demo application: {error:?}"),
)),
};
}
fn install_default_rustls_provider() -> kb_core::Result<()> {
if rustls::crypto::CryptoProvider::get_default().is_some() {
return std::result::Result::Ok(());
}
let provider_result = rustls::crypto::aws_lc_rs::default_provider().install_default();
return match provider_result {
std::result::Result::Ok(()) => std::result::Result::Ok(()),
std::result::Result::Err(error) => std::result::Result::Err(kb_core::Error::invalid_state(
format!("cannot install default rustls crypto provider: {error:?}"),
)),
};
}
fn into_ipc_result<T>(result: kb_core::Result<T>) -> std::result::Result<T, std::string::String> {
return match result {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(error) => std::result::Result::Err(error.to_string()),
};
}
#[tauri::command]
fn emit_frontend_log(payload: crate::FrontendLogPayload) {
crate::emit_frontend_log(payload);
}
#[tauri::command]
fn load_project_readme() -> std::result::Result<std::string::String, std::string::String> {
return into_ipc_result(crate::load_project_readme());
}