Skip to content

Commit fa72a66

Browse files
committed
perf(runtime): optimize startup latency, isolate webview ipc broadcasts, and harden keyed lock concurrency
- Isolate agentic streaming events to main window via TransportAdapter::emit_to to prevent IPC storm across auxiliary webviews - Lower workspace startup snapshot block timeout from 4000ms to 150ms to eliminate window creation freeze - Make Tokio worker threads auto-scale with available CPU parallelism (2..=8) - Parallelize plugin host and miniapp initialization during pre-Tauri setup - Add browser_webview_close Tauri command and wire frontend lifecycle cleanup to reclaim webview/VRAM resources - Replace KeyedAsyncLock single StdMutex<HashMap> with DashMap striped concurrency and atomic dead key reclamation
1 parent 7e23bdb commit fa72a66

8 files changed

Lines changed: 123 additions & 67 deletions

File tree

‎src/apps/desktop/src/api/app_state.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,9 +169,12 @@ impl AppState {
169169
log::warn!("Failed to mark stale miniapp drafts for cleanup: {}", e);
170170
}
171171
}
172-
if let Err(e) = seed_builtin_miniapps(&miniapp_manager).await {
173-
log::warn!("Failed to seed built-in miniapps: {}", e);
174-
}
172+
let seed_manager = miniapp_manager.clone();
173+
tokio::spawn(async move {
174+
if let Err(e) = seed_builtin_miniapps(&seed_manager).await {
175+
log::warn!("Failed to seed built-in miniapps: {}", e);
176+
}
177+
});
175178

176179
let worker_host_path = match resolve_worker_host_path() {
177180
Some(p) => {

‎src/apps/desktop/src/api/browser_api.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,19 @@ pub async fn browser_get_url(
692692
.map_err(|e| format!("url failed: {e}"))
693693
}
694694

695+
#[tauri::command]
696+
pub async fn browser_webview_close(
697+
app: tauri::AppHandle,
698+
request: WebviewLabelRequest,
699+
) -> Result<(), String> {
700+
validate_browser_label(&request.label)?;
701+
unregister_browser_target(&request.label);
702+
if let Some(webview) = app.get_webview(&request.label) {
703+
let _ = webview.close();
704+
}
705+
Ok(())
706+
}
707+
695708
#[cfg(test)]
696709
mod tests {
697710
use super::*;

‎src/apps/desktop/src/lib.rs‎

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -556,41 +556,44 @@ pub async fn run() {
556556
startup_timings.record_elapsed("initialize_global_config", step_started);
557557
startup_trace.record_elapsed_step("native_pre_tauri", "initialize_global_config", step_started);
558558

559-
let step_started = Instant::now();
560-
match openbitfun_core::plugin_host::initialize_configured_plugin_host_with_log_file(
561-
PLUGIN_HOST_LAUNCH_POLICY,
562-
Some(session_log_dir.join("plugin-host.log")),
563-
)
564-
.await
565-
{
566-
Ok(openbitfun_core::plugin_host::PluginHostStartup::Disabled) => {}
567-
Ok(status) => log::info!("Plugin host initialization completed: {:?}", status),
568-
Err(error) => {
569-
log::error!("Failed to initialize configured plugin host: {}", error);
570-
openbitfun_core::plugin_host::report_configured_plugin_activation_failure(
571-
"Desktop startup",
572-
None,
573-
error,
574-
)
575-
.await;
576-
}
577-
}
578-
startup_timings.record_elapsed("initialize_plugin_host", step_started);
579-
startup_trace.record_elapsed_step("native_pre_tauri", "initialize_plugin_host", step_started);
580-
581-
// The three steps below only depend on the global config service (initialized
582-
// above) and write to disjoint global singletons, so they can run concurrently:
559+
// The four steps below only depend on the global config service (initialized
560+
// above) and write to disjoint targets, so they can run concurrently:
561+
// - initialize_plugin_host: starts the plugin host process
583562
// - initialize_global_i18n_service: reads config, sets the global i18n singleton
584563
// - resolve_runtime_log_level: reads config, returns a value
585564
// - AIClientFactory::initialize_global: reads config, sets GLOBAL_AI_CLIENT_FACTORY
586565
let (
566+
plugin_host_duration_ms,
587567
i18n_duration_ms,
588568
(startup_log_level, log_level_duration_ms),
589569
(ai_factory_result, ai_factory_duration_ms),
590570
) = {
591571
use openbitfun_core::service::config::get_global_config_service;
592572
use openbitfun_core::service::i18n::initialize_global_i18n_service;
593573

574+
let plugin_host_task = async {
575+
let step_started = Instant::now();
576+
match openbitfun_core::plugin_host::initialize_configured_plugin_host_with_log_file(
577+
PLUGIN_HOST_LAUNCH_POLICY,
578+
Some(session_log_dir.join("plugin-host.log")),
579+
)
580+
.await
581+
{
582+
Ok(openbitfun_core::plugin_host::PluginHostStartup::Disabled) => {}
583+
Ok(status) => log::info!("Plugin host initialization completed: {:?}", status),
584+
Err(error) => {
585+
log::error!("Failed to initialize configured plugin host: {}", error);
586+
openbitfun_core::plugin_host::report_configured_plugin_activation_failure(
587+
"Desktop startup",
588+
None,
589+
error,
590+
)
591+
.await;
592+
}
593+
}
594+
elapsed_ms(step_started)
595+
};
596+
594597
// Initialize global I18nService so bot/remote-connect language is always in sync.
595598
let i18n_task = async {
596599
let step_started = Instant::now();
@@ -619,9 +622,16 @@ pub async fn run() {
619622
(result, elapsed_ms(step_started))
620623
};
621624

622-
tokio::join!(i18n_task, log_level_task, ai_factory_task)
625+
tokio::join!(plugin_host_task, i18n_task, log_level_task, ai_factory_task)
623626
};
624627

628+
startup_timings.push_duration("initialize_plugin_host", plugin_host_duration_ms);
629+
startup_trace.record_step(
630+
"native_step_end",
631+
"native_pre_tauri",
632+
"initialize_plugin_host",
633+
plugin_host_duration_ms,
634+
);
625635
startup_timings.push_duration("initialize_global_i18n_service", i18n_duration_ms);
626636
startup_trace.record_step(
627637
"native_step_end",
@@ -1071,7 +1081,7 @@ pub async fn run() {
10711081
// on timeout the frontend falls back to the existing
10721082
// `initialize_workspace_startup_state` command path.
10731083
const WORKSPACE_STARTUP_SNAPSHOT_TIMEOUT: std::time::Duration =
1074-
std::time::Duration::from_secs(4);
1084+
std::time::Duration::from_millis(150);
10751085
tokio::task::block_in_place(|| {
10761086
tokio::runtime::Handle::current().block_on(async {
10771087
match tokio::time::timeout(
@@ -2008,6 +2018,7 @@ pub async fn run() {
20082018
api::browser_api::browser_webview_capture_preview,
20092019
api::browser_api::browser_webview_set_agent_target_state,
20102020
api::browser_api::browser_get_url,
2021+
api::browser_api::browser_webview_close,
20112022
api::html_preview_api::html_preview_create,
20122023
api::html_preview_api::html_preview_read_resource,
20132024
api::html_preview_api::html_preview_release,

‎src/apps/desktop/src/main.rs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,15 @@ fn main() {
66
// Tokio reads this value while creating its worker threads. Setting it in
77
// the async body is too late, because the runtime has already been built.
88
std::env::set_var("RUST_MIN_STACK", "8388608"); // 8 MiB worker stacks
9+
10+
// Size worker threads dynamically according to host hardware (bounded between 2 and 8)
11+
// to prevent over-allocation on dual-core and under-utilization on multi-core systems.
12+
let worker_threads = std::thread::available_parallelism()
13+
.map(|n| n.get().clamp(2, 8))
14+
.unwrap_or(4);
15+
916
let runtime = tokio::runtime::Builder::new_multi_thread()
10-
.worker_threads(4)
17+
.worker_threads(worker_threads)
1118
.enable_all()
1219
.build()
1320
.expect("failed to build Tokio runtime");

‎src/crates/adapters/transport/src/adapters/tauri.rs‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,30 @@ impl TransportAdapter for TauriTransportAdapter {
4242
warn!("Unhandled AgenticEvent type in TauriAdapter");
4343
return Ok(());
4444
};
45-
self.app_handle
46-
.emit(projected.event_name.as_str(), projected.payload)?;
47-
Ok(())
45+
self.emit_to("main", projected.event_name.as_str(), projected.payload)
46+
.await
4847
}
4948

5049
async fn emit_generic(
5150
&self,
5251
event_name: &str,
5352
payload: serde_json::Value,
5453
) -> anyhow::Result<()> {
55-
self.app_handle.emit(event_name, payload)?;
54+
if event_name.starts_with("agentic://") {
55+
self.emit_to("main", event_name, payload).await
56+
} else {
57+
self.app_handle.emit(event_name, payload)?;
58+
Ok(())
59+
}
60+
}
61+
62+
async fn emit_to(
63+
&self,
64+
target: &str,
65+
event_name: &str,
66+
payload: serde_json::Value,
67+
) -> anyhow::Result<()> {
68+
self.app_handle.emit_to(target, event_name, payload)?;
5669
Ok(())
5770
}
5871
}

‎src/crates/adapters/transport/src/traits.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,15 @@ pub trait TransportAdapter: Send + Sync + Debug {
1414
event_name: &str,
1515
payload: serde_json::Value,
1616
) -> anyhow::Result<()>;
17+
18+
/// Emit an event directed to a specific target window/webview (e.g. "main").
19+
async fn emit_to(
20+
&self,
21+
target: &str,
22+
event_name: &str,
23+
payload: serde_json::Value,
24+
) -> anyhow::Result<()> {
25+
let _ = target;
26+
self.emit_generic(event_name, payload).await
27+
}
1728
}

‎src/crates/assembly/core/src/agentic/keyed_lock.rs‎

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
use std::collections::HashMap;
2-
use std::sync::{Arc, Mutex as StdMutex, Weak};
1+
use std::sync::{Arc, Weak};
32

3+
use dashmap::DashMap;
44
use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
55

66
pub(crate) struct KeyedAsyncLockGuard {
77
guard: Option<OwnedMutexGuard<()>>,
8-
registry: Arc<StdMutex<HashMap<String, Weak<AsyncMutex<()>>>>>,
8+
registry: Arc<DashMap<String, Weak<AsyncMutex<()>>>>,
99
key: String,
1010
generation: Weak<AsyncMutex<()>>,
1111
}
@@ -16,44 +16,44 @@ impl Drop for KeyedAsyncLockGuard {
1616
// waiter either upgrades this generation first or creates the next one
1717
// after removal; two live generations cannot overlap.
1818
drop(self.guard.take());
19-
let mut registry = self
20-
.registry
21-
.lock()
22-
.unwrap_or_else(|error| error.into_inner());
23-
if registry
24-
.get(&self.key)
25-
.is_some_and(|current| current.ptr_eq(&self.generation) && current.upgrade().is_none())
26-
{
27-
registry.remove(&self.key);
28-
}
19+
self.registry.remove_if(&self.key, |_, current| {
20+
current.ptr_eq(&self.generation) && current.upgrade().is_none()
21+
});
2922
}
3023
}
3124

3225
/// Race-safe keyed async lock registry.
3326
///
34-
/// The registry owns only weak references. Waiters keep the lock generation
35-
/// alive through their strong references, while dead keys are reclaimed on the
36-
/// next acquisition without allowing two live generations for one key.
27+
/// The registry owns only weak references backed by a sharded concurrent map (DashMap).
28+
/// Waiters keep the lock generation alive through their strong references, while dead
29+
/// keys are reclaimed atomically without holding a process-wide mutex.
3730
#[derive(Clone, Default)]
3831
pub(crate) struct KeyedAsyncLock {
39-
registry: Arc<StdMutex<HashMap<String, Weak<AsyncMutex<()>>>>>,
32+
registry: Arc<DashMap<String, Weak<AsyncMutex<()>>>>,
4033
}
4134

4235
impl KeyedAsyncLock {
4336
pub(crate) async fn lock(&self, key: &str) -> KeyedAsyncLockGuard {
4437
let (lock, generation) = {
45-
let mut registry = self
46-
.registry
47-
.lock()
48-
.unwrap_or_else(|error| error.into_inner());
49-
if let Some(lock) = registry.get(key).and_then(Weak::upgrade) {
50-
let generation = Arc::downgrade(&lock);
51-
(lock, generation)
52-
} else {
53-
let lock = Arc::new(AsyncMutex::new(()));
54-
let generation = Arc::downgrade(&lock);
55-
registry.insert(key.to_string(), generation.clone());
56-
(lock, generation)
38+
let mut entry = self.registry.entry(key.to_string());
39+
match entry {
40+
dashmap::mapref::entry::Entry::Occupied(ref mut occupied) => {
41+
if let Some(lock) = occupied.get().upgrade() {
42+
let generation = Arc::downgrade(&lock);
43+
(lock, generation)
44+
} else {
45+
let lock = Arc::new(AsyncMutex::new(()));
46+
let generation = Arc::downgrade(&lock);
47+
occupied.insert(generation.clone());
48+
(lock, generation)
49+
}
50+
}
51+
dashmap::mapref::entry::Entry::Vacant(vacant) => {
52+
let lock = Arc::new(AsyncMutex::new(()));
53+
let generation = Arc::downgrade(&lock);
54+
vacant.insert(generation.clone());
55+
(lock, generation)
56+
}
5757
}
5858
};
5959
let guard = lock.lock_owned().await;
@@ -67,10 +67,7 @@ impl KeyedAsyncLock {
6767

6868
#[cfg(test)]
6969
fn registry_len(&self) -> usize {
70-
self.registry
71-
.lock()
72-
.unwrap_or_else(|error| error.into_inner())
73-
.len()
70+
self.registry.len()
7471
}
7572
}
7673

‎src/web-ui/src/app/scenes/browser/useEmbeddedBrowserWebview.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,7 @@ export function useEmbeddedBrowserWebview(options: UseEmbeddedBrowserWebviewOpti
346346

347347
try {
348348
await setAgentTargetState(target.label, false).catch(() => {});
349+
await api.invoke('browser_webview_close', { request: { label: target.label } }).catch(() => {});
349350
await target.close();
350351
} catch (closeError) {
351352
if (!isWebviewNotFoundError(closeError)) {

0 commit comments

Comments
 (0)