diff --git a/design-system/packages/ui/src/flow-chat/conversation/FlowItemRhythm.css b/design-system/packages/ui/src/flow-chat/conversation/FlowItemRhythm.css index c3fe346a6e..4ca7317743 100644 --- a/design-system/packages/ui/src/flow-chat/conversation/FlowItemRhythm.css +++ b/design-system/packages/ui/src/flow-chat/conversation/FlowItemRhythm.css @@ -15,7 +15,13 @@ :is([data-flow-item-stack], .explore-region__content, .flow-group-content-segment):has( > .flowchat-flow-item > .flow-tool-card-wrapper [data-openbitfun-tool-card='agent-control'] -) > * { +) > :where(.flowchat-flow-item, .flow-text-block, .flow-thinking-item, + .subagent-projection-text--truncated, .flowchat-capsule-row-break, + .explore-region, .flow-group-content-segment, .model-round-item__meta, + .model-round-item__continuation, .model-round-item__retry-history, .model-round-item__footer) { + /* The stack renderers own these children. An unqualified child after :has() + registered subtree invalidation on unrelated shell ancestors during row + recycling. :where() keeps the original rule's specificity and geometry. */ flex: 0 0 100%; min-inline-size: 0; } diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 07d0e52015..2501934ccc 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -3781,7 +3781,7 @@ "visibility": "documented", "rustPath": "get_mode_skill_configs", "sourceFile": "src/apps/desktop/src/api/skill_api.rs", - "signature": "fn get_mode_skill_configs( state: State<'_, AppState>, mode_id: String, force_refresh: Option, include_diagnostics: Option, workspace_id: Option, workspace_path: Option, ) -> Result", + "signature": "fn get_mode_skill_configs( state: State<'_, AppState>, mode_id: String, force_refresh: Option, include_diagnostics: Option, workspace_id: Option, workspace_path: Option, summary_mode_ids: Option>, ) -> Result", "remoteWorkspacePolicy": "LegacyUnaudited" }, { diff --git a/scripts/generate-miniapp-chat-styles.mjs b/scripts/generate-miniapp-chat-styles.mjs index dac35829fa..654004f137 100644 --- a/scripts/generate-miniapp-chat-styles.mjs +++ b/scripts/generate-miniapp-chat-styles.mjs @@ -24,7 +24,8 @@ export async function buildMiniAppChatStyles() { const style = output.find(file => file.type === 'asset' && file.fileName.endsWith('.css')); if (!script || !style || script.imports.length || script.dynamicImports.length) throw new Error('MiniApp chat projection must contain only CSS and static class names'); const header = '/* Generated from the Hi and FlowChat style owners by scripts/generate-miniapp-chat-styles.mjs. */\n'; - return { 'chat-style-classes.js': header + script.code, 'chat-styles.css': header + style.source }; + // Vite preserves imported CSS line endings; generated projections use LF on every host. + return { 'chat-style-classes.js': header + script.code, 'chat-styles.css': header + String(style.source).replace(/\r\n?/g, '\n') }; } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { diff --git a/src/apps/cli/AGENTS.md b/src/apps/cli/AGENTS.md index e3ce230805..28a83902f6 100644 --- a/src/apps/cli/AGENTS.md +++ b/src/apps/cli/AGENTS.md @@ -150,6 +150,7 @@ Run the smallest checks matching the changed path: cargo check -p openbitfun-cli cargo test -p openbitfun-cli cargo test -p openbitfun-cli --bin openbitfun peer_host:: +cargo test --locked -p openbitfun-cli --bin openbitfun peer_host::commands::skills::tests cargo test -p openbitfun-cli --bin openbitfun system_info_home_contract ``` diff --git a/src/apps/cli/src/peer_host/commands/session.rs b/src/apps/cli/src/peer_host/commands/session.rs index a461a730eb..35f58ffe10 100644 --- a/src/apps/cli/src/peer_host/commands/session.rs +++ b/src/apps/cli/src/peer_host/commands/session.rs @@ -1007,6 +1007,31 @@ pub(crate) async fn get_available_modes( let mode_infos = get_agent_registry() .get_modes_info_for_workspace(workspace_id.as_deref(), workspace_id.is_some()) .await; + let include_counts = request + .get("includeSubagentCounts") + .and_then(Value::as_bool) + .unwrap_or(false); + let counts = if include_counts { + let local_scope = match workspace_id.as_deref() { + Some(id) => { + state + .workspace_service + .require_workspace(id) + .await + .map_err(|error| error.to_string())? + .workspace_kind + != openbitfun_core::service::workspace::WorkspaceKind::Remote + } + None => false, + }; + Some( + get_agent_registry() + .mode_manageable_subagent_counts(&mode_infos, workspace_id.as_deref(), local_scope) + .await, + ) + } else { + None + }; let dtos: Vec = mode_infos .into_iter() .map(|info| { @@ -1014,7 +1039,11 @@ pub(crate) async fn get_available_modes( .config_profile_id .clone() .unwrap_or_else(|| info.id.clone()); - json!({ + let count = counts + .as_ref() + .and_then(|counts| counts.get(&config_profile_id)) + .copied(); + let mut dto = json!({ "id": info.id, "name": info.name, "description": info.description, @@ -1028,7 +1057,13 @@ pub(crate) async fn get_available_modes( "source": info.source, "path": info.path, "model": info.model, - }) + }); + if let Some(count) = count { + dto.as_object_mut() + .unwrap() + .insert("manageableSubagentCount".into(), Value::from(count)); + } + dto }) .collect(); Ok(Value::Array(dtos)) diff --git a/src/apps/cli/src/peer_host/commands/skills.rs b/src/apps/cli/src/peer_host/commands/skills.rs index 4a8121d618..8fad623cd3 100644 --- a/src/apps/cli/src/peer_host/commands/skills.rs +++ b/src/apps/cli/src/peer_host/commands/skills.rs @@ -128,28 +128,70 @@ pub(crate) async fn get_skill_configs(args: &Value) -> Result { pub(crate) async fn get_mode_skill_configs(args: &Value) -> Result { let request = request_value(args); let mode_id = get_string(request, "modeId")?; + let summary_ids = request + .get("summaryModeIds") + .filter(|value| !value.is_null()) + .map(|value| { + serde_json::from_value::>(value.clone()) + .map_err(|error| format!("Invalid summaryModeIds: {error}")) + }) + .transpose()?; + let include_diagnostics = optional_bool(request, "includeDiagnostics").unwrap_or(false); + let summary = include_diagnostics && summary_ids.is_some(); + let mut mode_ids = if summary { + summary_ids.unwrap_or_default() + } else { + Vec::new() + }; + if !mode_ids.contains(&mode_id) { + mode_ids.push(mode_id.clone()); + } let workspace = resolve_workspace(request).await?; let registry = SkillRegistry::global(); if optional_bool(request, "forceRefresh").unwrap_or(false) { registry.refresh().await; } - let report = if let Some((root, fs)) = remote_workspace_fs(workspace.as_ref()).await? { + let mut reports = if let Some((root, fs)) = remote_workspace_fs(workspace.as_ref()).await? { within_remote_deadline( - registry.get_mode_skill_scan_report_for_remote_workspace(&fs, &root, &mode_id), + registry.get_mode_skill_scan_reports_for_remote_workspace(&fs, &root, &mode_ids), ) .await? } else { registry - .get_mode_skill_scan_report_for_workspace( + .get_mode_skill_scan_reports_for_workspace( workspace.as_ref().map(SkillPolicyWorkspace::from_record), - &mode_id, + &mode_ids, ) .await }; - scan_response( - report, - optional_bool(request, "includeDiagnostics").unwrap_or(false), - ) + let counts: std::collections::HashMap = reports + .iter() + .map(|(id, report)| { + ( + id.clone(), + report + .skills + .iter() + .filter(|skill| skill.effective_enabled) + .count(), + ) + }) + .collect(); + let report = reports + .remove(&mode_id) + .expect("The anchor mode is included in the summary"); + let mut response = scan_response(report, include_diagnostics)?; + if summary { + let object = response + .as_object_mut() + .expect("Diagnostics responses are objects"); + object.insert("skillCountsVersion".into(), Value::from(1)); + object.insert( + "enabledSkillCounts".into(), + serde_json::to_value(counts).map_err(|error| error.to_string())?, + ); + } + Ok(response) } /// Read-only availability settings. Version 0 tells the controller that direct @@ -189,6 +231,42 @@ mod tests { assert!(error.contains("modeId"), "{error}"); } + #[tokio::test] + async fn invalid_summary_ids_fail_before_discovery() { + let error = get_mode_skill_configs( + &json!({"modeId":"Cowork","includeDiagnostics":true,"summaryModeIds":[1]}), + ) + .await + .unwrap_err(); + assert!(error.contains("summaryModeIds")); + } + + #[tokio::test] + async fn mode_summary_preserves_legacy_payloads() { + let legacy = get_mode_skill_configs(&json!({"modeId":"Cowork"})) + .await + .unwrap(); + let diagnostic = + get_mode_skill_configs(&json!({"modeId":"Cowork","includeDiagnostics":true})) + .await + .unwrap(); + assert_eq!(legacy, diagnostic["skills"]); + assert!(diagnostic.get("skillCountsVersion").is_none()); + let summary = get_mode_skill_configs(&json!({"modeId":"Cowork","includeDiagnostics":true,"summaryModeIds":["Cowork","review","Cowork"]})).await.unwrap(); + assert_eq!(legacy, summary["skills"]); + assert_eq!(summary["skillCountsVersion"], 1); + assert_eq!( + summary["enabledSkillCounts"]["Cowork"].as_u64().unwrap(), + legacy + .as_array() + .unwrap() + .iter() + .filter(|skill| skill["effectiveEnabled"] == true) + .count() as u64 + ); + assert!(summary["enabledSkillCounts"]["review"].is_number()); + } + #[test] fn global_settings_are_read_only_on_this_host() { let settings = global_settings_value(vec!["user::a".into()], Vec::new()); diff --git a/src/apps/desktop/src/api/agentic_api.rs b/src/apps/desktop/src/api/agentic_api.rs index 3537c42af2..c76e19cd35 100644 --- a/src/apps/desktop/src/api/agentic_api.rs +++ b/src/apps/desktop/src/api/agentic_api.rs @@ -4256,6 +4256,20 @@ pub async fn get_available_modes( ) .await; + let counts = if request.include_subagent_counts == Some(true) { + Some( + state + .agent_registry + .mode_manageable_subagent_counts( + &mode_infos, + workspace.as_ref().map(|record| record.id.as_str()), + external_sources_supported, + ) + .await, + ) + } else { + None + }; let dtos: Vec = mode_infos .into_iter() .map(|info| { @@ -4264,6 +4278,10 @@ pub async fn get_available_modes( .clone() .unwrap_or_else(|| info.id.clone()); ModeInfoDTO { + manageable_subagent_count: counts + .as_ref() + .and_then(|counts| counts.get(&config_profile_id)) + .copied(), id: info.id, name: info.name, description: info.description, @@ -4288,6 +4306,7 @@ pub async fn get_available_modes( #[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GetAvailableModesRequest { + pub include_subagent_counts: Option, pub workspace_id: Option, pub workspace_path: Option, pub remote_connection_id: Option, @@ -4316,6 +4335,8 @@ pub async fn get_default_review_team_definition() -> Result, pub id: String, pub name: String, pub description: String, @@ -4426,6 +4447,19 @@ mod tests { use openbitfun_product_domains::tool_permissions::{PermissionEffect, PermissionRule}; use serde_json::json; + #[test] + fn legacy_mode_catalog_requests_do_not_require_summary_fields() { + let old: GetAvailableModesRequest = + serde_json::from_value(json!({"workspaceId":"workspace-1"})).unwrap(); + assert_eq!(old.include_subagent_counts, None); + assert_eq!(old.workspace_id.as_deref(), Some("workspace-1")); + let new: GetAvailableModesRequest = serde_json::from_value( + json!({"workspaceId":"workspace-1","includeSubagentCounts":true}), + ) + .unwrap(); + assert_eq!(new.include_subagent_counts, Some(true)); + } + #[tokio::test] async fn mode_catalog_uses_record_kind_even_when_local_and_remote_paths_are_identical() { use openbitfun_core::service::workspace::{ diff --git a/src/apps/desktop/src/api/skill_api.rs b/src/apps/desktop/src/api/skill_api.rs index 3276924345..d33df13cbe 100644 --- a/src/apps/desktop/src/api/skill_api.rs +++ b/src/apps/desktop/src/api/skill_api.rs @@ -755,6 +755,7 @@ pub async fn get_mode_skill_configs( include_diagnostics: Option, workspace_id: Option, workspace_path: Option, + summary_mode_ids: Option>, ) -> Result { let workspace = resolve_skill_workspace(workspace_id.as_deref(), workspace_path.as_deref()).await?; @@ -764,6 +765,71 @@ pub async fn get_mode_skill_configs( registry.refresh().await; } + // Additive projection on the existing diagnostics response. Older hosts + // ignore the optional argument; controllers check skillCountsVersion before + // using the summary and retain the single-mode compatibility path. + if let Some(mut mode_ids) = summary_mode_ids.filter(|_| include_diagnostics == Some(true)) { + if !mode_ids.contains(&mode_id) { + mode_ids.push(mode_id.clone()); + } + let mut reports = if let Some((remote_root, entry)) = + resolve_remote_workspace(workspace.as_ref()).await? + { + await_remote_skill_discovery( + async { + let remote_fs = state + .get_remote_file_service_async() + .await + .map_err(|error| format!("Remote file service not available: {error}"))?; + let fs = RemoteWorkspaceFs::new(entry, remote_fs); + Ok(registry + .get_mode_skill_scan_reports_for_remote_workspace( + &fs, + &remote_root, + &mode_ids, + ) + .await) + }, + REMOTE_SKILL_DISCOVERY_TIMEOUT, + ) + .await? + } else { + registry + .get_mode_skill_scan_reports_for_workspace( + workspace.as_ref().map(SkillPolicyWorkspace::from_record), + &mode_ids, + ) + .await + }; + let counts: HashMap = reports + .iter() + .map(|(id, report)| { + ( + id.clone(), + report + .skills + .iter() + .filter(|skill| skill.effective_enabled) + .count(), + ) + }) + .collect(); + let report = reports + .remove(&mode_id) + .expect("The anchor mode is included in the summary"); + let mut response = + serialize_skill_scan_response(report, true).map_err(|error| error.to_string())?; + let object = response + .as_object_mut() + .expect("Diagnostics responses are objects"); + object.insert("skillCountsVersion".into(), Value::from(1)); + object.insert( + "enabledSkillCounts".into(), + serde_json::to_value(counts).map_err(|error| error.to_string())?, + ); + return Ok(response); + } + let mode_skill_infos = get_mode_skill_scan_report_for_workspace_input( &state, registry, diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index 5b9172c1a7..a39efaec5b 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -521,7 +521,7 @@ cargo test --locked -p openbitfun-core --no-default-features --features agent-ru Skill discovery, installation provenance, and local/remote registry regressions: ```bash -cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib agentic::tools::implementations::skills:: +cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git,file-watch --lib agentic::tools::implementations::skills:: ``` SessionControl workspace selection, remote routing, and session-targeted actions: diff --git a/src/crates/assembly/core/src/agentic/agents/registry/query.rs b/src/crates/assembly/core/src/agentic/agents/registry/query.rs index 02d87aec4c..2815bdece9 100644 --- a/src/crates/assembly/core/src/agentic/agents/registry/query.rs +++ b/src/crates/assembly/core/src/agentic/agents/registry/query.rs @@ -35,6 +35,44 @@ pub(super) fn merge_dynamic_mode_tools( } impl AgentRegistry { + /// Lightweight counts use the same management policy as the detail query. + /// Profiles shared by several harness modes are resolved only once. + pub async fn mode_manageable_subagent_counts( + &self, + modes: &[AgentInfo], + workspace_id: Option<&str>, + external_sources_supported: bool, + ) -> std::collections::HashMap { + let mut counts = std::collections::HashMap::new(); + for mode in modes { + let profile = mode.config_profile_id.as_deref().unwrap_or(&mode.id); + if counts.contains_key(profile) { + continue; + } + let agents = self + .get_subagents_for_query(&SubagentQueryContext { + parent_agent_type: Some(&mode.id), + workspace_id: if external_sources_supported { + workspace_id + } else { + None + }, + list_scope: SubagentListScope::RegistryManagement, + include_disabled: true, + external_sources_supported, + }) + .await; + counts.insert( + profile.to_owned(), + agents + .iter() + .filter(|agent| agent.effective_enabled) + .count(), + ); + } + counts + } + /// Recursive delegation is an explicit tool capability. It only takes /// effect inside Swarm; ordinary child sessions remain non-recursive. pub(crate) async fn can_delegate_in_swarm( diff --git a/src/crates/assembly/core/src/agentic/agents/registry/tests.rs b/src/crates/assembly/core/src/agentic/agents/registry/tests.rs index 49c3dd3a2b..5513cb72c0 100644 --- a/src/crates/assembly/core/src/agentic/agents/registry/tests.rs +++ b/src/crates/assembly/core/src/agentic/agents/registry/tests.rs @@ -2539,3 +2539,37 @@ fn local_route_resolves_review_agents_as_session_primaries() { ); } } + +#[tokio::test] +async fn mode_catalog_counts_match_management_visibility_and_shared_profiles() { + let registry = AgentRegistry::new(); + let modes = registry.get_modes_info_for_workspace(None, false).await; + assert!(!modes.is_empty()); + let counts = registry + .mode_manageable_subagent_counts(&modes, None, false) + .await; + let mut checked = std::collections::HashSet::new(); + for mode in &modes { + let profile = mode.config_profile_id.as_deref().unwrap_or(&mode.id); + if !checked.insert(profile) { + continue; + } + let children = registry + .get_subagents_for_query(&SubagentQueryContext { + parent_agent_type: Some(&mode.id), + workspace_id: None, + list_scope: SubagentListScope::RegistryManagement, + include_disabled: true, + external_sources_supported: false, + }) + .await; + assert_eq!( + counts[profile], + children + .iter() + .filter(|agent| agent.effective_enabled) + .count() + ); + } + assert_eq!(counts.len(), checked.len()); +} diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/skills/builtin.rs b/src/crates/assembly/core/src/agentic/tools/implementations/skills/builtin.rs index 93f9d85ccb..0ceb59a8d0 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/skills/builtin.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/skills/builtin.rs @@ -172,8 +172,11 @@ async fn install_builtin_skills_to_staging( pub async fn ensure_builtin_skills_installed() -> OpenBitFunResult<()> { let pm = get_path_manager_arc(); - let user_skills_root = pm.user_skills_dir(); - let dest_root = pm.builtin_skills_dir(); + ensure_builtin_skills_installed_at(&pm.user_skills_dir()).await +} + +async fn ensure_builtin_skills_installed_at(user_skills_root: &Path) -> OpenBitFunResult<()> { + let dest_root = user_skills_root.join(".system"); // Create the parent user skills directory before taking the shared install // lock so every contender points at the same stable path. @@ -194,23 +197,21 @@ pub async fn ensure_builtin_skills_installed() -> OpenBitFunResult<()> { } } - let staging_root = builtin_skills_staging_root(&user_skills_root); - if let Err(error) = fs::remove_dir_all(&staging_root).await { - if error.kind() != std::io::ErrorKind::NotFound { - return Err(error.into()); - } - } - fs::create_dir_all(&staging_root).await?; + let staging_root = builtin_skills_staging_root(user_skills_root); + fs::create_dir(&staging_root).await?; + // A packaged Windows parent can virtualize a newly created AppData child + // onto another volume even when the logical parent already exists on C:. + // Publish both paths through the created directory's physical parent. + let staging_root = fs::canonicalize(&staging_root).await?; + let publish_parent = staging_root.parent().ok_or_else(|| { + crate::util::errors::OpenBitFunError::io("Built-in skills staging parent is unavailable") + })?; + let dest_root = publish_parent.join(".system"); let publish_result = async { let (installed, updated) = install_builtin_skills_to_staging(&staging_root).await?; - if let Err(error) = fs::remove_dir_all(&dest_root).await { - if error.kind() != std::io::ErrorKind::NotFound { - return Err(error.into()); - } - } - fs::rename(&staging_root, &dest_root).await?; + publish_staged_skills(&staging_root, &dest_root).await?; if installed > 0 || updated > 0 { debug!( @@ -238,6 +239,57 @@ pub async fn ensure_builtin_skills_installed() -> OpenBitFunResult<()> { publish_result } +async fn publish_staged_skills(staging_root: &Path, dest_root: &Path) -> OpenBitFunResult<()> { + // Only replace the managed bundle, with a rollback copy on the same volume. + let parent = staging_root.parent().ok_or_else(|| { + crate::util::errors::OpenBitFunError::io("Built-in skills staging parent is unavailable") + })?; + if !staging_root.is_absolute() || dest_root != parent.join(".system") { + return Err(crate::util::errors::OpenBitFunError::validation( + "Built-in skills publication paths do not share the managed parent".to_string(), + )); + } + if let Ok(metadata) = fs::symlink_metadata(dest_root).await { + if metadata.file_type().is_symlink() { + return Err(crate::util::errors::OpenBitFunError::validation( + "The managed built-in skills directory must not be a symbolic link".to_string(), + )); + } + } + let name = staging_root.file_name().ok_or_else(|| { + crate::util::errors::OpenBitFunError::io("Built-in skills staging name is unavailable") + })?; + let backup = parent.join(format!("{}.previous", name.to_string_lossy())); + let previous = match fs::rename(dest_root, &backup).await { + Ok(()) => true, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, + Err(error) => return Err(error.into()), + }; + if let Err(error) = fs::rename(staging_root, dest_root).await { + if previous { + if let Err(restore_error) = fs::rename(&backup, dest_root).await { + error!( + "Failed to restore built-in skills bundle: backup={}, destination={}, error={}", + backup.display(), + dest_root.display(), + restore_error + ); + } + } + return Err(error.into()); + } + if previous { + if let Err(error) = fs::remove_dir_all(&backup).await { + warn!( + "Failed to remove previous built-in skills bundle: path={}, error={}", + backup.display(), + error + ); + } + } + Ok(()) +} + #[derive(Default)] struct SyncStats { installed: usize, @@ -317,6 +369,59 @@ mod tests { use super::BUILTIN_SKILLS_DIR; use openbitfun_agent_runtime::skills::{SkillData, SkillLocation}; + #[tokio::test] + async fn installation_reuses_a_complete_manifest_without_rewriting_the_bundle() { + let root = tempfile::tempdir().unwrap(); + super::ensure_builtin_skills_installed_at(root.path()) + .await + .unwrap(); + let installed = root.path().join(".system"); + let marker = installed.join("cache-reuse-marker"); + tokio::fs::write(&marker, b"retained").await.unwrap(); + super::ensure_builtin_skills_installed_at(root.path()) + .await + .unwrap(); + assert_eq!(tokio::fs::read(marker).await.unwrap(), b"retained"); + assert!(installed.join("create-agent/SKILL.md").is_file()); + assert_eq!( + super::read_installed_manifest(&installed) + .await + .unwrap() + .unwrap() + .bundle_hash, + super::builtin_skills_bundle_hash() + ); + } + + #[tokio::test] + async fn publication_replaces_retired_files_and_preserves_the_old_bundle_on_failure() { + let root = tempfile::tempdir().unwrap(); + let parent = tokio::fs::canonicalize(root.path()).await.unwrap(); + let dest = parent.join(".system"); + tokio::fs::create_dir(&dest).await.unwrap(); + tokio::fs::write(dest.join("old"), b"old bundle") + .await + .unwrap(); + let missing = parent.join(".system.tmp.missing"); + assert!(super::publish_staged_skills(&missing, &dest).await.is_err()); + assert_eq!( + tokio::fs::read(dest.join("old")).await.unwrap(), + b"old bundle" + ); + let staging = parent.join(".system.tmp.new"); + tokio::fs::create_dir(&staging).await.unwrap(); + tokio::fs::write(staging.join("new"), b"new bundle") + .await + .unwrap(); + super::publish_staged_skills(&staging, &dest).await.unwrap(); + assert_eq!( + tokio::fs::read(dest.join("new")).await.unwrap(), + b"new bundle" + ); + assert!(!dest.join("old").exists()); + assert!(!parent.join(".system.tmp.new.previous").exists()); + } + fn embedded_skill_text(path: &str) -> &'static str { BUILTIN_SKILLS_DIR .get_file(path) diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/skills/mode_overrides.rs b/src/crates/assembly/core/src/agentic/tools/implementations/skills/mode_overrides.rs index 9b860b4aa7..0995eabba2 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/skills/mode_overrides.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/skills/mode_overrides.rs @@ -25,22 +25,38 @@ fn resolve_profile_id(mode_id: &str) -> String { pub async fn load_user_mode_skill_overrides( mode_id: &str, ) -> OpenBitFunResult { + Ok(load_user_mode_skill_overrides_batch(&[mode_id.to_owned()]) + .await? + .remove(mode_id) + .unwrap_or_default()) +} + +pub async fn load_user_mode_skill_overrides_batch( + mode_ids: &[String], +) -> OpenBitFunResult> { let config_service = GlobalConfigManager::get_service().await?; let stored_configs: HashMap = config_service .get_config(Some("ai.agent_profiles")) .await .unwrap_or_default(); - let profile_id = resolve_profile_id(mode_id); - - let config = stored_configs.get(&profile_id); - Ok(normalize_user_mode_skill_overrides( - config - .map(|item| item.disabled_user_skills.clone()) - .unwrap_or_default(), - config - .map(|item| item.enabled_user_skills.clone()) - .unwrap_or_default(), - )) + Ok(mode_ids + .iter() + .map(|id| { + let profile_id = resolve_profile_id(id); + let config = stored_configs.get(&profile_id); + ( + id.clone(), + normalize_user_mode_skill_overrides( + config + .map(|item| item.disabled_user_skills.clone()) + .unwrap_or_default(), + config + .map(|item| item.enabled_user_skills.clone()) + .unwrap_or_default(), + ), + ) + }) + .collect()) } pub async fn set_user_mode_skill_state( @@ -436,21 +452,23 @@ pub async fn load_disabled_mode_skills_remote( remote_root: &str, mode_id: &str, ) -> OpenBitFunResult> { + let document = load_project_mode_skills_document_remote(fs, remote_root).await?; + Ok(get_disabled_mode_skills_from_document(&document, mode_id)) +} + +pub async fn load_project_mode_skills_document_remote( + fs: &dyn WorkspaceFileSystem, + remote_root: &str, +) -> OpenBitFunResult { let path = project_agent_profiles_path_for_remote(remote_root); - let exists = fs.exists(&path).await.unwrap_or(false); - if !exists { - return Ok(Vec::new()); + if !fs.exists(&path).await.unwrap_or(false) { + return Ok(ProjectAgentProfilesDocument::default()); } - let content = fs.read_file_text(&path).await.map_err(|error| { OpenBitFunError::config(format!( "Failed to read remote project mode profiles: {}", error )) })?; - let document = deserialize_project_agent_profiles_document(&content)?; - Ok(get_disabled_project_skills( - &document, - &resolve_profile_id(mode_id), - )) + deserialize_project_agent_profiles_document(&content) } diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/skills/registry.rs b/src/crates/assembly/core/src/agentic/tools/implementations/skills/registry.rs index 1d22cd3a06..b798a0c945 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/skills/registry.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/skills/registry.rs @@ -4,9 +4,11 @@ use super::builtin::ensure_builtin_skills_installed; use super::mode_overrides::{ - load_disabled_mode_skills_local, load_disabled_mode_skills_remote, - load_globally_disabled_project_skills, load_globally_disabled_user_skills, - load_user_mode_skill_overrides, SkillPolicyWorkspace, UserModeSkillOverrides, + get_disabled_mode_skills_from_document, load_disabled_mode_skills_local, + load_disabled_mode_skills_remote, load_globally_disabled_project_skills, + load_globally_disabled_user_skills, load_project_mode_skills_document_local, + load_project_mode_skills_document_remote, load_user_mode_skill_overrides, + load_user_mode_skill_overrides_batch, SkillPolicyWorkspace, UserModeSkillOverrides, }; use super::runtime_settings::apply_builtin_runtime_settings; #[cfg(feature = "file-watch")] @@ -337,13 +339,13 @@ mod local_skill_scan_tests { .find(|item| item.unsupported_field.is_some()) .unwrap(); assert_eq!(unsupported.unsupported_field.as_deref(), Some("context")); - assert!(unsupported.path.ends_with("guard/SKILL.md")); + assert!(Path::new(&unsupported.path).ends_with(Path::new("guard").join("SKILL.md"))); let failure = scan .diagnostics .iter() .find(|item| item.unsupported_field.is_none()) .unwrap(); - assert!(failure.path.ends_with("broken/SKILL.md")); + assert!(Path::new(&failure.path).ends_with(Path::new("broken").join("SKILL.md"))); assert!(failure.message.contains("description")); } @@ -1860,41 +1862,72 @@ impl SkillRegistry { workspace: Option>, mode_id: &str, ) -> SkillScanReport { + self.get_mode_skill_scan_reports_for_workspace(workspace, &[mode_id.to_owned()]) + .await + .remove(mode_id) + .expect("The requested mode is included in the scan") + } + + /// Resolve several mode policies against one discovery snapshot. Catalog + /// counts must not scan the same workspace once per displayed Agent. + pub async fn get_mode_skill_scan_reports_for_workspace( + &self, + workspace: Option>, + mode_ids: &[String], + ) -> HashMap> { let workspace_root = workspace.map(|workspace| workspace.root); let scan = self .scan_skill_candidates_with_diagnostics_for_workspace(workspace_root) .await; let candidates = scan.candidates; let all_skills = sort_skills(annotate_shadowed_skills(candidates.clone())); - let user_overrides = load_user_mode_skill_overrides(mode_id) + let globally_disabled_user_skills = Self::globally_disabled_skill_keys(workspace).await; + let mut user_overrides_by_mode = load_user_mode_skill_overrides_batch(mode_ids) .await - .unwrap_or_else(|_| UserModeSkillOverrides::default()); - let disabled_project = match workspace_root { - Some(root) => load_disabled_mode_skills_local(root, mode_id) + .unwrap_or_default(); + let project_document = match workspace_root { + Some(root) => load_project_mode_skills_document_local(root) .await .unwrap_or_default(), - None => Vec::new(), + None => Default::default(), }; - let disabled_project: HashSet = - normalize_skill_keys(disabled_project).into_iter().collect(); - let globally_disabled_user_skills = Self::globally_disabled_skill_keys(workspace).await; - let filtered = Self::filter_globally_disabled_candidates( - filter_candidates_for_mode(candidates, mode_id, &user_overrides, &disabled_project), - &globally_disabled_user_skills, - ); - let resolved = resolve_visible_skills(filtered); - - SkillScanReport { - skills: build_mode_skill_infos( - all_skills, - resolved, - mode_id, - &user_overrides, - &disabled_project, + let mut reports = HashMap::new(); + for mode_id in mode_ids { + if reports.contains_key(mode_id) { + continue; + } + let user_overrides = user_overrides_by_mode.remove(mode_id).unwrap_or_default(); + let disabled_project = + get_disabled_mode_skills_from_document(&project_document, mode_id); + let disabled_project: HashSet = + normalize_skill_keys(disabled_project).into_iter().collect(); + let filtered = Self::filter_globally_disabled_candidates( + filter_candidates_for_mode( + candidates.clone(), + mode_id, + &user_overrides, + &disabled_project, + ), &globally_disabled_user_skills, - ), - diagnostics: scan.diagnostics, + ); + let resolved = resolve_visible_skills(filtered); + + reports.insert( + mode_id.clone(), + SkillScanReport { + skills: build_mode_skill_infos( + all_skills.clone(), + resolved, + mode_id, + &user_overrides, + &disabled_project, + &globally_disabled_user_skills, + ), + diagnostics: scan.diagnostics.clone(), + }, + ); } + reports } pub async fn get_mode_skill_infos_for_remote_workspace( @@ -1914,37 +1947,71 @@ impl SkillRegistry { remote_root: &str, mode_id: &str, ) -> SkillScanReport { + self.get_mode_skill_scan_reports_for_remote_workspace( + fs, + remote_root, + &[mode_id.to_owned()], + ) + .await + .remove(mode_id) + .expect("The requested mode is included in the scan") + } + + pub async fn get_mode_skill_scan_reports_for_remote_workspace( + &self, + fs: &dyn WorkspaceFileSystem, + remote_root: &str, + mode_ids: &[String], + ) -> HashMap> { let scan = self .scan_skill_candidates_with_diagnostics_for_remote_workspace(fs, remote_root) .await; let candidates = scan.candidates; let all_skills = sort_skills(annotate_shadowed_skills(candidates.clone())); - let user_overrides = load_user_mode_skill_overrides(mode_id) + let globally_disabled_user_skills = Self::globally_disabled_skill_keys(None).await; + let mut user_overrides_by_mode = load_user_mode_skill_overrides_batch(mode_ids) .await - .unwrap_or_else(|_| UserModeSkillOverrides::default()); - let disabled_project = load_disabled_mode_skills_remote(fs, remote_root, mode_id) + .unwrap_or_default(); + let project_document = load_project_mode_skills_document_remote(fs, remote_root) .await .unwrap_or_default(); - let disabled_project: HashSet = - normalize_skill_keys(disabled_project).into_iter().collect(); - let globally_disabled_user_skills = Self::globally_disabled_skill_keys(None).await; - let filtered = Self::filter_globally_disabled_candidates( - filter_candidates_for_mode(candidates, mode_id, &user_overrides, &disabled_project), - &globally_disabled_user_skills, - ); - let resolved = resolve_visible_skills(filtered); - - SkillScanReport { - skills: build_mode_skill_infos( - all_skills, - resolved, - mode_id, - &user_overrides, - &disabled_project, + let mut reports = HashMap::new(); + for mode_id in mode_ids { + if reports.contains_key(mode_id) { + continue; + } + let user_overrides = user_overrides_by_mode.remove(mode_id).unwrap_or_default(); + let disabled_project = + get_disabled_mode_skills_from_document(&project_document, mode_id); + let disabled_project: HashSet = + normalize_skill_keys(disabled_project).into_iter().collect(); + let filtered = Self::filter_globally_disabled_candidates( + filter_candidates_for_mode( + candidates.clone(), + mode_id, + &user_overrides, + &disabled_project, + ), &globally_disabled_user_skills, - ), - diagnostics: scan.diagnostics, + ); + let resolved = resolve_visible_skills(filtered); + + reports.insert( + mode_id.clone(), + SkillScanReport { + skills: build_mode_skill_infos( + all_skills.clone(), + resolved, + mode_id, + &user_overrides, + &disabled_project, + &globally_disabled_user_skills, + ), + diagnostics: scan.diagnostics.clone(), + }, + ); } + reports } pub async fn find_skill_by_key_for_workspace( @@ -2547,6 +2614,7 @@ mod remote_scan_tests { installation_lock: Option, pi_settings: Option, claude_hooks: bool, + mode_profiles: Option, } impl DelayedFs { @@ -2566,6 +2634,12 @@ mod remote_scan_tests { } async fn read_file_text(&self, path: &str) -> anyhow::Result { self.round_trip().await; + if path.ends_with("/agent_profiles.json") { + return self + .mode_profiles + .clone() + .ok_or_else(|| anyhow::anyhow!("missing profiles")); + } if path.ends_with("/.pi/settings.json") { assert_eq!(path, "/remote/project/.pi/settings.json"); return self @@ -2597,6 +2671,9 @@ mod remote_scan_tests { anyhow::bail!("read-only fixture") } async fn exists(&self, path: &str) -> anyhow::Result { + if path.ends_with("/agent_profiles.json") { + return Ok(self.mode_profiles.is_some()); + } if path.ends_with("/.pi/settings.json") { return Ok(self.pi_settings.is_some()); } @@ -2631,6 +2708,98 @@ mod remote_scan_tests { } } + #[tokio::test] + async fn batch_mode_reports_scan_remote_skills_once_and_preserve_single_mode_policy() { + let registry = SkillRegistry::new(); + let initial = registry + .get_mode_skill_scan_report_for_remote_workspace( + &DelayedFs::default(), + "/remote/project", + "Cowork", + ) + .await; + let key = initial + .skills + .iter() + .find(|skill| { + skill.skill.level == super::SkillLocation::Project && skill.effective_enabled + }) + .unwrap() + .skill + .key + .clone(); + let mut document = + crate::service::config::agent_profile_project_store::ProjectAgentProfilesDocument::new( + ); + crate::service::config::agent_profile_project_store::set_disabled_project_skills( + &mut document, + &crate::agentic::agents::resolve_mode_config_profile_id("Cowork"), + vec![key.clone()], + ); + let contents = serde_json::to_string(&document).unwrap(); + let single_fs = DelayedFs { + mode_profiles: Some(contents.clone()), + ..Default::default() + }; + let first = registry + .get_mode_skill_scan_report_for_remote_workspace( + &single_fs, + "/remote/project", + "Cowork", + ) + .await; + let single_calls = single_fs.calls.load(Ordering::SeqCst); + let batch_fs = DelayedFs { + mode_profiles: Some(contents.clone()), + ..Default::default() + }; + let reports = registry + .get_mode_skill_scan_reports_for_remote_workspace( + &batch_fs, + "/remote/project", + &["Cowork".into(), "review".into(), "Cowork".into()], + ) + .await; + assert_eq!(reports.len(), 2); + assert!( + !reports["Cowork"] + .skills + .iter() + .find(|skill| skill.skill.key == key) + .unwrap() + .effective_enabled + ); + assert!( + reports["review"] + .skills + .iter() + .find(|skill| skill.skill.key == key) + .unwrap() + .effective_enabled + ); + assert_eq!( + serde_json::to_value(&first).unwrap(), + serde_json::to_value(&reports["Cowork"]).unwrap() + ); + // Discovery and project policy are each read once for the entire batch. + assert!(batch_fs.calls.load(Ordering::SeqCst) <= single_calls); + let review_fs = DelayedFs { + mode_profiles: Some(contents), + ..Default::default() + }; + let review = registry + .get_mode_skill_scan_report_for_remote_workspace( + &review_fs, + "/remote/project", + "review", + ) + .await; + assert_eq!( + serde_json::to_value(review).unwrap(), + serde_json::to_value(&reports["review"]).unwrap() + ); + } + #[tokio::test] async fn remote_claude_scan_reports_unsupported_fields_without_loading_the_skill() { let fs = DelayedFs { diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/skills/source_cache.rs b/src/crates/assembly/core/src/agentic/tools/implementations/skills/source_cache.rs index aa3c141a1d..7ed72c85ef 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/skills/source_cache.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/skills/source_cache.rs @@ -39,12 +39,20 @@ struct CachedSnapshot { value: T, } +struct CompletedUncachedSnapshot { + generation: u64, + completion: u64, + value: T, +} + /// A lazy, single-flight snapshot that cannot publish a value observed across /// an invalidation boundary. pub(super) struct VersionedSnapshotCache { invalidator: SnapshotInvalidator, snapshot: RwLock>>, load_gate: Mutex<()>, + completed_loads: AtomicU64, + uncached_completion: RwLock>>, } impl VersionedSnapshotCache { @@ -53,6 +61,8 @@ impl VersionedSnapshotCache { invalidator: SnapshotInvalidator::new(), snapshot: RwLock::new(None), load_gate: Mutex::new(()), + completed_loads: AtomicU64::new(0), + uncached_completion: RwLock::new(None), } } @@ -69,6 +79,7 @@ impl VersionedSnapshotCache { F: FnMut() -> Fut, Fut: Future, { + let observed_completion = self.completed_loads.load(Ordering::Acquire); let mut attempts = 0usize; loop { let generation = self.invalidator.current(); @@ -81,9 +92,24 @@ impl VersionedSnapshotCache { if let Some(value) = self.value_for_generation(generation).await { return value; } + // Concurrent readers share even an unhealthy scan, including its + // diagnostics. A reader arriving after completion retries normally; + // this is not a persistent cache of a failed/partial discovery. + if let Some(completed) = self.uncached_completion.read().await.as_ref() { + if completed.generation == generation && completed.completion > observed_completion + { + return completed.value.clone(); + } + } let (value, cacheable) = load().await; if !cacheable { + let completion = self.completed_loads.fetch_add(1, Ordering::AcqRel) + 1; + *self.uncached_completion.write().await = Some(CompletedUncachedSnapshot { + generation, + completion, + value: value.clone(), + }); return value; } if self.invalidator.current() != generation { @@ -98,6 +124,8 @@ impl VersionedSnapshotCache { generation, value: value.clone(), }); + self.completed_loads.fetch_add(1, Ordering::AcqRel); + *self.uncached_completion.write().await = None; return value; } } @@ -515,6 +543,58 @@ mod tests { assert_eq!(loads.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn concurrent_uncacheable_readers_share_one_scan_but_a_later_read_retries() { + let cache = VersionedSnapshotCache::new(); + let loads = AtomicUsize::new(0); + let mut leader = Box::pin(cache.get_or_load(|| async { + loads.fetch_add(1, Ordering::SeqCst); + ("unhealthy".to_owned(), false) + })); + // Hold the load gate while every follower has observed this flight. + let gate = cache.load_gate.lock().await; + assert!( + std::future::poll_fn(|cx| std::task::Poll::Ready(std::future::Future::poll( + leader.as_mut(), + cx + ))) + .await + .is_pending() + ); + let mut followers = (0..8) + .map(|_| { + Box::pin(cache.get_or_load(|| async { + loads.fetch_add(1, Ordering::SeqCst); + ("unexpected rescan".to_owned(), false) + })) + }) + .collect::>(); + for follower in &mut followers { + assert!( + std::future::poll_fn(|cx| std::task::Poll::Ready(std::future::Future::poll( + follower.as_mut(), + cx + ))) + .await + .is_pending() + ); + } + drop(gate); + assert_eq!(leader.await, "unhealthy"); + for follower in followers { + assert_eq!(follower.await, "unhealthy"); + } + assert_eq!(loads.load(Ordering::SeqCst), 1); + let retry = cache + .get_or_load(|| async { + loads.fetch_add(1, Ordering::SeqCst); + ("repaired".to_owned(), true) + }) + .await; + assert_eq!(retry, "repaired"); + assert_eq!(loads.load(Ordering::SeqCst), 2); + } + #[tokio::test] async fn watched_semantic_source_changes_invalidate_the_cached_snapshot() { let temp = tempfile::tempdir().expect("tempdir"); diff --git a/src/web-ui/AGENTS.md b/src/web-ui/AGENTS.md index 71b6dc0634..3422df5eb9 100644 --- a/src/web-ui/AGENTS.md +++ b/src/web-ui/AGENTS.md @@ -138,6 +138,15 @@ pnpm --dir src/web-ui run test:run src/app/scenes/agents/components/CreateAgentD These DOM fixtures cover local forms and simulated Peer surface switches; they do not establish native rendering or live remote behavior. +For retained gallery refresh, empty snapshots, pagination and stale workspace/Peer reads: + +```bash +pnpm --dir src/web-ui run test:run src/app/hooks/useGallerySceneAutoRefresh.test.tsx src/app/scenes/agents/hooks/useAgentsList.test.tsx src/app/scenes/skills/hooks/useInstalledSkills.test.tsx src/app/scenes/skills/hooks/useSkillMarket.test.tsx src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx src/app/scenes/personal-overview/usePersonalOverview.test.tsx +``` + +These hook and DOM fixtures exercise background updates and simulated surface +activation; they do not establish native timing or live remote behavior. + For startup logo handoff, welcome typing, reduced motion, and interrupted startup exits: ```bash @@ -515,15 +524,20 @@ pnpm --dir src/web-ui run test:run src/infrastructure/workspace-icons/workspaceI These fixtures exercise DOM behavior and simulated device switching, not live remote hosts. -For retained scene visibility, Todos display-clock suspension and immediate return +For retained scene visibility, content render isolation, overview layout suspension, +Todos display-clock suspension and immediate return catch-up (including midnight and document visibility), run: ```bash -pnpm --dir src/web-ui run test:run src/app/scenes/SceneViewport.test.tsx src/app/scenes/todos/useTodoClock.test.tsx src/app/scenes/personal-overview/usePersonalOverview.test.tsx +pnpm --dir src/web-ui run test:run src/app/scenes/SceneViewport.test.tsx src/app/scenes/todos/useTodoClock.test.tsx src/app/scenes/personal-overview/usePersonalOverview.test.tsx src/app/scenes/personal-overview/OverviewMiniAppLogos.test.tsx ``` These local DOM fixtures do not establish native rendering or live remote behavior. The Todos display clock must not gate job subscriptions or scheduler execution. +Retained scene content may skip unchanged deck renders, but must keep its own +state/context subscriptions and receive activity/workspace changes. Suspend +overview sizing observers while inactive and remeasure on reveal; do not change +the scene host lifetime or transcript viewport ownership to save rendering work. For scene-readiness-only changes, run the SceneViewport test file alone. Readiness must follow the committed tree: a closed or Suspense-hidden tree cannot leave a ready id that reveals a newly suspended reopening. Native non-editor close/reopen diff --git a/src/web-ui/src/app/hooks/useGallerySceneAutoRefresh.test.tsx b/src/web-ui/src/app/hooks/useGallerySceneAutoRefresh.test.tsx new file mode 100644 index 0000000000..afeab93112 --- /dev/null +++ b/src/web-ui/src/app/hooks/useGallerySceneAutoRefresh.test.tsx @@ -0,0 +1,48 @@ +// @vitest-environment jsdom +import React, { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { useSceneStore } from '@/app/stores/sceneStore'; +import { useGallerySceneAutoRefresh } from './useGallerySceneAutoRefresh'; + +vi.mock('@/app/stores/sceneStore', async () => { + const { create } = await import('zustand'); + return { useSceneStore: create(() => ({ activeTabId: 'agents', navigationSequence: 0 })) }; +}); +let root: Root; +let container: HTMLDivElement; +let renders = 0; +const refresh = vi.fn(); +function Harness() { + renders++; + useGallerySceneAutoRefresh({ sceneId: 'agents', refetch: refresh }); + return null; +} +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + refresh.mockReset(); + renders = 0; + useSceneStore.setState({ activeTabId: 'agents', navigationSequence: 0 }); + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); +}); +afterEach(() => { act(() => root.unmount()); container.remove(); }); + +it('refreshes on re-entry and visible focus, without subscribing to unrelated navigation state', async () => { + await act(async () => root.render()); + expect(refresh).not.toHaveBeenCalled(); + act(() => useSceneStore.setState({ navigationSequence: 1 })); + expect(renders).toBe(1); + act(() => useSceneStore.setState({ activeTabId: 'skills' })); + const inactiveRenders = renders; + act(() => useSceneStore.setState({ activeTabId: 'miniapps' })); + expect(renders).toBe(inactiveRenders); + Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' }); + act(() => document.dispatchEvent(new Event('visibilitychange'))); + expect(refresh).not.toHaveBeenCalled(); + await act(async () => useSceneStore.setState({ activeTabId: 'agents' })); + expect(refresh).toHaveBeenCalledTimes(1); + act(() => document.dispatchEvent(new Event('visibilitychange'))); + expect(refresh).toHaveBeenCalledTimes(2); +}); diff --git a/src/web-ui/src/app/hooks/useGallerySceneAutoRefresh.ts b/src/web-ui/src/app/hooks/useGallerySceneAutoRefresh.ts index 26aff54142..9dba655203 100644 --- a/src/web-ui/src/app/hooks/useGallerySceneAutoRefresh.ts +++ b/src/web-ui/src/app/hooks/useGallerySceneAutoRefresh.ts @@ -1,6 +1,6 @@ import { useEffect, useRef } from 'react'; import type { SceneTabId } from '@/app/components/SceneBar/types'; -import { useSceneManager } from './useSceneManager'; +import { useSceneStore } from '@/app/stores/sceneStore'; export interface UseGallerySceneAutoRefreshOptions { /** Tab id from SceneBar (e.g. skills, agents, miniapps). */ @@ -23,8 +23,7 @@ export function useGallerySceneAutoRefresh({ refetch, enabled = true, }: UseGallerySceneAutoRefreshOptions): void { - const { activeTabId } = useSceneManager(); - const isActive = activeTabId === sceneId; + const isActive = useSceneStore(state => state.activeTabId === sceneId); const refetchRef = useRef(refetch); refetchRef.current = refetch; @@ -53,7 +52,7 @@ export function useGallerySceneAutoRefresh({ if (document.visibilityState !== 'visible') { return; } - if (activeTabId !== sceneId) { + if (!isActive) { return; } void Promise.resolve(refetchRef.current()); @@ -61,5 +60,5 @@ export function useGallerySceneAutoRefresh({ document.addEventListener('visibilitychange', onVisibility); return () => document.removeEventListener('visibilitychange', onVisibility); - }, [enabled, activeTabId, sceneId]); + }, [enabled, isActive]); } diff --git a/src/web-ui/src/app/scenes/SceneViewport.test.tsx b/src/web-ui/src/app/scenes/SceneViewport.test.tsx index 692ec3d1e3..4656cf57df 100644 --- a/src/web-ui/src/app/scenes/SceneViewport.test.tsx +++ b/src/web-ui/src/app/scenes/SceneViewport.test.tsx @@ -5,6 +5,8 @@ import React, { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +const sceneDataContext = React.createContext('initial'); + const sceneHarness = vi.hoisted(() => { let resolveAgents: (() => void) | null = null; let agentsAreReady = false; @@ -26,6 +28,7 @@ const sceneHarness = vi.hoisted(() => { agentsAreReady: () => agentsAreReady, resolveAgents: () => resolveAgents?.(), settingsSuspension: null as Promise | null, + settingsRender: vi.fn(), }; }); @@ -52,11 +55,14 @@ vi.mock('./session/SessionScene', () => ({ vi.mock('./settings/SettingsScene', () => ({ default: ({ isActive }: { isActive?: boolean }) => { + const data = React.useContext(sceneDataContext); + sceneHarness.settingsRender(isActive, data); if (sceneHarness.settingsSuspension) throw sceneHarness.settingsSuspension; return
; + data-scene-data={data} + >
; }, })); @@ -96,6 +102,7 @@ describe('SceneViewport transitions', () => { beforeEach(() => { sceneHarness.settingsSuspension = null; + sceneHarness.settingsRender.mockClear(); sessionPaneLayoutStore.setState(sessionPaneLayoutStore.getInitialState()); vi.useFakeTimers(); vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => ( @@ -342,4 +349,39 @@ describe('SceneViewport transitions', () => { expect(settingsContent?.getAttribute('data-scene-prop-active')).toBe('true'); }); + it('retains inactive scene state without rendering it for unrelated navigation', async () => { + sceneHarness.state.openTabs.push({ id: 'settings', lastUsed: 1 }, { id: 'assistant', lastUsed: 2 }); + await act(async () => { root.render(); await Promise.resolve(); }); + const content = container.querySelector('[data-testid="settings-scene-content"]'); + const input = content!.querySelector('input')!; + input.value = 'Unsaved settings draft'; + sceneHarness.settingsRender.mockClear(); + + for (const id of ['assistant', 'session', 'assistant']) { + sceneHarness.state = { ...sceneHarness.state, activeTabId: id, navigationSequence: sceneHarness.state.navigationSequence + 1 }; + act(() => root.render()); + } + expect(sceneHarness.settingsRender).not.toHaveBeenCalled(); + expect(container.querySelector('[data-testid="settings-scene-content"]')).toBe(content); + expect(input.value).toBe('Unsaved settings draft'); + + sceneHarness.state = { ...sceneHarness.state, activeTabId: 'settings', navigationSequence: 4 }; + act(() => root.render()); + expect(sceneHarness.settingsRender).toHaveBeenCalledWith(true, 'initial'); + expect(container.querySelector('[data-testid="settings-scene-content"]')).toBe(content); + expect(input.value).toBe('Unsaved settings draft'); + }); + + it('delivers context updates to an inactive retained scene', () => { + sceneHarness.state.openTabs.push({ id: 'settings', lastUsed: 1 }); + act(() => root.render()); + const content = container.querySelector('[data-testid="settings-scene-content"]'); + sceneHarness.settingsRender.mockClear(); + + act(() => root.render()); + expect(sceneHarness.settingsRender).toHaveBeenCalledWith(false, 'after'); + expect(container.querySelector('[data-testid="settings-scene-content"]')).toBe(content); + expect(content?.getAttribute('data-scene-data')).toBe('after'); + }); + }); diff --git a/src/web-ui/src/app/scenes/SceneViewport.tsx b/src/web-ui/src/app/scenes/SceneViewport.tsx index e8543e1243..e5258b577d 100644 --- a/src/web-ui/src/app/scenes/SceneViewport.tsx +++ b/src/web-ui/src/app/scenes/SceneViewport.tsx @@ -135,6 +135,21 @@ interface SceneViewportProps { paned?: boolean; } +interface SceneContentProps { + sceneId: SceneTabId; + workspacePath?: string; + isEntering?: boolean; + isActive: boolean; +} + +// Keep retained scenes subscribed to their own data/context, without rendering +// every open scene again for each navigation and transition phase in the deck. +const SceneContent = React.memo(function SceneContent({ + sceneId, workspacePath, isEntering, isActive, +}: SceneContentProps) { + return renderScene(sceneId, workspacePath, isEntering, isActive); +}); + const SceneViewport: React.FC = ({ workspacePath, isEntering = false, paned = false }) => { const { openTabs, @@ -258,7 +273,7 @@ const SceneViewport: React.FC = ({ workspacePath, isEntering } > - {renderScene(tabId, workspacePath, isEntering, isActive)} + )} diff --git a/src/web-ui/src/app/scenes/agents/AgentsScene.test.tsx b/src/web-ui/src/app/scenes/agents/AgentsScene.test.tsx index 0c3ed4e910..cf0e8e92a5 100644 --- a/src/web-ui/src/app/scenes/agents/AgentsScene.test.tsx +++ b/src/web-ui/src/app/scenes/agents/AgentsScene.test.tsx @@ -113,7 +113,7 @@ vi.mock('@/app/components/GalleryLayout', () => ({ })); vi.mock('./hooks/useAgentsList', () => ({ - useAgentsList: () => useAgentsListMock(), + useAgentsList: (options: unknown) => useAgentsListMock(options), })); function mockAgentsList(overrides: Record = {}) { @@ -125,6 +125,8 @@ function mockAgentsList(overrides: Record = {}) { availableTools: [], toolCatalogStatus: 'available', getModeProfile: () => null, + getAgentSkillCount: (id: string) => ((overrides.getAgentSkills as ((id: string) => { effectiveEnabled: boolean }[]) | undefined)?.(id) ?? []).filter(skill => skill.effectiveEnabled).length, + getAgentSubagentCount: (id: string) => ((overrides.allAgents as {id: string;visibleSubagentCount?: number}[] | undefined)?.find(agent => agent.id === id)?.visibleSubagentCount ?? 0), getAgentSkills: () => [], getModeManageableSubagents: () => [], counts: { builtin: 0, user: 0, project: 0, mode: 0, subagent: 0 }, @@ -197,7 +199,7 @@ describeWithJsdom('AgentsScene', () => { let container: HTMLDivElement; let root: Root; - beforeEach(() => { + beforeEach(async () => { dom = new JSDOMCtor!('', { pretendToBeVisual: true, url: 'http://localhost', @@ -229,7 +231,10 @@ describeWithJsdom('AgentsScene', () => { container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container); - }); + // Transform the scene after DOM setup, outside the interaction deadline. + // A cold module import must not outlive a test and mutate the next DOM. + await import('./AgentsScene'); + }, 60000); afterEach(() => { act(() => { @@ -375,6 +380,7 @@ describeWithJsdom('AgentsScene', () => { }); expect(document.querySelector('[data-testid="agent-detail-panel"]')).toBeNull(); expect(preview.dataset.detailView).toBe('transitioning'); + expect(useAgentsListMock).toHaveBeenLastCalledWith(expect.objectContaining({ selectedAgentId: 'Standard' })); expect(preview.dataset.state).toBe('open'); expect(document.querySelectorAll('[data-openbitfun-component="dialog"][data-openbitfun-part="overlay"]')).toHaveLength(1); await act(async () => { await new Promise(resolve => setTimeout(resolve, 220)); }); diff --git a/src/web-ui/src/app/scenes/agents/AgentsScene.tsx b/src/web-ui/src/app/scenes/agents/AgentsScene.tsx index 30d0685884..7ff5807c51 100644 --- a/src/web-ui/src/app/scenes/agents/AgentsScene.tsx +++ b/src/web-ui/src/app/scenes/agents/AgentsScene.tsx @@ -208,12 +208,17 @@ const AgentsHomeView: React.FC = () => { } = useUserSkillGroups(); const { + catalogContextKey, workspaceId, allAgents, filteredAgents, loading, + countsLoading = false, catalogError, countsError, + detailsLoading = false, detailsLoaded = true, detailsError, loadAgentDetails, + getAgentSkillCount, getAgentSubagentCount, availableTools, toolCatalogStatus, + modelCatalogReady = true, configuredModels = [], modelPools = [], getModeProfile, @@ -229,6 +234,8 @@ const AgentsHomeView: React.FC = () => { handleSetSubagentEnabled, handleSetSubagentModel, } = useAgentsList({ + // Start explicit management reads during the retained size transition. + selectedAgentId: detailView !== 'preview' ? selectedAgentId : null, searchQuery, filterLevel: agentFilterLevel, filterType: agentFilterType, @@ -249,9 +256,8 @@ const AgentsHomeView: React.FC = () => { useGallerySceneAutoRefresh({ sceneId: 'agents', - refetch: () => { - void loadAgents(); - void reloadSkillGroups(); + refetch: async () => { + await Promise.all([loadAgents({ background: true }), reloadSkillGroups()]); }, }); @@ -397,21 +403,21 @@ const AgentsHomeView: React.FC = () => { } return agent.toolCount ?? 0; }, [getModeConfig]); - const getDisplayedSkillCount = useCallback((agent: AgentWithCapabilities): number => { + const getDisplayedSkillCount = useCallback((agent: AgentWithCapabilities): number | null => { const configuredTools = isPrimaryAgent(agent) ? (getModeConfig(agent.id)?.enabled_tools ?? agent.defaultTools ?? []) : (agent.defaultTools ?? []); return hasSkillTool(configuredTools) - ? getConfiguredEnabledSkillKeys(getAgentSkills(agent.id)).length + ? getAgentSkillCount(agent.id) : 0; - }, [getAgentSkills, getModeConfig]); - const getDisplayedSubagentCount = useCallback((agent: AgentWithCapabilities): number => { + }, [getAgentSkillCount, getModeConfig]); + const getDisplayedSubagentCount = useCallback((agent: AgentWithCapabilities): number | null => { if (!isPrimaryAgent(agent)) { return 0; } const configuredTools = getModeConfig(agent.id)?.enabled_tools ?? agent.defaultTools ?? []; - return hasAgentCollaborationTool(configuredTools) ? (agent.visibleSubagentCount ?? 0) : 0; - }, [getModeConfig]); + return hasAgentCollaborationTool(configuredTools) ? getAgentSubagentCount(agent.id) : 0; + }, [getAgentSubagentCount, getModeConfig]); const selectedAgentSourceLabel = selectedAgent ? subagentSourceLabel(selectedAgent.source ?? selectedAgent.subagentSource, t) : ''; @@ -597,6 +603,10 @@ const AgentsHomeView: React.FC = () => { resetEditState(); }, [resetEditState]); + // Detail drafts belong to their device/workspace. Same-owner navigation and + // background reads keep them mounted; changing the owner fences old writes. + useEffect(() => closeAgentDetails(), [catalogContextKey, closeAgentDetails]); + const openCapabilitySection = (section: CapabilitySection) => { captureDetailSize(); lastCapabilityEntry.current = section; @@ -905,6 +915,7 @@ const AgentsHomeView: React.FC = () => { + {catalogError || countsError ?
{catalogError ?? countsError}
: null} {loading ? renderSkeletons('agent') : null} {!loading && catalogAgents.length === 0 ? ( @@ -927,6 +938,7 @@ const AgentsHomeView: React.FC = () => { toolCount: getDisplayedToolCount(agent), skillCount: getDisplayedSkillCount(agent), subagentCount: getDisplayedSubagentCount(agent), + countsLoading, onOpenDetails: openAgentDetails, disabledReason: agent.id === 'ComputerUse' && !computerUseEnabled ? t('coreAgentsZone.computerUseDisabledBadge') @@ -1082,8 +1094,12 @@ const AgentsHomeView: React.FC = () => { aria-label={activeDetailSection === 'basic' ? t('agentsOverview.detail.overview') : undefined} aria-labelledby={activeDetailSection !== 'basic' ? `${detailId}-section-title` : undefined} data-detail-page={activeDetailSection} + data-agent-detail-loading={detailsLoading || undefined} + aria-busy={detailsLoading || undefined} > -
+ {detailsLoading ?
{t('agentsOverview.form.loadingDetail')}
: null} + {detailsError ?
{detailsError}
: null} + {detailsLoaded ?
{activeDetailSection === 'basic' ? (
@@ -1136,7 +1152,7 @@ const AgentsHomeView: React.FC = () => { options={visibleSubagentModelOptions} value={selectedSubagentModelValue} onValueChange={(value) => void handleSubagentModelChange(value)} - disabled={savingSubagentModel} + disabled={savingSubagentModel || !modelCatalogReady} data-testid="agent-detail-subagent-model-select" /> @@ -1289,7 +1305,7 @@ const AgentsHomeView: React.FC = () => {
) ) : null} -
+
: null} {currentCapabilityMeta && canManageCurrentCapability && isCurrentSectionEditing ? ( diff --git a/src/web-ui/src/app/scenes/agents/components/AgentCard.tsx b/src/web-ui/src/app/scenes/agents/components/AgentCard.tsx index a05bf413e7..dc729c34d6 100644 --- a/src/web-ui/src/app/scenes/agents/components/AgentCard.tsx +++ b/src/web-ui/src/app/scenes/agents/components/AgentCard.tsx @@ -9,8 +9,9 @@ import './AgentCatalogCard.scss'; interface AgentCardProps { agent: AgentWithCapabilities; toolCount?: number; - skillCount?: number; - subagentCount?: number; + skillCount?: number | null; + subagentCount?: number | null; + countsLoading?: boolean; disabledReason?: string; onOpenDetails: (agent: AgentWithCapabilities) => void; } diff --git a/src/web-ui/src/app/scenes/agents/components/AgentCatalogCard.tsx b/src/web-ui/src/app/scenes/agents/components/AgentCatalogCard.tsx index 78357e28ee..b4876df5ef 100644 --- a/src/web-ui/src/app/scenes/agents/components/AgentCatalogCard.tsx +++ b/src/web-ui/src/app/scenes/agents/components/AgentCatalogCard.tsx @@ -45,8 +45,9 @@ const AgentCatalogCard: React.FC = ({ agent, onOpenDetail export interface AgentCatalogMetricsProps extends React.HTMLAttributes { agent: AgentWithCapabilities; toolCount?: number; - skillCount?: number; - subagentCount?: number; + skillCount?: number | null; + subagentCount?: number | null; + countsLoading?: boolean; } export const AgentCatalogMetrics: React.FC = ({ @@ -54,6 +55,7 @@ export const AgentCatalogMetrics: React.FC = ({ toolCount, skillCount = 0, subagentCount = 0, + countsLoading = false, ...props }) => { const { t } = useI18n('scenes/agents'); @@ -66,10 +68,10 @@ export const AgentCatalogMetrics: React.FC = ({ ]; return ( -
+
{metrics.map(({ key, label, value }) => ( - {value} + {value ?? (countsLoading ? "…" : "β€”")} {label} ))} diff --git a/src/web-ui/src/app/scenes/agents/components/CoreAgentCard.tsx b/src/web-ui/src/app/scenes/agents/components/CoreAgentCard.tsx index 6250634fa1..d8c984fe36 100644 --- a/src/web-ui/src/app/scenes/agents/components/CoreAgentCard.tsx +++ b/src/web-ui/src/app/scenes/agents/components/CoreAgentCard.tsx @@ -9,8 +9,9 @@ import './AgentCatalogCard.scss'; interface CoreAgentCardProps { agent: AgentWithCapabilities; toolCount?: number; - skillCount?: number; - subagentCount?: number; + skillCount?: number | null; + subagentCount?: number | null; + countsLoading?: boolean; onOpenDetails: (agent: AgentWithCapabilities) => void; /** Replaces the connected status when the capability is off in Settings. */ disabledReason?: string; diff --git a/src/web-ui/src/app/scenes/agents/hooks/useAgentsList.test.tsx b/src/web-ui/src/app/scenes/agents/hooks/useAgentsList.test.tsx new file mode 100644 index 0000000000..97a59cd3f2 --- /dev/null +++ b/src/web-ui/src/app/scenes/agents/hooks/useAgentsList.test.tsx @@ -0,0 +1,191 @@ +// @vitest-environment jsdom +import React, { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { TFunction } from 'i18next'; +import { useAgentsList } from './useAgentsList'; +import { activateSurface, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; + +const mocks = vi.hoisted(() => ({ + workspace: { id: 'workspace-a' }, + peer: { peerMode: { active: false, deviceId: 'peer-a' }, currentPeerCapabilities: null }, + modes: vi.fn(), pools: vi.fn(), counts: vi.fn(), skills: vi.fn(), tools: vi.fn(), manageable: vi.fn(), selected: null as string | null, + t: (key: string) => key, +})); +vi.mock('@/infrastructure/config/services/modelSelections', () => ({ + modelSelectionsConfigPath: () => 'ai.agent_model_selections', + effectiveModelSelections: () => ({ subagents: { builtin: {} } }), +})); +vi.mock('@/infrastructure/config/services/ConfigManager', () => ({ configManager: {} })); +vi.mock('@/infrastructure/api/service-api/ModelPoolAPI', () => ({ + modelPoolAPI: { list: mocks.pools }, readableModelPools: () => [], supportsModelPools: () => true, +})); +vi.mock('@/infrastructure/api/service-api/AgentAPI', () => ({ agentAPI: { getAvailableModes: mocks.modes } })); +vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ api: { invoke: mocks.tools } })); +vi.mock('@/infrastructure/api/service-api/SubagentAPI', () => ({ + SubagentAPI: { listSubagents: async () => [], listManageableSubagents: mocks.manageable }, +})); +vi.mock('@/infrastructure/api/service-api/ConfigAPI', () => ({ configAPI: { + getAgentProfileConfigs: async () => ({}), getConfigs: async () => ({}), getModeSkillConfigs: mocks.skills, getModeSkillCounts: mocks.counts, +} })); +vi.mock('@/infrastructure/contexts/WorkspaceContext', () => ({ + useCurrentWorkspace: () => ({ workspace: mocks.workspace, workspacePath: '/project' }), +})); +vi.mock('@/infrastructure/peer-device/peerDeviceContextState', () => ({ usePeerDeviceModeOptional: () => mocks.peer })); +vi.mock('@/infrastructure/peer-device/peerCapabilityResolution', () => ({ canQueryToolCatalogOnSurface: () => true })); +vi.mock('@/shared/services/reviewTeamService', () => ({ loadDefaultReviewTeamDefinition: async () => undefined })); +vi.mock('@/shared/notification-system', () => ({ useNotification: () => ({}) })); +vi.mock('@/infrastructure/event-bus', () => ({ globalEventBus: { on: vi.fn(), off: vi.fn() } })); +vi.mock('@/shared/agents/identity', () => ({ primaryAgentKind: () => 'agent', agentName: (mode: { name: string }) => mode.name })); +vi.mock('../utils', () => ({ enrichCapabilities: (agent: unknown) => agent })); + +const mode = { id: 'review', name: 'Review', description: 'Review code', configProfileId: 'review', defaultTools: [] }; +let current: ReturnType; +let root: Root; +let container: HTMLDivElement; +function Harness() { + current = useAgentsList({ selectedAgentId: mocks.selected, searchQuery: '', filterLevel: 'all', filterType: 'all', t: mocks.t as TFunction<'scenes/agents'> }); + return {current.loading ? 'loading' : 'ready'}; +} +beforeEach(() => { + resetDeviceSurfaceForTest(); + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + mocks.selected = null; + mocks.counts.mockReset().mockResolvedValue({ review: 2 }); + mocks.skills.mockReset().mockResolvedValue([]); + mocks.tools.mockReset().mockResolvedValue([]); + mocks.manageable.mockReset().mockResolvedValue([]); + mocks.workspace.id = 'workspace-a'; + mocks.peer.peerMode.active = false; + mocks.peer.peerMode.deviceId = 'peer-a'; + mocks.modes.mockReset().mockResolvedValue([mode]); + mocks.pools.mockReset().mockResolvedValue(undefined); + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); +}); +afterEach(() => { + act(() => root.unmount()); + container.remove(); + resetDeviceSurfaceForTest(); +}); + +describe('retained agent catalog refresh', () => { + it.each([{ entries: [mode] }, { entries: [] }])('keeps a loaded catalog visible until the background result arrives: $entries.length entries', async ({ entries }) => { + mocks.modes.mockResolvedValueOnce(entries); + await act(async () => root.render()); + const previous = current.allAgents; + let finish!: (modes: typeof entries) => void; + mocks.modes.mockReturnValueOnce(new Promise(resolve => { finish = resolve; })); + let refresh!: Promise; + await act(async () => { refresh = current.loadAgents({ background: true }); }); + expect(current.loading).toBe(false); + expect(current.allAgents).toBe(previous); + await act(async () => { finish([{ ...mode, name: 'Updated' }]); await refresh; }); + expect(current.allAgents[0].name).toBe('Updated'); + }); + + it.each(['workspace', 'peer'] as const)('does not reuse a background snapshot after a %s switch', async (owner) => { + await act(async () => root.render()); + let finishOld!: (modes: typeof mode[]) => void; + mocks.modes.mockReturnValueOnce(new Promise(resolve => { finishOld = resolve; })); + let oldRefresh!: Promise; + await act(async () => { oldRefresh = current.loadAgents({ background: true }); }); + let finishNew!: (modes: typeof mode[]) => void; + mocks.modes.mockReturnValue(new Promise(resolve => { finishNew = resolve; })); + if (owner === 'workspace') mocks.workspace.id = 'workspace-b'; + else { mocks.peer.peerMode.active = true; mocks.peer.peerMode.deviceId = 'peer-b'; } + await act(async () => root.render()); + await act(async () => { void current.loadAgents({ background: true }); }); + expect(current.loading).toBe(true); + await act(async () => { finishOld([{ ...mode, name: 'Stale' }]); await oldRefresh; }); + expect(current.loading).toBe(true); + expect(current.allAgents.some(agent => agent.name === 'Stale')).toBe(false); + await act(async () => { finishNew([{ ...mode, name: 'Current' }]); }); + expect(current.loading).toBe(false); + expect(current.allAgents[0].name).toBe('Current'); + }); + + it('requires a fresh load after an A β†’ B β†’ A activation with unchanged workspace and peer context', async () => { + await act(async () => root.render()); + mocks.modes.mockReturnValue(new Promise(() => {})); + await act(async () => { activateSurface('peer-b'); activateSurface('local'); }); + await act(async () => { void current.loadAgents({ background: true }); }); + expect(current.loading).toBe(true); + }); +}); + + +describe('progressive Agent catalog', () => { + it('discards an older detail read after catalog refresh and keeps loaded details mounted while retrying', async () => { + mocks.selected = 'review'; + mocks.modes.mockResolvedValue([{ ...mode, defaultTools: ['Skill'], manageableSubagentCount: 0 }]); + let finishOld!: (skills: { key: string; effectiveEnabled: boolean }[]) => void; + mocks.skills.mockReturnValueOnce(new Promise(resolve => { finishOld = resolve; })) + .mockResolvedValue([{ key: 'current', effectiveEnabled: true }]); + await act(async () => root.render()); + expect(current.detailsLoading).toBe(true); + await act(async () => { await current.loadAgents({ background: true, force: true }); }); + expect(current.detailsLoaded).toBe(true); + expect(current.getAgentSkills('review')[0].key).toBe('current'); + await act(async () => { finishOld([{ key: 'stale', effectiveEnabled: false }]); }); + expect(current.getAgentSkills('review')[0].key).toBe('current'); + let retry!: (skills: { key: string; effectiveEnabled: boolean }[]) => void; + mocks.skills.mockReturnValueOnce(new Promise(resolve => { retry = resolve; })); + let pending!: Promise; + await act(async () => { pending = current.loadAgentDetails('review', true); }); + expect(current.detailsLoading).toBe(false); + expect(current.detailsLoaded).toBe(true); + await act(async () => { retry([{ key: 'refreshed', effectiveEnabled: true }]); await pending; }); + expect(current.getAgentSkills('review')[0].key).toBe('refreshed'); + }); + + it('renders the catalog before summaries and only loads complete capabilities on detail open', async () => { + let finish!: (counts: Record) => void; + mocks.counts.mockReturnValue(new Promise(resolve => { finish = resolve; })); + mocks.modes.mockResolvedValue([{ ...mode, defaultTools: ['Skill', 'AgentSpawn'], manageableSubagentCount: 3 }]); + await act(async () => root.render()); + expect(current.loading).toBe(false); + expect(current.allAgents).toHaveLength(1); + expect(current.countsLoading).toBe(true); + expect(current.getAgentSkillCount('review')).toBe(null); + expect(current.getAgentSubagentCount('review')).toBe(3); + expect(mocks.skills).not.toHaveBeenCalled(); + expect(mocks.tools).not.toHaveBeenCalled(); + expect(mocks.manageable).not.toHaveBeenCalled(); + mocks.selected = 'review'; + await act(async () => root.render()); + expect(current.detailsLoaded).toBe(true); + expect(mocks.skills).toHaveBeenCalledTimes(1); + expect(mocks.tools).toHaveBeenCalledTimes(1); + expect(mocks.manageable).toHaveBeenCalledTimes(1); + await act(async () => { finish({ review: 2 }); }); + expect(current.getAgentSkillCount('review')).toBe(2); + }); + + it('coalesces concurrent catalog reloads and language-only rendering', async () => { + let finish!: (modes: typeof mode[]) => void; + mocks.modes.mockReturnValue(new Promise(resolve => { finish = resolve; })); + await act(async () => root.render()); + await act(async () => { void current.loadAgents({ background: true }); void current.loadAgents(); }); + expect(mocks.modes).toHaveBeenCalledTimes(1); + await act(async () => { finish([mode]); }); + const oldTranslate = mocks.t; + mocks.t = key => key + '-translated'; + await act(async () => root.render()); + expect(mocks.modes).toHaveBeenCalledTimes(1); + mocks.t = oldTranslate; + }); + + it('keeps the list usable and reports a summary failure for retry', async () => { + mocks.counts.mockRejectedValue(new Error('offline summary')); + await act(async () => root.render()); + expect(current.loading).toBe(false); + expect(current.allAgents).toHaveLength(1); + expect(current.countsError).toContain('offline summary'); + mocks.counts.mockResolvedValue({ review: 4 }); + await act(async () => { await current.loadAgents({ background: true, force: true }); }); + expect(current.countsError).toBe(null); + expect(current.getAgentSkillCount('review')).toBe(4); + }); +}); diff --git a/src/web-ui/src/app/scenes/agents/hooks/useAgentsList.ts b/src/web-ui/src/app/scenes/agents/hooks/useAgentsList.ts index 7ef87b5581..63233b3e2d 100644 --- a/src/web-ui/src/app/scenes/agents/hooks/useAgentsList.ts +++ b/src/web-ui/src/app/scenes/agents/hooks/useAgentsList.ts @@ -3,7 +3,7 @@ import { configManager } from '@/infrastructure/config/services/ConfigManager'; import { modelPoolAPI, readableModelPools, supportsModelPools, type ModelPoolDefinition } from '@/infrastructure/api/service-api/ModelPoolAPI'; import { primaryAgentKind, agentName } from '@/shared/agents/identity'; import { isPrimaryAgent, isOrdinaryAgent } from '../agentVisibility'; -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import type { TFunction } from 'i18next'; import { agentAPI, type ModeInfo } from '@/infrastructure/api/service-api/AgentAPI'; import { api } from '@/infrastructure/api/service-api/ApiClient'; @@ -30,6 +30,7 @@ import { isRemoteWorkspace } from '@/shared/types'; import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState'; import { canQueryToolCatalogOnSurface } from '@/infrastructure/peer-device/peerCapabilityResolution'; import { createLogger } from '@/shared/utils/logger'; +import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; const toolLog = createLogger('useAgentsList'); @@ -43,6 +44,7 @@ export type FilterType = 'all' | 'agent' | 'subagent'; * empty list. See PR #2428 #5. */ export type ToolCatalogStatus = + | 'loading' | 'available' | 'unsupported' | 'failed' @@ -61,6 +63,7 @@ interface ToolCatalogLoadResult { } interface UseAgentsListOptions { + selectedAgentId?: string | null; searchQuery: string; filterLevel: FilterLevel; filterType: FilterType; @@ -187,6 +190,7 @@ function subagentModelDisplayName( export function useAgentsList({ searchQuery, + selectedAgentId = null, filterLevel, filterType, t, @@ -194,6 +198,7 @@ export function useAgentsList({ const notification = useNotification(); const { workspace, workspacePath } = useCurrentWorkspace(); const peerDevice = usePeerDeviceModeOptional(); + const scope = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope); // Identity of the rendered surface: null on the controller, otherwise the // peer device id. Part of the catalog-load deps so Aβ†’B (same workspacePath, // same capability) still reloads β€” otherwise the UI keeps A's catalog while @@ -216,175 +221,228 @@ export function useAgentsList({ const [allAgents, setAllAgents] = useState([]); const [loading, setLoading] = useState(true); const [availableTools, setAvailableTools] = useState([]); - const [toolCatalogStatus, setToolCatalogStatus] = useState('available'); + const [toolCatalogStatus, setToolCatalogStatus] = useState('loading'); + const [modelCatalogReady, setModelCatalogReady] = useState(false); const [modelPools, setModelPools] = useState([]); const [configuredModels, setConfiguredModels] = useState([]); const [modeProfiles, setModeProfiles] = useState>({}); const [agentSkills, setAgentSkills] = useState>({}); + const [skillCounts, setSkillCounts] = useState>({}); + const [subagentCounts, setSubagentCounts] = useState>({}); + const [countsLoading, setCountsLoading] = useState(true); + const [catalogError, setCatalogError] = useState(null); + const [countsError, setCountsError] = useState(null); const [modeConfigs, setModeConfigs] = useState>({}); const [modeManageableSubagents, setModeManageableSubagents] = useState>({}); - const [hiddenAgentIds, setHiddenAgentIds] = useState>( - () => new Set(HIDDEN_AGENT_IDS), - ); + const [hiddenAgentIds, setHiddenAgentIds] = useState>(() => new Set(HIDDEN_AGENT_IDS)); + const [, setDetailRevision] = useState(0); const loadRequestIdRef = useRef(0); - - const loadAgents = useCallback(async () => { - const requestId = ++loadRequestIdRef.current; - setLoading(true); - // `renderedPeerDeviceId` is read here so a surface switch (Aβ†’B) recreates - // this callback even when canQueryToolCatalog/workspacePath are unchanged; - // the requestId guard then drops the previous surface's in-flight result. - // See PR #2428 #3. - const surfaceTag = renderedPeerDeviceId ?? 'controller'; - - const fetchTools = async (): Promise => { - if (!canQueryToolCatalog) { - toolLog.info('Tool catalog unsupported on the current peer host; leaving the list empty', { surface: surfaceTag }); - return { tools: [], status: 'unsupported' }; - } - try { - const tools = await api.invoke('get_all_tools_info'); - return { - tools, - status: tools.length > 0 ? 'available' : 'empty', - }; - } catch (error) { - toolLog.error('Failed to load tool catalog', { error }); - return { tools: [], status: 'failed' }; - } + const catalogContextKey = scope.key(scope.epoch, renderedPeerDeviceId, workspace?.id, String(canQueryToolCatalog)); + const loadedContextKeyRef = useRef(null); + const translateRef = useRef(t); + translateRef.current = t; + const selectedIdRef = useRef(selectedAgentId); + selectedIdRef.current = selectedAgentId; + const catalogRef = useRef<{ + key: string; modes: ModeInfo[]; subagents: SubagentInfo[]; + profiles: Record; + configs: Record; + } | null>(null); + const catalogFlight = useRef<{ key: string; promise: Promise } | null>(null); + const toolsFlight = useRef<{ key: string; promise: Promise } | null>(null); + const details = useRef(new Map; error?: string; generation: number }>()); + const detailLoaderRef = useRef<(id: string, force?: boolean) => Promise>(async () => {}); + + const loadAgentDetails = useCallback((agentId: string, force = false): Promise => { + const catalog = catalogRef.current; + if (!catalog || catalog.key !== catalogContextKey || !scope.isCurrent()) return Promise.resolve(); + const mode = catalog.modes.find(item => item.id === agentId); + const subagent = catalog.subagents.find(item => item.id === agentId); + if (!mode && !subagent) return Promise.resolve(); + const profile = mode ? catalog.profiles[modeProfileIdFor(mode)] : undefined; + const profileId = profile?.profileId ?? agentId; + const targetId = profile?.representativeModeId ?? agentId; + const key = `${catalogContextKey}:${profileId}`; + const previous = details.current.get(key); + if (previous?.pending) return previous.pending; + if (previous?.loaded && !force) return Promise.resolve(); + const entry = { loaded: previous?.loaded ?? false, generation: (previous?.generation ?? 0) + 1 } as { + loaded: boolean; generation: number; pending?: Promise; error?: string; }; - - try { - const [modes, subagents, toolCatalog, configs, reviewTeamDefinition, modelConfigs, poolDocument] = await Promise.all([ - agentAPI.getAvailableModes({ workspaceId: workspace?.id }).catch(() => []), - SubagentAPI.listSubagents({ workspaceId: workspace?.id }).catch(() => []), - fetchTools(), - configAPI.getAgentProfileConfigs().catch(() => ({})), - loadDefaultReviewTeamDefinition().catch(() => undefined), - configAPI.getConfigs([ - 'ai.models', - 'ai.default_models', - modelSelectionsConfigPath(), - ]).catch((): Record => ({})), - supportsModelPools() ? modelPoolAPI.list() : Promise.resolve(undefined), - ]); - - const profileMap = buildProfileMap(modes); - const profileEntries = Object.values(profileMap); - - const skillTargets = [ - ...profileEntries.map((profile) => ({ - cacheKey: profile.profileId, - agentId: profile.representativeModeId, - })), - ...subagents - .filter((subagent) => subagent.defaultTools.includes('Skill')) - .map((subagent) => ({ - cacheKey: subagent.id, - agentId: subagent.id, - })), - ]; - const skillEntries = await Promise.all( - skillTargets.map(async ({ cacheKey, agentId }) => [ - cacheKey, - await configAPI.getModeSkillConfigs({ - modeId: agentId, - workspaceId: workspace?.id, - }).catch(() => []), - ] as const), - ); - const manageableSubagentEntries = await Promise.all( - profileEntries.map(async (profile) => [ - profile.profileId, - await SubagentAPI.listManageableSubagents({ - parentAgentType: profile.representativeModeId, - workspaceId: workspace?.id, - }).catch(() => []), - ] as const), - ); - - if (requestId !== loadRequestIdRef.current) { - return; - } - - const manageableSubagentsByProfile = Object.fromEntries(manageableSubagentEntries); - const models = (modelConfigs['ai.models'] as AIModelConfig[] | undefined) ?? []; - const defaultModels = ( - modelConfigs['ai.default_models'] as DefaultModelsConfig | undefined - ) ?? {}; - const builtinOverrides = effectiveModelSelections(modelConfigs[modelSelectionsConfigPath()] as AgentModelDefaultsConfig | undefined).subagents.builtin; - const pools = poolDocument ? readableModelPools(poolDocument) : []; - setModelPools(pools); - - const modeAgents: AgentWithCapabilities[] = modes.map((mode) => - enrichCapabilities({ - key: `mode::${mode.id}`, - id: mode.id, - name: agentName(mode, t), - description: mode.description, - isReadonly: mode.isReadonly, - toolCount: mode.toolCount, - defaultTools: mode.defaultTools ?? [], - source: mode.source, - path: mode.path, - model: mode.model, - promptCacheScopeKey: mode.promptCacheScopeKey, - configProfileId: mode.configProfileId, - configProfileLabel: mode.configProfileLabel, - configProfileMemberModeIds: mode.configProfileMemberModeIds, - visibleSubagentCount: manageableSubagentsByProfile[mode.configProfileId] - ?.filter((subagent) => subagent.effectiveEnabled).length ?? 0, - capabilities: [], - agentKind: primaryAgentKind(mode), - }), - ); - - const subAgents: AgentWithCapabilities[] = subagents.map((subagent) => { - const modelOverride = subagentModelOverride(subagent, builtinOverrides); - - return enrichCapabilities({ - ...subagent, - name: agentName(subagent, t), - capabilities: [], - agentKind: 'subagent', - subagentModelOverride: modelOverride, - subagentModelDisplayName: modelOverride?.kind === 'pool' ? pools.find(pool => pool.id === modelOverride.pool_id)?.name ?? modelOverride.pool_id : subagentModelDisplayName(modelOverride, models, defaultModels), + details.current.set(key, entry); + setDetailRevision(value => value + 1); + const current = () => scope.isCurrent() && catalogRef.current?.key === catalogContextKey && details.current.get(key) === entry; + const fetchTools = (): Promise => { + if (toolsFlight.current?.key === catalogContextKey) return toolsFlight.current.promise; + const promise = !canQueryToolCatalog + ? Promise.resolve({ tools: [], status: 'unsupported' }) + : api.invoke('get_all_tools_info').then(tools => ({ tools, status: tools.length ? 'available' : 'empty' } as ToolCatalogLoadResult)).catch(error => { + toolLog.error('Failed to load tool catalog', { error }); + return { tools: [], status: 'failed' } as ToolCatalogLoadResult; }); - }); - - setAllAgents([...modeAgents, ...subAgents]); + toolsFlight.current = { key: catalogContextKey, promise }; + return promise; + }; + const configuredTools = mode + ? catalog.configs[profileId]?.enabled_tools ?? mode.defaultTools ?? [] + : subagent?.defaultTools ?? []; + entry.pending = Promise.all([ + fetchTools(), + configuredTools.includes('Skill') ? configAPI.getModeSkillConfigs({ modeId: targetId, workspaceId: workspace?.id }) : Promise.resolve([] as ModeSkillInfo[]), + mode ? SubagentAPI.listManageableSubagents({ parentAgentType: targetId, workspaceId: workspace?.id }) : Promise.resolve([] as SubagentInfo[]), + ]).then(([toolCatalog, skills, manageable]) => { + if (!current()) return; setAvailableTools(toolCatalog.tools); setToolCatalogStatus(toolCatalog.status); - setConfiguredModels(models); - setModeProfiles(profileMap); - setAgentSkills(Object.fromEntries(skillEntries)); - setModeConfigs(buildModeConfigsByProfile(modes, configs as Record)); - setModeManageableSubagents(manageableSubagentsByProfile); - setHiddenAgentIds(new Set([ - ...HIDDEN_AGENT_IDS, - ...(reviewTeamDefinition?.hiddenAgentIds ?? []), - ])); - } finally { - if (requestId === loadRequestIdRef.current) { - setLoading(false); + // A failed tool read is explicit and is retried on the next detail open. + if (toolCatalog.status === 'failed') toolsFlight.current = null; + setAgentSkills(state => ({ ...state, [profileId]: skills })); + setSkillCounts(state => ({ ...state, [profileId]: skills.filter(skill => skill.effectiveEnabled).length })); + if (mode) { + setModeManageableSubagents(state => ({ ...state, [profileId]: manageable })); + setSubagentCounts(state => ({ ...state, [profileId]: manageable.filter(agent => agent.effectiveEnabled).length })); } + entry.loaded = true; + }).catch(error => { + if (!current()) return; + entry.error = error instanceof Error ? error.message : String(error); + toolLog.error('Failed to load Agent detail capabilities', { agentId, error }); + }).finally(() => { + if (!current()) return; + entry.pending = undefined; + setDetailRevision(value => value + 1); + }); + return entry.pending; + }, [canQueryToolCatalog, catalogContextKey, scope, workspace?.id]); + detailLoaderRef.current = loadAgentDetails; + + const loadAgents = useCallback((options?: { background?: boolean; force?: boolean }): Promise => { + const existing = catalogFlight.current; + if (!options?.force && existing?.key === catalogContextKey) return existing.promise; + const requestId = ++loadRequestIdRef.current; + const current = () => requestId === loadRequestIdRef.current && scope.isCurrent(); + const retained = loadedContextKeyRef.current === catalogContextKey; + setLoading(!(options?.background && retained)); + setCatalogError(null); + if (!retained) { + setSkillCounts({}); setSubagentCounts({}); setAgentSkills({}); + setModeManageableSubagents({}); setAvailableTools([]); setToolCatalogStatus('loading'); + setConfiguredModels([]); setModelPools([]); setModelCatalogReady(false); } - }, [canQueryToolCatalog, workspace?.id, renderedPeerDeviceId, t]); + const flight = { key: catalogContextKey, promise: Promise.resolve() }; + catalogFlight.current = flight; + flight.promise = (async () => { + try { + const [modes, subagents, configs, reviewTeam] = await Promise.all([ + agentAPI.getAvailableModes({ workspaceId: workspace?.id, includeSubagentCounts: true }), + SubagentAPI.listSubagents({ workspaceId: workspace?.id }), + configAPI.getAgentProfileConfigs(), + loadDefaultReviewTeamDefinition().catch(() => undefined), + ]); + if (!current()) return; + const profiles = buildProfileMap(modes); + const byProfile = buildModeConfigsByProfile(modes, configs); + for (const [key, detail] of details.current) { + if (key.startsWith(catalogContextKey + ':')) details.current.set(key, { ...detail, pending: undefined }); + } + catalogRef.current = { key: catalogContextKey, modes, subagents, profiles, configs: byProfile }; + setModeProfiles(profiles); setModeConfigs(byProfile); + setHiddenAgentIds(new Set([...HIDDEN_AGENT_IDS, ...(reviewTeam?.hiddenAgentIds ?? [])])); + const initialCounts: Record = {}; + for (const mode of modes) if (typeof mode.manageableSubagentCount === 'number') initialCounts[modeProfileIdFor(mode)] = mode.manageableSubagentCount; + setSubagentCounts(state => retained ? { ...state, ...initialCounts } : initialCounts); + const modeAgents = modes.map(mode => enrichCapabilities({ + key: `mode::${mode.id}`, id: mode.id, name: agentName(mode, translateRef.current), + description: mode.description, isReadonly: mode.isReadonly, toolCount: mode.toolCount, + defaultTools: mode.defaultTools ?? [], source: mode.source, path: mode.path, model: mode.model, + promptCacheScopeKey: mode.promptCacheScopeKey, configProfileId: mode.configProfileId, + configProfileLabel: mode.configProfileLabel, configProfileMemberModeIds: mode.configProfileMemberModeIds, + visibleSubagentCount: initialCounts[modeProfileIdFor(mode)], capabilities: [], agentKind: primaryAgentKind(mode), + })); + const subAgents = subagents.map(agent => enrichCapabilities({ ...agent, name: agentName(agent, translateRef.current), capabilities: [], agentKind: 'subagent' as const })); + setAllAgents([...modeAgents, ...subAgents]); + loadedContextKeyRef.current = catalogContextKey; + setLoading(false); + setCountsLoading(true); setCountsError(null); + toolsFlight.current = null; + // An already-open editor keeps its mounted content while capabilities + // are revalidated. Opening a closed detail is handled by its own effect. + if (selectedIdRef.current) void detailLoaderRef.current(selectedIdRef.current, true); + const skillTargets = [ + ...Object.values(profiles).map(profile => ({ key: profile.profileId, id: profile.representativeModeId })), + ...subagents.filter(agent => agent.defaultTools.includes('Skill')).map(agent => ({ key: agent.id, id: agent.id })), + ]; + const missingCounts = Object.values(profiles).filter(profile => initialCounts[profile.profileId] === undefined); + const [skillResult, subagentResult, modelResult] = await Promise.allSettled([ + configAPI.getModeSkillCounts(skillTargets.map(target => target.id), workspace?.id), + Promise.all(missingCounts.map(async profile => [profile.profileId, (await SubagentAPI.listManageableSubagents({ parentAgentType: profile.representativeModeId, workspaceId: workspace?.id })).filter(agent => agent.effectiveEnabled).length] as const)), + Promise.all([ + configAPI.getConfigs(['ai.models', 'ai.default_models', modelSelectionsConfigPath()]), + supportsModelPools() ? modelPoolAPI.list() : Promise.resolve(undefined), + ]), + ]); + if (!current()) return; + const failures: string[] = []; + if (skillResult.status === 'fulfilled') { + setSkillCounts(Object.fromEntries(skillTargets.map(target => [target.key, skillResult.value[target.id]]))); + } else failures.push(String(skillResult.reason)); + if (subagentResult.status === 'fulfilled') { + setSubagentCounts(state => ({ ...state, ...Object.fromEntries(subagentResult.value) })); + } else failures.push(String(subagentResult.reason)); + if (modelResult.status === 'fulfilled') { + const [modelConfigs, document] = modelResult.value; + const models = (modelConfigs['ai.models'] as AIModelConfig[] | undefined) ?? []; + const defaults = (modelConfigs['ai.default_models'] as DefaultModelsConfig | undefined) ?? {}; + const overrides = effectiveModelSelections(modelConfigs[modelSelectionsConfigPath()] as AgentModelDefaultsConfig | undefined).subagents.builtin; + const pools = document ? readableModelPools(document) : []; + setModelPools(pools); setConfiguredModels(models); setModelCatalogReady(true); + const projected = new Map(subagents.map(agent => { + const selection = subagentModelOverride(agent, overrides); + return [agent.id, { subagentModelOverride: selection, subagentModelDisplayName: selection?.kind === 'pool' ? pools.find(pool => pool.id === selection.pool_id)?.name ?? selection.pool_id : subagentModelDisplayName(selection, models, defaults) }]; + })); + setAllAgents(state => state.map(agent => agent.agentKind === 'subagent' ? { ...agent, ...projected.get(agent.id) } : agent)); + } else failures.push(String(modelResult.reason)); + if (failures.length) { + setCountsError(failures.join('\n')); + toolLog.error('Failed to load Agent catalog summaries', { errors: failures }); + } + } catch (error) { + if (current()) { + setCatalogError(error instanceof Error ? error.message : String(error)); + toolLog.error('Failed to load Agent catalog', { error }); + } + } finally { + if (current()) { setLoading(false); setCountsLoading(false); } + if (catalogFlight.current === flight) catalogFlight.current = null; + } + })(); + return flight.promise; + }, [catalogContextKey, scope, workspace?.id]); + useEffect(() => { void loadAgents(); }, [loadAgents]); useEffect(() => { - void loadAgents(); + const refresh = () => { void loadAgents({ background: true, force: true }); }; + globalEventBus.on('custom-agent:updated', refresh); + return () => globalEventBus.off('custom-agent:updated', refresh); }, [loadAgents]); - useEffect(() => { - const handleCustomAgentUpdated = () => { - void loadAgents(); - }; + if (selectedAgentId) void loadAgentDetails(selectedAgentId, true); + }, [selectedAgentId, loadAgentDetails]); - globalEventBus.on('custom-agent:updated', handleCustomAgentUpdated); - return () => { - globalEventBus.off('custom-agent:updated', handleCustomAgentUpdated); - }; - }, [loadAgents]); + const profileForCount = (agentId: string) => { + const mode = catalogRef.current?.modes.find(mode => mode.id === agentId); + return mode ? modeProfileIdFor(mode) : agentId; + }; + const getAgentSkillCount = (agentId: string): number | null => skillCounts[profileForCount(agentId)] ?? null; + const getAgentSubagentCount = (agentId: string): number | null => subagentCounts[profileForCount(agentId)] ?? null; + const detailMode = catalogRef.current?.modes.find(mode => mode.id === selectedAgentId); + const detailKey = `${catalogContextKey}:${detailMode ? modeProfileIdFor(detailMode) : selectedAgentId}`; + const selectedDetail = details.current.get(detailKey); + const detailsLoading = Boolean(selectedAgentId && !selectedDetail?.loaded && !selectedDetail?.error); + const detailsError = selectedDetail?.error ?? null; + // Changing only the language reprojects labels, without restarting requests. + const localizedAgents = useMemo(() => allAgents.map(agent => ({ ...agent, name: agentName(agent, t) })), [allAgents, t]); + const catalogOwned = loadedContextKeyRef.current === catalogContextKey; const getModeProfile = useCallback((agentId: string): ModeProfileEntry | null => { const agent = allAgents.find((item) => item.id === agentId && isPrimaryAgent(item)); @@ -442,6 +500,7 @@ export function useAgentsList({ const updated = { ...config, ...updates }; await configAPI.setAgentProfileConfig(profile.representativeModeId, updated); setModeConfigs((prev) => ({ ...prev, [profile.profileId]: updated })); + void loadAgents({ background: true, force: true }); try { const { globalEventBus } = await import('@/infrastructure/event-bus'); @@ -449,7 +508,7 @@ export function useAgentsList({ } catch { // ignore } - }, [getModeConfig, getModeProfile]); + }, [getModeConfig, getModeProfile, loadAgents]); const handleSetTools = useCallback(async (agentId: string, toolNames: string[]) => { try { @@ -474,6 +533,8 @@ export function useAgentsList({ const modes = await agentAPI.getAvailableModes().catch(() => []); setModeConfigs(buildModeConfigsByProfile(modes, updated as Record)); setAgentSkills((prev) => ({ ...prev, [profile.profileId]: updatedSkills })); + setSkillCounts(state => ({ ...state, [profile.profileId]: updatedSkills.filter(skill => skill.effectiveEnabled).length })); + void loadAgents({ background: true, force: true }); notification.success(t('agentsOverview.toolsResetSuccess')); try { @@ -485,7 +546,7 @@ export function useAgentsList({ } catch { notification.error(t('agentsOverview.toolsResetFailed')); } - }, [getModeProfile, notification, t, workspace?.id]); + }, [getModeProfile, loadAgents, notification, t, workspace?.id]); const handleSetSkills = useCallback(async (agentId: string, enabledSkillKeys: string[]) => { const profile = getModeProfile(agentId); @@ -504,6 +565,8 @@ export function useAgentsList({ workspaceId: workspace?.id, }); setAgentSkills((prev) => ({ ...prev, [cacheKey]: updatedSkills })); + setSkillCounts(state => ({ ...state, [cacheKey]: updatedSkills.filter(skill => skill.effectiveEnabled).length })); + void loadAgents({ background: true, force: true }); try { const { globalEventBus } = await import('@/infrastructure/event-bus'); @@ -516,7 +579,7 @@ export function useAgentsList({ notification.error(t('agentsOverview.skillToggleFailed')); return false; } - }, [getModeProfile, notification, t, workspace?.id]); + }, [getModeProfile, loadAgents, notification, t, workspace?.id]); const handleResetSkills = useCallback(async (agentId: string) => { const profile = getModeProfile(agentId); @@ -534,6 +597,8 @@ export function useAgentsList({ workspaceId: workspace?.id, }); setAgentSkills((prev) => ({ ...prev, [cacheKey]: updatedSkills })); + setSkillCounts(state => ({ ...state, [cacheKey]: updatedSkills.filter(skill => skill.effectiveEnabled).length })); + void loadAgents({ background: true, force: true }); try { const { globalEventBus } = await import('@/infrastructure/event-bus'); @@ -546,7 +611,7 @@ export function useAgentsList({ notification.error(t('agentsOverview.skillToggleFailed')); return false; } - }, [getModeProfile, notification, t, workspace?.id]); + }, [getModeProfile, loadAgents, notification, t, workspace?.id]); const handleSetSubagentEnabled = useCallback(async ( agentId: string, @@ -567,8 +632,10 @@ export function useAgentsList({ const updatedSubagents = await SubagentAPI.listManageableSubagents({ parentAgentType: profile.representativeModeId, workspaceId: workspace?.id, - }).catch(() => []); + }); + setSubagentCounts(state => ({ ...state, [profile.profileId]: updatedSubagents.filter(agent => agent.effectiveEnabled).length })); + void loadAgents({ background: true, force: true }); setModeManageableSubagents((prev) => ({ ...prev, [profile.profileId]: updatedSubagents, @@ -591,7 +658,7 @@ export function useAgentsList({ } catch { notification.error(t('agentsOverview.subagentToggleFailed')); } - }, [getModeProfile, notification, t, workspace?.id]); + }, [getModeProfile, loadAgents, notification, t, workspace?.id]); const handleSetSubagentModel = useCallback(async ( subagentId: string, @@ -610,13 +677,13 @@ export function useAgentsList({ workspaceId: workspace?.id, }); } - await loadAgents(); + await loadAgents({ background: true, force: true }); } catch { notification.error(t('agentCard.modelSelector.updateFailed')); } }, [allAgents, loadAgents, notification, t, workspace?.id]); - const filteredAgents = useMemo(() => allAgents.filter((agent) => { + const filteredAgents = useMemo(() => localizedAgents.filter((agent) => { if (searchQuery) { const query = searchQuery.toLowerCase(); if (!agent.name.toLowerCase().includes(query) && !agent.description.toLowerCase().includes(query)) { @@ -635,11 +702,11 @@ export function useAgentsList({ } return true; - }), [allAgents, filterLevel, filterType, searchQuery]); + }), [localizedAgents, filterLevel, filterType, searchQuery]); const overviewAgents = useMemo( - () => allAgents.filter((agent) => !hiddenAgentIds.has(agent.id) && agent.agentKind !== 'harness'), - [allAgents, hiddenAgentIds], + () => localizedAgents.filter((agent) => !hiddenAgentIds.has(agent.id) && agent.agentKind !== 'harness'), + [localizedAgents, hiddenAgentIds], ); const counts = useMemo(() => ({ @@ -653,16 +720,21 @@ export function useAgentsList({ }), [overviewAgents]); return { + catalogContextKey, workspacePath, workspaceId: workspace?.id, workspaceIsRemote: isRemoteWorkspace(workspace), - allAgents, - filteredAgents, - loading, + allAgents: catalogOwned ? localizedAgents : [], + filteredAgents: catalogOwned ? filteredAgents : [], + loading: (loading || !catalogOwned) && !catalogError, + countsLoading, catalogError, countsError, + detailsLoading, detailsLoaded: Boolean(selectedDetail?.loaded), detailsError, loadAgentDetails, + getAgentSkillCount, getAgentSubagentCount, availableTools, toolCatalogStatus, configuredModels, modelPools, + modelCatalogReady, getModeProfile, getAgentSkills, getModeManageableSubagents, diff --git a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx index 70e646634f..c4994b4884 100644 --- a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx +++ b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx @@ -98,6 +98,47 @@ afterEach(() => { }); describe('MiniApp detail page navigation', () => { + it.each([{ apps: [] }, { apps: [app] }])('retains installed content throughout a pending return refresh: $apps.length entries', async ({ apps }) => { + vi.useFakeTimers(); + useMiniAppStore.setState({ apps }); + await render(); + const card = container.querySelector('.miniapp-installed-card'); + let finish!: (apps: MiniAppMeta[]) => void; + mocks.listMiniApps.mockReturnValueOnce(new Promise(resolve => { finish = resolve; })); + let refresh!: Promise; + await act(async () => { refresh = mocks.refetch!(); }); + expect(useMiniAppStore.getState().loading).toBe(false); + expect(container.querySelector('.gallery-skeleton')).toBeNull(); + if (card) expect(container.querySelector('.miniapp-installed-card')).toBe(card); + else expect(container.textContent).toContain('market.library.empty'); + await act(async () => { finish([{ ...app, name: 'Refreshed' }]); await refresh; }); + expect(container.querySelector('.miniapp-installed-card')?.textContent).toContain('Refreshed'); + }); + + it('does not clear another catalog load while a return refresh finishes', async () => { + vi.useFakeTimers(); + useMiniAppStore.setState({ apps: [], loading: true }); + await render(); + await act(async () => { await mocks.refetch!(); }); + expect(useMiniAppStore.getState().loading).toBe(true); + }); + + it.each([{ items: [] }, { items: [listing] }])('keeps a cached marketplace snapshot during return refresh: $items.length entries', async ({ items }) => { + vi.useFakeTimers(); + mocks.items = items; + await render('market'); + let finish!: (page: { items: MarketListingDetail[] }) => void; + mocks.browse.mockReturnValueOnce(new Promise(resolve => { finish = resolve; })); + let refresh!: Promise; + await act(async () => { refresh = mocks.refetch!(); }); + expect(container.querySelector('.gallery-skeleton')).toBeNull(); + expect(container.querySelector('[role="list"][aria-busy="true"]')).toBeNull(); + if (items.length) expect(container.querySelector('.miniapp-library-row')?.textContent).toContain('Timer'); + else expect(container.textContent).toContain('market.empty'); + await act(async () => { finish({ items: [listing] }); await refresh; }); + expect(container.querySelector('.miniapp-library-row')?.textContent).toContain('Timer'); + }); + it.each([{ apps: [] }, { apps: [app] }])('finishes the installed refresh before the marketplace responds: $apps.length entries', async ({ apps }) => { vi.useFakeTimers(); mocks.listMiniApps.mockResolvedValue(apps); diff --git a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx index 1ef2a0c746..c82b9665d8 100644 --- a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx +++ b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx @@ -142,7 +142,7 @@ const MiniAppLibraryContent: React.FC = ({ const [cachedPage] = useState(() => miniAppMarketAPI.getCachedPage({ query: '', category: 'all', sort: 'downloads', limit: 30 })); const [marketItems, setMarketItems] = useState(cachedPage?.items ?? []); const [nextCursor, setNextCursor] = useState(cachedPage?.nextCursor); - const [catalogLoading, setCatalogLoading] = useState(true); + const [catalogLoading, setCatalogLoading] = useState(!cachedPage); const [loadingMore, setLoadingMore] = useState(false); const [catalogError, setCatalogError] = useState(); const [detail, setDetail] = useState(); @@ -167,6 +167,7 @@ const MiniAppLibraryContent: React.FC = ({ const importTriggerRef = useRef(null); const importMenuRef = useRef(null); const catalogRequestRef = useRef(0); + const loadedCatalogKeyRef = useRef(cachedPage ? JSON.stringify(['', 'all', 'downloads']) : null); const animateList = useRef(true); const detailRequestRef = useRef(0); const catalogContentRef = useRef(null); @@ -275,12 +276,13 @@ const MiniAppLibraryContent: React.FC = ({ /> ); - const fetchCatalog = useCallback(async (cursor?: string, append = false) => { + const fetchCatalog = useCallback(async (cursor?: string, append = false, background = false) => { if (!surfaceScope.isCurrent()) return; const requestId = ++catalogRequestRef.current; + const catalogKey = JSON.stringify([query, category, sort]); if (append) setLoadingMore(true); else { - setCatalogLoading(true); + setCatalogLoading(!(background && loadedCatalogKeyRef.current === catalogKey)); setLoadingMore(false); } setCatalogError(undefined); @@ -296,6 +298,7 @@ const MiniAppLibraryContent: React.FC = ({ if (requestId !== catalogRequestRef.current) return; setMarketItems((current) => append ? [...current, ...page.items] : page.items); setNextCursor(page.nextCursor); + loadedCatalogKeyRef.current = catalogKey; } catch (loadError) { if (requestId !== catalogRequestRef.current) return; log.error('Failed to load MiniApp marketplace catalog', loadError); @@ -311,7 +314,7 @@ const MiniAppLibraryContent: React.FC = ({ useEffect(() => { const timeout = window.setTimeout(() => { - void fetchCatalog(undefined, false); + void fetchCatalog(undefined, false, true); }, 250); return () => { window.clearTimeout(timeout); @@ -322,7 +325,8 @@ const MiniAppLibraryContent: React.FC = ({ const refetchMiniAppLibrary = useCallback(async () => { if (!surfaceScope.isCurrent()) return; - setLoading(true); + // The startup catalog owner manages initial loading. A return refresh must + // neither replace a valid empty view nor clear another owner's pending load. try { const [refreshed, running, origins] = await Promise.all([ miniAppAPI.listMiniApps(), @@ -337,13 +341,11 @@ const MiniAppLibraryContent: React.FC = ({ if (!surfaceScope.isCurrent()) return; log.error('Failed to refresh MiniApp library', error); return; - } finally { - if (surfaceScope.isCurrent()) setLoading(false); } // Installed entries are ready independently of the network catalog. Keep // refreshing marketplace metadata without extending the local loading state. - await fetchCatalog(undefined, false); - }, [fetchCatalog, setApps, setLoading, setMarketOrigins, setRunningWorkerIds, surfaceScope]); + await fetchCatalog(undefined, false, true); + }, [fetchCatalog, setApps, setMarketOrigins, setRunningWorkerIds, surfaceScope]); useGallerySceneAutoRefresh({ sceneId: 'miniapps', diff --git a/src/web-ui/src/app/scenes/personal-overview/OverviewMiniAppLogos.test.tsx b/src/web-ui/src/app/scenes/personal-overview/OverviewMiniAppLogos.test.tsx index 5afa732189..fb98cfa816 100644 --- a/src/web-ui/src/app/scenes/personal-overview/OverviewMiniAppLogos.test.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/OverviewMiniAppLogos.test.tsx @@ -12,6 +12,7 @@ vi.mock('@/infrastructure/i18n/hooks/useI18n', () => ({ let root: Root; let container: HTMLDivElement; let width: number; +let rowLayoutReads: number; const resizeListeners = new Set<() => void>(); const details = vi.fn(); const launch = vi.fn(); @@ -23,6 +24,7 @@ const resize = (nextWidth: number) => act(() => { width = nextWidth; resizeListe beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); width = 136; + rowLayoutReads = 0; vi.clearAllMocks(); resizeListeners.clear(); vi.stubGlobal('ResizeObserver', class { @@ -31,7 +33,9 @@ beforeEach(() => { disconnect() { resizeListeners.delete(this.listener); } }); vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function () { - return this.classList.contains('overview-miniapp-logos') ? width + 4 : 0; + if (!this.classList.contains('overview-miniapp-logos')) return 0; + rowLayoutReads += 1; + return width + 4; }); vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(function () { return this.classList.contains('overview-miniapp-logos__probe') ? 40 : 0; @@ -50,7 +54,7 @@ afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); }); -const render = () => act(async () => { root.render(); }); +const render = (isActive = true) => act(async () => { root.render(); }); it('fits complete logos to the measured width and reserves an overflow entry', async () => { await render(); @@ -83,3 +87,20 @@ it('keeps details and launch independent and restores focus when a focused app i resize(88); expect(document.activeElement).toBe(container.querySelector('[data-testid="personal-overview-more-miniapps"]')); }); + +it('retains fitted logos while inactive and measures the current width again on reveal', async () => { + await render(false); + expect(rowLayoutReads).toBe(0); + await render(); + expect(visibleIds()).toEqual(['app-0', 'app-1']); + const oldDelivery = [...resizeListeners]; + await render(false); + const previousReads = rowLayoutReads; + resize(232); + act(() => oldDelivery.forEach(deliver => deliver())); + expect(rowLayoutReads).toBe(previousReads); + expect(visibleIds()).toEqual(['app-0', 'app-1']); + await render(); + expect(visibleIds()).toEqual(apps.map(app => app.id)); + expect(rowLayoutReads).toBeGreaterThan(previousReads); +}); diff --git a/src/web-ui/src/app/scenes/personal-overview/OverviewMiniAppLogos.tsx b/src/web-ui/src/app/scenes/personal-overview/OverviewMiniAppLogos.tsx index c1bf3a2b00..343bfe40a3 100644 --- a/src/web-ui/src/app/scenes/personal-overview/OverviewMiniAppLogos.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/OverviewMiniAppLogos.tsx @@ -7,11 +7,12 @@ import { pickLocalizedString } from '../miniapps/utils/pickLocalizedString'; import { renderMiniAppIcon } from '../miniapps/utils/miniAppIcons'; import './OverviewMiniAppLogos.scss'; -export function OverviewMiniAppLogos({ apps, onDetails, onLaunch, onViewAll }: { +export function OverviewMiniAppLogos({ apps, onDetails, onLaunch, onViewAll, isActive = true }: { apps: MiniAppMeta[]; onDetails: (app: MiniAppMeta) => void; onLaunch: (appId: string) => void; onViewAll: () => void; + isActive?: boolean; }) { const { t, currentLanguage, formatNumber } = useI18n('scenes/personal-overview'); const rowRef = useRef(null); @@ -21,10 +22,13 @@ export function OverviewMiniAppLogos({ apps, onDetails, onLaunch, onViewAll }: { const [visibleCount, setVisibleCount] = useState(null); useLayoutEffect(() => { + if (!isActive) return; const row = rowRef.current; const probe = probeRef.current; if (!row || !probe) return; + let disposed = false; const measure = () => { + if (disposed) return; const style = getComputedStyle(row); const width = row.clientWidth - (Number.parseFloat(style.paddingInlineStart) || 0) - (Number.parseFloat(style.paddingInlineEnd) || 0); const size = probe.offsetWidth; @@ -43,8 +47,8 @@ export function OverviewMiniAppLogos({ apps, onDetails, onLaunch, onViewAll }: { const observer = new ResizeObserver(measure); observer.observe(row); observer.observe(probe); - return () => observer.disconnect(); - }, [apps.length]); + return () => { disposed = true; observer.disconnect(); }; + }, [apps.length, isActive]); useLayoutEffect(() => { if (!restoreFocus.current) return; diff --git a/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.tsx b/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.tsx index 2e71c8be11..df953a9d47 100644 --- a/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.tsx @@ -275,7 +275,7 @@ const PersonalOverviewScene: React.FC<{ isActive?: boolean }> = ({ isActive = tr /> {miniApps.status === 'ready' ? miniAppItems.length > 0 ? ( - useSceneStore.getState().openScene(`miniapp:${appId}`)} onViewAll={() => useSceneStore.getState().openScene('miniapps')} /> ) :

{t('miniApps.empty')}

: ( diff --git a/src/web-ui/src/app/scenes/personal-overview/usePersonalOverview.test.tsx b/src/web-ui/src/app/scenes/personal-overview/usePersonalOverview.test.tsx index 60abccc087..30b078d782 100644 --- a/src/web-ui/src/app/scenes/personal-overview/usePersonalOverview.test.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/usePersonalOverview.test.tsx @@ -138,6 +138,39 @@ describe('personal overview data isolation', () => { expect(mocks.usage).toHaveBeenCalledTimes(2); }); + it('retains successful sections during re-entry and commits independently refreshed data', async () => { + await render(); + const previous = latest; + const usage = deferred(); + const apps = deferred(); + const skills = deferred(); + mocks.usage.mockReturnValueOnce(usage.promise); + mocks.miniApps.mockReturnValueOnce(apps.promise); + mocks.skills.mockReturnValueOnce(skills.promise); + await render(false); + await render(true); + expect(latest.usage).toBe(previous.usage); + expect(latest.miniApps).toBe(previous.miniApps); + expect(latest.skills).toBe(previous.skills); + await act(async () => { usage.resolve(statistics(50)); }); + expect(latest.usage.status === 'ready' && latest.usage.data.stats.totalTokens).toBe(50); + expect(latest.miniApps).toBe(previous.miniApps); + await act(async () => { + apps.resolve([]); + skills.resolve({ skills: [], diagnostics: [], diagnosticsAvailable: false }); + }); + expect(latest.skills).toEqual({ status: 'ready', data: { skills: [], diagnostics: [], diagnosticsAvailable: false } }); + }); + + it('reports background failures instead of presenting a retained snapshot as current success', async () => { + await render(); + mocks.usage.mockRejectedValueOnce(new Error('Usage unavailable')); + await render(false); + await render(true); + expect(latest.usage.status).toBe('failed'); + expect(latest.miniApps.status).toBe('ready'); + }); + it('does not present failed MiniApp or Skill reads as empty catalogs, and retries independently of usage', async () => { mocks.miniApps.mockRejectedValue(new Error('Peer offline')); mocks.skills.mockRejectedValue(new Error('Remote workspace unavailable')); diff --git a/src/web-ui/src/app/scenes/personal-overview/usePersonalOverview.ts b/src/web-ui/src/app/scenes/personal-overview/usePersonalOverview.ts index c480340bd3..1891c9c609 100644 --- a/src/web-ui/src/app/scenes/personal-overview/usePersonalOverview.ts +++ b/src/web-ui/src/app/scenes/personal-overview/usePersonalOverview.ts @@ -63,7 +63,15 @@ export function usePersonalOverview(timeZone: string, isActive: boolean) { if (!isActive) return; let cancelled = false; const current = () => !cancelled && scope.isCurrent(); - setSnapshot({ key, usage: loading, agents: loading, miniApps: loading, skills: loading }); + // Keep independent, successful sections visible while revalidating the same + // surface/workspace. Failed sections still enter loading for a real retry. + setSnapshot(state => state?.key === key ? { + ...state, + usage: state.usage.status === 'ready' ? state.usage : loading, + agents: state.agents.status === 'ready' ? state.agents : loading, + miniApps: state.miniApps.status === 'ready' ? state.miniApps : loading, + skills: state.skills.status === 'ready' ? state.skills : loading, + } : { key, usage: loading, agents: loading, miniApps: loading, skills: loading }); void tokenUsageStatisticsApi.getStatistics({ timeRange: 'all', granularity: 'day', timeZone, includeSubagent: true, }).then(stats => { diff --git a/src/web-ui/src/app/scenes/skills/SkillsScene.tsx b/src/web-ui/src/app/scenes/skills/SkillsScene.tsx index fa5300fa89..9df8d898b2 100644 --- a/src/web-ui/src/app/scenes/skills/SkillsScene.tsx +++ b/src/web-ui/src/app/scenes/skills/SkillsScene.tsx @@ -236,7 +236,11 @@ const SkillsScene: React.FC = () => { }, [coverageSourceBySkillKey, installed, market.isRemoteWorkspace, t]); const refetchSkillsScene = useCallback(async () => { - await Promise.all([installed.loadSkills(true), market.refresh(), skillGroups.reload()]); + await Promise.all([ + installed.loadSkills(true, { background: true }), + market.refresh({ background: true }), + skillGroups.reload(), + ]); }, [installed, market, skillGroups]); useGallerySceneAutoRefresh({ diff --git a/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.test.tsx b/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.test.tsx index 631807eabb..cc47a1f0b5 100644 --- a/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.test.tsx +++ b/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.test.tsx @@ -184,6 +184,43 @@ describe('useInstalledSkills', () => { expect(currentInstalled?.counts.all).toBe(0); }); + it.each([{ entries: [] }, { entries: [{ key: 'review', name: 'Review', level: 'user', path: '/skills/review' }] }])('keeps a successful snapshot during forced background scans: $entries.length entries', async ({ entries }) => { + getSkillConfigsMock.mockResolvedValueOnce(entries); + await act(async () => root.render()); + let finish!: (skills: typeof entries) => void; + getSkillConfigsMock.mockReturnValueOnce(new Promise(resolve => { finish = resolve; })); + let refresh!: Promise; + await act(async () => { refresh = currentInstalled!.loadSkills(true, { background: true }); }); + expect(currentInstalled?.loading).toBe(false); + expect(currentInstalled?.skills).toEqual(entries); + expect(getSkillConfigsMock).toHaveBeenLastCalledWith({ forceRefresh: true, workspaceId: 'workspace-id' }); + const updated = [{ key: 'updated', name: 'Updated', level: 'user', path: '/skills/updated' }]; + await act(async () => { finish(updated); await refresh; }); + expect(currentInstalled?.skills).toEqual(updated); + }); + + it('keeps background scan failures visible and fences a later workspace switch', async () => { + await act(async () => root.render()); + getSkillConfigsMock.mockRejectedValueOnce(new Error('Scan failed')); + await act(async () => { await currentInstalled!.loadSkills(true, { background: true }); }); + expect(currentInstalled?.error).toBe('Scan failed'); + getSkillConfigsMock.mockReturnValue(new Promise(() => {})); + workspaceMock.id = 'workspace-b'; + await act(async () => root.render()); + await act(async () => { void currentInstalled!.loadSkills(true, { background: true }); }); + expect(currentInstalled?.loading).toBe(true); + expect(currentInstalled?.skills).toEqual([]); + }); + + it('requires a new snapshot after disabling and re-enabling the catalog', async () => { + await act(async () => root.render()); + await act(async () => root.render()); + getSkillConfigsMock.mockReturnValue(new Promise(() => {})); + await act(async () => root.render()); + await act(async () => { void currentInstalled!.loadSkills(true, { background: true }); }); + expect(currentInstalled?.loading).toBe(true); + }); + it('reports unsupported skill capabilities without claiming a scan failure', async () => { diagnosticsMock.items = [{ path: '/skills/guard/SKILL.md', sourceId: 'claude-code', diff --git a/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.ts b/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.ts index 8113e1ee86..36ab55033c 100644 --- a/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.ts +++ b/src/web-ui/src/app/scenes/skills/hooks/useInstalledSkills.ts @@ -67,6 +67,7 @@ export function useInstalledSkills({ const [isValidating, setIsValidating] = useState(false); const [isAdding, setIsAdding] = useState(false); const loadRequestIdRef = useRef(0); + const loadedContextKeyRef = useRef(null); const lastScanFeedbackKeyRef = useRef(null); const validationRequestIdRef = useRef(0); const capabilityKey = scope.key(scope.epoch, String(enabled), workspace?.id, String(isRemoteWorkspace)); @@ -96,7 +97,7 @@ export function useInstalledSkills({ capabilityRef.current.enabled && capabilityRef.current.epoch === epoch ), []); - const loadSkills = useCallback(async (forceRefresh?: boolean) => { + const loadSkills = useCallback(async (forceRefresh?: boolean, options?: { background?: boolean }) => { const capabilityEpoch = currentCapabilityEpoch(); if (capabilityEpoch === null) { return; @@ -104,7 +105,7 @@ export function useInstalledSkills({ const requestId = ++loadRequestIdRef.current; try { - setLoading(true); + setLoading(!(options?.background && loadedContextKeyRef.current === capabilityRef.current.key)); setError(null); const [list, globalSettings] = await Promise.all([ configAPI.getSkillScanReport({ @@ -122,6 +123,7 @@ export function useInstalledSkills({ return; } setLoadedContextKey(capabilityRef.current.key); + loadedContextKeyRef.current = capabilityRef.current.key; setSkills(list.skills); setDiagnostics(list.diagnostics); setDiagnosticsAvailable(list.diagnosticsAvailable); @@ -202,6 +204,7 @@ export function useInstalledSkills({ setIsValidating(false); setIsAdding(false); if (!enabled) { + loadedContextKeyRef.current = null; setSkills([]); setDiagnostics([]); setDiagnosticsAvailable(true); diff --git a/src/web-ui/src/app/scenes/skills/hooks/useSkillMarket.test.tsx b/src/web-ui/src/app/scenes/skills/hooks/useSkillMarket.test.tsx index bd7aa802c0..3e34773717 100644 --- a/src/web-ui/src/app/scenes/skills/hooks/useSkillMarket.test.tsx +++ b/src/web-ui/src/app/scenes/skills/hooks/useSkillMarket.test.tsx @@ -5,6 +5,7 @@ import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { SkillMarketItem } from '@/infrastructure/config/types'; import { useSkillMarket } from './useSkillMarket'; +import { activateSurface, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; const listSkillMarketMock = vi.hoisted(() => vi.fn()); const searchSkillMarketMock = vi.hoisted(() => vi.fn()); @@ -68,6 +69,7 @@ describe('useSkillMarket', () => { let root: Root; beforeEach(() => { + resetDeviceSurfaceForTest(); Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); container = document.createElement('div'); document.body.appendChild(container); @@ -85,6 +87,7 @@ describe('useSkillMarket', () => { afterEach(async () => { await act(async () => root.unmount()); container.remove(); + resetDeviceSurfaceForTest(); }); it('refreshes when marketplace configuration changes and ignores the old response', async () => { @@ -108,6 +111,57 @@ describe('useSkillMarket', () => { expect(currentMarket?.marketError).toBeNull(); }); + it('retains the current page and loaded range during a background refresh', async () => { + const items = Array.from({ length: 40 }, (_, index) => ({ + id: `skill-${index}`, installId: `source@skill-${index}`, name: `Skill ${index}`, source: 'source', + })) as SkillMarketItem[]; + listSkillMarketMock.mockResolvedValueOnce(items.slice(0, 20)).mockResolvedValueOnce(items); + await act(async () => root.render()); + await act(async () => { await currentMarket!.goToPage(2); }); + expect(currentMarket?.currentPage).toBe(2); + const previous = currentMarket!.marketSkills; + let finish!: (skills: SkillMarketItem[]) => void; + listSkillMarketMock.mockReturnValueOnce(new Promise(resolve => { finish = resolve; })); + let refresh!: Promise; + await act(async () => { refresh = currentMarket!.refresh({ background: true }); }); + expect(currentMarket?.marketLoading).toBe(false); + expect(currentMarket?.currentPage).toBe(2); + expect(currentMarket?.marketSkills).toEqual(previous); + expect(listSkillMarketMock).toHaveBeenLastCalledWith(undefined, 40); + await act(async () => { finish(items.map(item => ({ ...item, description: 'Updated' }))); await refresh; }); + expect(currentMarket?.currentPage).toBe(2); + expect(currentMarket?.marketSkills[0].description).toBe('Updated'); + }); + + it('retains a valid empty background snapshot and still reports refresh failures', async () => { + await act(async () => root.render()); + let fail!: (error: Error) => void; + listSkillMarketMock.mockReturnValueOnce(new Promise((_, reject) => { fail = reject; })); + let refresh!: Promise; + await act(async () => { refresh = currentMarket!.refresh({ background: true }); }); + expect(currentMarket?.marketLoading).toBe(false); + expect(currentMarket?.marketSkills).toEqual([]); + await act(async () => { fail(new Error('Market offline')); await refresh; }); + expect(currentMarket?.marketError).toBe('Market offline'); + }); + + it('does not reuse a background snapshot or late response on another peer with the same workspace ID', async () => { + const item = { id: 'private', installId: 'source@private', name: 'Private', source: 'source' } as SkillMarketItem; + listSkillMarketMock.mockResolvedValueOnce([item]); + await act(async () => root.render()); + let finishOld!: (skills: SkillMarketItem[]) => void; + listSkillMarketMock.mockReturnValueOnce(new Promise(resolve => { finishOld = resolve; })); + let oldRefresh!: Promise; + await act(async () => { oldRefresh = currentMarket!.refresh({ background: true }); }); + listSkillMarketMock.mockReturnValue(new Promise(() => {})); + await act(async () => { activateSurface('peer-b'); }); + expect(currentMarket?.marketLoading).toBe(true); + expect(currentMarket?.marketSkills).toEqual([]); + await act(async () => { finishOld([item]); await oldRefresh; }); + expect(currentMarket?.marketSkills).toEqual([]); + expect(currentMarket?.marketLoading).toBe(true); + }); + it('prioritizes only the installed repository when market skills share a name', async () => { const first = { id: 'first/skills/eli5', name: 'eli5', source: 'first/skills', diff --git a/src/web-ui/src/app/scenes/skills/hooks/useSkillMarket.ts b/src/web-ui/src/app/scenes/skills/hooks/useSkillMarket.ts index e5bea5ddc8..4aacc36a66 100644 --- a/src/web-ui/src/app/scenes/skills/hooks/useSkillMarket.ts +++ b/src/web-ui/src/app/scenes/skills/hooks/useSkillMarket.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { useTranslation } from 'react-i18next'; import { configManager } from '@/infrastructure/config/services/ConfigManager'; import { configAPI } from '@/infrastructure/api'; @@ -7,6 +7,7 @@ import type { SkillLevel, SkillMarketItem } from '@/infrastructure/config/types' import { useWorkspaceManagerSync } from '@/infrastructure/hooks/useWorkspaceManagerSync'; import { useNotification } from '@/shared/notification-system'; import { createLogger } from '@/shared/utils/logger'; +import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; const log = createLogger('SkillsScene:useSkillMarket'); @@ -33,6 +34,7 @@ export function useSkillMarket({ const { t } = useTranslation('scenes/skills'); const notification = useNotification(); const { workspace, hasWorkspace, isRemoteWorkspace } = useWorkspaceManagerSync(); + const scope = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope); const [marketSkills, setMarketSkills] = useState([]); const [marketLoading, setMarketLoading] = useState(true); @@ -51,7 +53,9 @@ export function useSkillMarket({ } }, [pageSize]); const marketRequestIdRef = useRef(0); - const capabilityKey = `${enabled}\u0000${workspace?.id ?? ''}\u0000${isRemoteWorkspace}`; + const loadedCatalogRef = useRef<{ key: string; query: string | undefined; limit: number } | null>(null); + const errorContextKeyRef = useRef(null); + const capabilityKey = scope.key(scope.epoch, String(enabled), workspace?.id, String(isRemoteWorkspace)); const capabilityRef = useRef({ key: capabilityKey, epoch: 0, enabled }); useLayoutEffect(() => { if (capabilityRef.current.key !== capabilityKey) { @@ -77,32 +81,44 @@ export function useSkillMarket({ return await configAPI.querySkillMarkets(normalized || undefined, limit); }, []); - const loadFirstPage = useCallback(async (query?: string) => { + const loadFirstPage = useCallback(async (query?: string, options?: { background?: boolean }) => { const capabilityEpoch = currentCapabilityEpoch(); if (capabilityEpoch === null) { return; } const requestId = ++marketRequestIdRef.current; + const snapshot = loadedCatalogRef.current; + const background = options?.background && snapshot?.key === capabilityRef.current.key && snapshot.query === query; + // Refresh all currently loaded pages so re-entry does not discard the page + // being read or shrink its scroll range back to the first fetch batch. + const limit = background ? snapshot.limit : FETCH_BATCH_SIZE; - setMarketLoading(true); + setMarketLoading(!background); setLoadingMore(false); setMarketError(null); - setSourceErrors([]); - setCurrentPage(0); + if (!background) { + setSourceErrors([]); + setCurrentPage(0); + } try { - const result = await fetchSkills(query, FETCH_BATCH_SIZE); + const result = await fetchSkills(query, limit); if (requestId !== marketRequestIdRef.current || !capabilityIsCurrent(capabilityEpoch)) { return; } const skillList = result.skills; setSourceErrors(result.sourceErrors); setMarketSkills(skillList); - setHasMore(skillList.length >= FETCH_BATCH_SIZE); + setHasMore(limit < MAX_TOTAL_SKILLS && skillList.length >= limit); + loadedCatalogRef.current = { key: capabilityRef.current.key, query, limit }; + if (background) { + setCurrentPage(page => Math.min(page, Math.max(0, Math.ceil(skillList.length / pageSizeRef.current) - 1))); + } } catch (err) { if (requestId !== marketRequestIdRef.current || !capabilityIsCurrent(capabilityEpoch)) { return; } log.error('Failed to load skill market', err); + errorContextKeyRef.current = capabilityRef.current.key; setMarketError(err instanceof Error ? err.message : String(err)); } finally { if (requestId === marketRequestIdRef.current && capabilityIsCurrent(capabilityEpoch)) { @@ -114,6 +130,7 @@ export function useSkillMarket({ useEffect(() => { marketRequestIdRef.current += 1; if (!enabled) { + loadedCatalogRef.current = null; setMarketSkills([]); setMarketLoading(false); setLoadingMore(false); @@ -129,17 +146,20 @@ export function useSkillMarket({ useEffect(() => configManager.onConfigChange((path) => { if (path === 'app.skill_market' || path.startsWith('app.skill_market.')) { + loadedCatalogRef.current = null; setMarketSkills([]); void loadFirstPage(searchQuery || undefined); } }), [loadFirstPage, searchQuery]); - const refresh = useCallback(async () => { - await loadFirstPage(searchQuery || undefined); + const refresh = useCallback(async (options?: { background?: boolean }) => { + await loadFirstPage(searchQuery || undefined, options); }, [loadFirstPage, searchQuery]); + const catalogCurrent = loadedCatalogRef.current?.key === capabilityKey; + const currentMarketError = errorContextKeyRef.current === capabilityKey ? marketError : null; const displayMarketSkills = useMemo(() => { - const entries = marketSkills.map((skill, index) => ({ + const entries = (catalogCurrent ? marketSkills : []).map((skill, index) => ({ skill, index, installed: isSkillMarketItemInstalled(skill, installedMarketIds), @@ -157,7 +177,7 @@ export function useSkillMarket({ }); return entries.map((entry) => entry.skill); - }, [installedMarketIds, marketSkills]); + }, [catalogCurrent, installedMarketIds, marketSkills]); const loadedPages = Math.ceil(displayMarketSkills.length / pageSize); const totalPages = hasMore ? loadedPages + 1 : Math.max(1, loadedPages); @@ -190,6 +210,7 @@ export function useSkillMarket({ setSourceErrors(result.sourceErrors); setMarketSkills(skillList); setHasMore(limit < MAX_TOTAL_SKILLS && skillList.length >= limit); + loadedCatalogRef.current = { key: capabilityRef.current.key, query: searchQuery || undefined, limit }; // An exhausted source may return no new entries. Stay on a populated page, // including when the viewport capacity changed during the request. setCurrentPage(Math.floor(Math.min(firstIndex, Math.max(0, skillList.length - 1)) / pageSizeRef.current)); @@ -246,9 +267,9 @@ export function useSkillMarket({ return { marketSkills: paginatedSkills, - marketLoading, + marketLoading: enabled && (marketLoading || (!catalogCurrent && !currentMarketError)), loadingMore, - marketError, + marketError: currentMarketError, sourceErrors, downloadingPackage, hasMore, diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md index 57c4cea6c3..f69bbec1e0 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md @@ -16,10 +16,12 @@ each missing what the other had. | Test | Contract it holds | |---|---| +| `../../timeline/useTimelineInteraction.test.tsx` | selection/focus retention and cleanup; mutation/resize bursts coalesce before dimension reads, inactive viewports keep leases without measurement and refresh on reveal, while explicit active selection/focus changes retain immediately; supplied DOM geometry, not native performance evidence | +| `flowItemRhythm.test.ts`, `../../../tools/generative-ui/genUISpacing.test.ts` | mixed agent-card full-row children and exact generated-content gap matching through nested stacks, hidden children and insert/remove snapshots; native invalidation and performance are verified separately | | `../../store/modernFlowChatStore.test.ts`, `../../grouping/selectors.test.ts`, `../../grouping/activityGrouping.test.ts`, `../../../shared/utils/resourceBudget.test.ts` | cached/full projection equivalence across repeated thinking/tool-parameter streams, interior updates, rollback, completion and legacy retry/recovery; alternating live/history/side projections, completed-row reuse on append, same-store clear/reopen invalidation, warm equal-ID source isolation, group alias restoration and group-position independence; interrupted-prefix and shared-reference byte accounting | | `useFlowChatVirtualizer.initial-window.test.tsx`, `useFlowChatSearch.test.ts` | delayed observer delivery after live prepend / history tail insertion resizes the surviving key; suspended mounts are observed on resume with or without origin handoff; closing one search releases its match cache without affecting another view | | `../../perf/longRoundPerfHarness.test.tsx` | deterministic settled-row/block identity reuse, including interleaved history and side projections, plus diagnostic stage timings; supplied DOM fixtures, not native frame-rate or live remote evidence | -| `../../../infrastructure/markdown/markdownSections.test.ts`, `../../timeline/document.test.ts` | exact source reconstruction and equivalent Markdown ASTs across LF/CRLF/CR, lists/fences/tables/quotes/math, conservative reference/HTML fallback, canonical identities, Unicode search counts, bounded section estimates, no live completion repartition, and display-only narrative ID handoff with canonical bookmark/navigation IDs, retry/source isolation and alias-collision recovery | +| `../../../infrastructure/markdown/markdownSections.test.ts`, `../../timeline/document.test.ts` | exact source reconstruction and equivalent Markdown ASTs across LF/CRLF/CR, lists/fences/tables/quotes/math, conservative reference/HTML fallback, canonical identities, Unicode search counts, bounded section estimates, no live completion repartition, and display-only narrative ID handoff with canonical bookmark/navigation IDs, retry/source isolation and alias-collision recovery; native single-attempt metadata omission and restored blank-line section coordinates without modifying host text | | `../FlowTextBlock.test.tsx`, `../../../infrastructure/markdown/MarkdownCodeBody.test.tsx` | sealed live-prefix DOM/parser reuse, one shared decoration observer, selected-node retention, source-only oversized fences and cleanup; DOM fixtures, not native paint evidence | | `../../trajectory` | bounded long-session rail, stable range identities, keyboard preview vs selection, searchable summary pagination, legacy-peer gating, stale device/query rejection, canonical peer body navigation, shared detail components and bounded output; local DOM/transport fixtures, not native rendering or live remote evidence | | `../FlowChatWidthBoundary.test.tsx`, `../../../infrastructure/appearance/preferences/flowChatWidthStore.test.ts`, `../../../app/scenes/settings/pages/application/FlowChatWidthSettingsSection.test.tsx` | symmetric pointer/keyboard column resizing, token-derived bounds, cancellation/cleanup, narrow-pane restoration, persisted preference compatibility and settings/reset synchronization; supplied DOM geometry, not visual or live remote evidence | diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md index 701fd08cb9..9442ed11ec 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md @@ -105,6 +105,13 @@ regression observed a 92px downward displacement followed by an eased return. narrative handoff inside the same Turn and model round. Types, attempts and content must agree (allowing coalesced blank lines and a recovered suffix); insertions, removals, unrelated prose and replaced tools do not qualify. +Native settled records can omit the first attempt's item-level metadata. An +explicit settled `attemptCount: 1` permits that handoff from `attemptIndex: 1`; +missing counts, multiple attempts and conflicting explicit identities do not. +Markdown section budgets use coalesced blank-line coordinates so that journal +whitespace cannot move a semantic boundary. View-local section aliases retain +the original display offsets while section ranges and bookmarks continue to +use the unmodified host source. No viewport writer or follow policy changes. Unchanged source arrays skip item reconciliation, retired sources are released, and aliases are weakly keyed by the source item objects. @@ -118,6 +125,14 @@ following and while reading. It does not establish native paint or live transpor ## Large text and decoration residency +Globally loaded styles also affect virtualization cost. Universal sibling rules +in the GenUI spacing sheets and an unqualified child after the shared agent-card +`:has()` selector invalidated unrelated shell subtrees when rows were recycled. +Spacing keeps its element-child matching and specificity; agent-row sizing names +the stack renderers' owned children inside `:where()`. New direct stack child +kinds must retain that sizing contract. Native invalidation/Selector Stats traces +identify the cause; ordinary uninstrumented runs establish the performance change. + `markdownSections` uses the existing streaming parser's block tokenizer to find semantic boundaries. It does not perform inline parsing or replace the product Markdown renderer/sanitizer. Live and historical replies project roughly 3,000-character @@ -126,8 +141,10 @@ not truncation: an individual fence, table, list or quote remains whole. Raw HTM reference/footnote dependencies and structured research protocols keep their whole-document path. Canonical text and export/copy payloads stay unchanged. -The first section retains its previous block key; later keys include the raw -source offset. Thinking stays with the first section. Search translates whole +The first section retains its previous block key; later keys initially include +the raw source offset, retained as a display alias during settled whitespace +handoff. Canonical bookmarks always use the current raw offset. Thinking stays +with the first section. Search translates whole message occurrence counts into section-local counts, including Unicode case folding. Section indexes and search boundary counts each have a 2 MiB/64-entry budget under the shared derived-resource budget. They retain neither DOM nor diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx index d42eee058d..eb335477a3 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx @@ -550,7 +550,7 @@ const VirtualMessageListSession = forwardRef void>(() => {}); - const interactionKeys = useTimelineInteraction(scrollerElementRef, reader, () => viewportOwner.currentOwner() === 'follow-output', undefined, kind => readerInteractionRef.current(kind)); + const interactionKeys = useTimelineInteraction(scrollerElementRef, reader, () => viewportOwner.currentOwner() === 'follow-output', undefined, kind => readerInteractionRef.current(kind), isViewportActive); const displayedTailTurnId = virtualItems.at(-1)?.turnId; const displayedTailStart = useMemo(() => virtualItems.findIndex(item => item.turnId === displayedTailTurnId), [virtualItems, displayedTailTurnId]); diff --git a/src/web-ui/src/flow_chat/components/modern/flowItemRhythm.test.ts b/src/web-ui/src/flow_chat/components/modern/flowItemRhythm.test.ts new file mode 100644 index 0000000000..865ee91a4b --- /dev/null +++ b/src/web-ui/src/flow_chat/components/modern/flowItemRhythm.test.ts @@ -0,0 +1,38 @@ +// @vitest-environment jsdom +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +const readSource = (relativePath: string) => readFileSync(new URL(relativePath, import.meta.url), 'utf8'); +const source = readSource('../../../../../../design-system/packages/ui/src/flow-chat/conversation/FlowItemRhythm.css'); +const selector = source.split('flex: 0 0 100%;')[0].split('}').at(-1)!.split('{')[0].trim(); +const previous = `${selector.slice(0, selector.indexOf('> :where('))}> *`; + +describe('mixed agent-card row composition', () => { + it.each(['data-flow-item-stack', 'explore-region__content', 'flow-group-content-segment'])( + 'preserves full-width children in %s without selecting unrelated shell nodes', stack => { + const host = document.createElement('div'); + host.innerHTML = `
+
+
Routing
+
Continuation
+
Previous attempt
+
Reasoning
+
Agent
+ + +

Text

Code
+
Collapsed collection
+
Deferred segment
+
Subagent preview
+ +
`; + const matched = new Set(host.querySelectorAll(selector)); + expect(matched).toEqual(new Set(host.querySelectorAll(previous))); + expect(matched.size).toBe(12); + expect(matched.has(host.querySelector('nav')!)).toBe(false); + host.querySelector('[data-openbitfun-tool-card]')!.remove(); + const fresh = host.cloneNode(true) as HTMLElement; + expect(fresh.querySelectorAll(selector)).toHaveLength(0); + }, + ); +}); diff --git a/src/web-ui/src/flow_chat/timeline/document.test.ts b/src/web-ui/src/flow_chat/timeline/document.test.ts index bc5276c40e..7169271041 100644 --- a/src/web-ui/src/flow_chat/timeline/document.test.ts +++ b/src/web-ui/src/flow_chat/timeline/document.test.ts @@ -23,6 +23,35 @@ const agent = (id: string, toolName = 'AgentSpawn', status: FlowToolItem['status }); describe('desktop conversation document', () => { + it('retains live reading rows when a single settled attempt omits item metadata and restores blank lines', () => { + const raw = Array.from({ length: 300 }, (_, index) => `\n\nStream paragraph ${index}: ${'Readable **text**. '.repeat(24)}` + + (index % 8 === 7 ? '\n\n```typescript\nexport const streamed = true;\n```\n' : '')).join(''); + const clean = raw.replace(/\n{3,}/g, '\n\n'); + const text = { id: 'live', type: 'text', content: clean.slice(0, clean.lastIndexOf('\n\nStream paragraph 240:')), + attemptId: 'first-attempt', attemptIndex: 1, isMarkdown: true, isStreaming: true, status: 'streaming' } as FlowItem; + const projection = new ConversationDocumentProjection(), opts = options(); + const live = projection.project([source([text])], opts).filter(row => row.timeline?.markdownSection); + const durable = { ...text, id: 'journal-text', content: raw, attemptId: undefined, attemptIndex: undefined, + isStreaming: false, status: 'completed' } as FlowItem; + const incoming = source([durable]); incoming.data.attemptCount = 1; + const settled = projection.project([incoming], opts).filter(row => row.timeline?.markdownSection); + expect(settled.slice(0, live.length).map(row => row.timeline?.key)).toEqual(live.map(row => row.timeline?.key)); + expect(settled.map(row => raw.slice(row.timeline!.markdownSection!.start, row.timeline!.markdownSection!.end)).join('')).toBe(raw); + expect(settled.every(row => row.type === 'model-round' && row.data.items[0] === durable)).toBe(true); + const reopened = new ConversationDocumentProjection().project([incoming], options()).filter(row => row.timeline?.markdownSection); + expect(reopened.map(getVirtualItemBookmarkKey)).toEqual(settled.map(getVirtualItemBookmarkKey)); + expect(settled.some((row, index) => index > 0 && row.timeline?.key !== `turn:live:markdown:${row.timeline?.markdownSection?.start}`)).toBe(true); + }); + + it.each([undefined, 2])('does not guess missing attempt identity with attempt count %s', attemptCount => { + const text = { id: 'live', type: 'text', content: 'Answer', attemptId: 'first-attempt', attemptIndex: 1, status: 'completed' } as FlowItem; + const projection = new ConversationDocumentProjection(), opts = options(); + projection.project([source([text])], opts); + const incoming = source([{ ...text, id: 'journal', attemptId: undefined, attemptIndex: undefined } as FlowItem]); + incoming.data.attemptCount = attemptCount; + expect(projection.project([incoming], opts)[0].timeline?.key).toBe('turn:journal'); + }); + it('keeps measured section keys while adopting durable narrative IDs and a missing suffix', () => { const content = 'A paragraph with some text.\n\n'.repeat(600); const thought = { id: 'thinking-live', type: 'thinking', content: 'Reasoning.\n\nMore.', status: 'completed' } as FlowItem; diff --git a/src/web-ui/src/flow_chat/timeline/document.ts b/src/web-ui/src/flow_chat/timeline/document.ts index f46c490bcb..6ae9f5a96b 100644 --- a/src/web-ui/src/flow_chat/timeline/document.ts +++ b/src/web-ui/src/flow_chat/timeline/document.ts @@ -235,7 +235,8 @@ export class ConversationDocumentProjection { && options.reader.get('navigation:whole-text', '') !== identity && !parseDeepResearchContent(text.content).hasProtocol ? markdownSections(text.content) : undefined; if (!sections) { add(kind, this.itemIdentity.key(run[0]), run, extra); return; } - sections.forEach((section, index) => add(kind, index === 0 ? this.itemIdentity.key(run[0]) : `${this.itemIdentity.key(text!)}:markdown:${section.start}`, index === 0 ? run : [text!], { + const displayOffsets = this.itemIdentity.sectionOffsets(text!, sections); + sections.forEach((section, index) => add(kind, index === 0 ? this.itemIdentity.key(run[0]) : `${this.itemIdentity.key(text!)}:markdown:${displayOffsets[index]}`, index === 0 ? run : [text!], { ...extra, first: extra.first && index === 0, last: extra.last && index === sections.length - 1, markdownSection: section, })); diff --git a/src/web-ui/src/flow_chat/timeline/timelineItemIdentity.ts b/src/web-ui/src/flow_chat/timeline/timelineItemIdentity.ts index bbedcfbb6d..d32074e66e 100644 --- a/src/web-ui/src/flow_chat/timeline/timelineItemIdentity.ts +++ b/src/web-ui/src/flow_chat/timeline/timelineItemIdentity.ts @@ -1,9 +1,14 @@ import type { FlowItem } from '../types/flow-chat'; import type { VirtualItem } from '../types/flow-chat-projection'; -function sameNarrative(previous: FlowItem, next: FlowItem): boolean { +function sameNarrative(previous: FlowItem, next: FlowItem, singleSettledAttempt: boolean): boolean { if ((previous.type !== 'text' && previous.type !== 'thinking') || next.type !== previous.type) return false; - if (previous.attemptId !== next.attemptId || previous.attemptIndex !== next.attemptIndex) return false; + const sameAttempt = previous.attemptId === next.attemptId && previous.attemptIndex === next.attemptIndex; + // Native journal reconstruction can omit item-level attempt fields. The + // settled round must prove there was only one attempt before bridging it. + const omittedFirstAttempt = singleSettledAttempt && previous.attemptIndex === 1 + && next.attemptIndex == null && !next.attemptId; + if (!sameAttempt && !omittedFirstAttempt) return false; if (!('content' in previous) || typeof previous.content !== 'string' || !('content' in next) || typeof next.content !== 'string') return false; // Live chunks coalesce blank lines; host records may retain them. A host can @@ -17,6 +22,7 @@ function sameNarrative(previous: FlowItem, next: FlowItem): boolean { export class TimelineItemIdentity { private sources = new Map(); private keys = new WeakMap(); + private sections = new WeakMap>(); /** True only when an existing object's alias changed, invalidating cached rows. */ reconcile(sources: readonly VirtualItem[]): boolean { @@ -32,13 +38,15 @@ export class TimelineItemIdentity { if (items === previous) continue; const previousById = new Map(previous?.map(item => [item.id, item])); const ids = new Set(items.map(item => item.id)); + const singleSettledAttempt = source.type === 'model-round' + && source.isTurnComplete && source.data.attemptCount === 1; // Only a one-to-one, ordered replacement inside the same source can // bridge different canonical IDs. Insertions, removals, moved IDs and // tool replacements must keep their own identity. const handoff = previous?.length === items.length && items.every((item, index) => { const before = previous[index]; return item.id === before.id && item.type === before.type - || (!ids.has(before.id) && !previousById.has(item.id) && sameNarrative(before, item)); + || (!ids.has(before.id) && !previousById.has(item.id) && sameNarrative(before, item, singleSettledAttempt)); }); items.forEach((item, index) => { const before = previousById.get(item.id) ?? (handoff ? previous![index] : undefined); @@ -47,6 +55,8 @@ export class TimelineItemIdentity { const cachedKey = this.keys.get(item); if (cachedKey !== undefined && cachedKey !== nextKey) cachedKeysChanged = true; this.keys.set(item, nextKey); + const sections = before && this.sections.get(before); + if (sections) this.sections.set(item, sections); }); } // Evicted Turns retain neither their old source bodies nor alias records. @@ -55,4 +65,23 @@ export class TimelineItemIdentity { } key(item: FlowItem): string { return this.keys.get(item) ?? item.id; } + + /** Display coordinates survive coalesced blank lines; bookmarks keep raw offsets. */ + sectionOffsets(item: FlowItem, sections: readonly { start: number }[]): number[] { + if (!('content' in item) || typeof item.content !== 'string') return sections.map(section => section.start); + let keys = this.sections.get(item); + if (!keys) { keys = new Map(); this.sections.set(item, keys); } + const runs = item.content.matchAll(/\n{3,}/g); + let run = runs.next(), removed = 0; + return sections.map(section => { + while (!run.done && run.value.index + run.value[0].length <= section.start) { + removed += run.value[0].length - 2; + run = runs.next(); + } + const normalized = section.start - removed; + const offset = keys.get(normalized) ?? section.start; + keys.set(normalized, offset); + return offset; + }); + } } diff --git a/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.test.tsx b/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.test.tsx index 1ef56b696d..4d0f165369 100644 --- a/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.test.tsx +++ b/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.test.tsx @@ -5,6 +5,89 @@ import { expect, it, vi } from 'vitest'; import { FlowChatReaderState } from './readerState'; import { useTimelineInteraction } from './useTimelineInteraction'; +it('retains interaction leases without layout reads while inactive and reconciles them on reveal', () => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true; + const host = document.createElement('div'); document.body.append(host); + const root = createRoot(host), reader = new FlowChatReaderState(), release = vi.fn(); + vi.spyOn(reader, 'holdGroup').mockReturnValue(release); + const frames = new Map(); + let nextFrame = 1, reads = 0, deliver = () => {}; + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + const id = nextFrame++; frames.set(id, callback); return id; + }); + vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id)); + vi.stubGlobal('MutationObserver', class { + constructor(callback: () => void) { deliver = callback; } + observe() {} disconnect() {} + }); + const tick = () => { const queued = [...frames.values()]; frames.clear(); queued.forEach(callback => callback(16)); }; + function View({ active }: { active: boolean }) { + const ref = useRef(null); + const pinned = useTimelineInteraction(ref, reader, () => true, undefined, undefined, active); + return
Text
; + } + try { + act(() => root.render()); + Object.defineProperties(host.firstElementChild!, { + clientHeight: { get: () => { reads++; return 800; } }, + clientWidth: { get: () => { reads++; return 600; } }, + }); + const range = document.createRange(); range.selectNodeContents(host.querySelector('.virtual-item-wrapper')!); + const selection = window.getSelection()!; selection.removeAllRanges(); selection.addRange(range); + act(() => document.dispatchEvent(new Event('selectionchange'))); + expect(host.firstElementChild?.getAttribute('data-pinned')).toBe('row'); + expect(reader.holdGroup).toHaveBeenCalledWith('group', 'reader'); + act(() => root.render()); reads = 0; + selection.removeAllRanges(); + act(() => { document.dispatchEvent(new Event('selectionchange')); deliver(); tick(); }); + expect(reads).toBe(0); expect(release).not.toHaveBeenCalled(); + expect(host.firstElementChild?.getAttribute('data-pinned')).toBe('row'); + act(() => root.render()); + expect(frames.size).toBe(1); + act(tick); + expect(reads).toBe(2); expect(release).toHaveBeenCalledTimes(1); + expect(host.firstElementChild?.getAttribute('data-pinned')).toBe(''); + } finally { act(() => root.unmount()); host.remove(); window.getSelection()?.removeAllRanges(); vi.unstubAllGlobals(); vi.restoreAllMocks(); } +}); + +it('coalesces mutation delivery without reading layout until the frame and ignores late delivery after disposal', () => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true; + const host = document.createElement('div'); document.body.append(host); + const root = createRoot(host), reader = new FlowChatReaderState(); + const frames = new Map(); + let nextFrame = 1, reads = 0, deliver = () => {}; + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + const id = nextFrame++; frames.set(id, callback); return id; + }); + vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id)); + vi.stubGlobal('MutationObserver', class { + constructor(callback: () => void) { deliver = callback; } + observe() {} disconnect() {} + }); + function View() { + const ref = useRef(null); + useTimelineInteraction(ref, reader, () => true); + return
Text
; + } + try { + act(() => root.render()); + Object.defineProperties(host.firstElementChild!, { + clientHeight: { get: () => { reads++; return 800; } }, + clientWidth: { get: () => { reads++; return 600; } }, + }); + act(() => { deliver(); deliver(); window.dispatchEvent(new Event('resize')); }); + expect(reads).toBe(0); + expect(frames.size).toBe(1); + act(() => { const queued = [...frames.values()]; frames.clear(); queued.forEach(callback => callback(16)); }); + expect(reads).toBe(2); + act(() => { deliver(); root.unmount(); }); + expect(frames.size).toBe(0); + deliver(); + expect(frames.size).toBe(0); + } finally { if (host.firstChild) act(() => root.unmount()); host.remove(); vi.unstubAllGlobals(); } +}); + it('takes reading ownership before manual disclosure, leaving automatic state changes alone', () => { globalThis.IS_REACT_ACT_ENVIRONMENT = true; const host = document.createElement('div'); document.body.append(host); diff --git a/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.ts b/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.ts index ff16595589..4245381de7 100644 --- a/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.ts +++ b/src/web-ui/src/flow_chat/timeline/useTimelineInteraction.ts @@ -11,12 +11,16 @@ export function useTimelineInteraction( isFollowing: () => boolean, rowSelector = '.virtual-item-wrapper[data-virtual-item-key]', onReaderInteraction?: (kind: TimelineReaderInteraction) => void, + isViewportActive = true, ) { const [pinnedKeys, setPinnedKeys] = useState>(() => new Set()); const followingRef = useRef(isFollowing); followingRef.current = isFollowing; const readerInteractionRef = useRef(onReaderInteraction); readerInteractionRef.current = onReaderInteraction; + const activeRef = useRef(isViewportActive); + activeRef.current = isViewportActive; + const scheduleRef = useRef<() => void>(() => {}); useEffect(() => { const scroller = scrollerRef.current; if (!scroller) return; @@ -46,7 +50,7 @@ export function useTimelineInteraction( || (field && !['Tab', 'Shift', 'Control', 'Alt', 'Meta', 'Escape'].includes(event.key))) activate(event); }; const update = () => { - if (!scroller.clientHeight || !scroller.clientWidth) return; + if (!activeRef.current || !scroller.clientHeight || !scroller.clientWidth) return; const pinned = new Set(); const rowFor = (node: Node | null) => { const element = node instanceof Element ? node : node?.parentElement; @@ -80,6 +84,7 @@ export function useTimelineInteraction( for (const group of groups) if (!holds.has(group)) holds.set(group, reader.holdGroup(group, 'reader')); }; const selectionChanged = () => { + if (!activeRef.current) return; const selection = window.getSelection(); const anchor = selection?.anchorNode; const anchorElement = anchor instanceof Element ? anchor : anchor?.parentElement; @@ -94,10 +99,14 @@ export function useTimelineInteraction( update(); }; let frame = 0; + let disposed = false; const schedule = () => { - cancelAnimationFrame(frame); - if (scroller.clientHeight && scroller.clientWidth) frame = requestAnimationFrame(update); + if (disposed || frame || !activeRef.current) return; + // Mutation delivery runs before layout. Coalesce first; update keeps the + // existing visibility and residency checks in the scheduled frame. + frame = requestAnimationFrame(() => { frame = 0; update(); }); }; + scheduleRef.current = schedule; scroller.addEventListener('scroll', schedule, { passive: true }); // Capture before React changes geometry. Programmatic completion/reveal has // no activation event and therefore keeps its existing follow ownership. @@ -116,6 +125,8 @@ export function useTimelineInteraction( mutations.observe(scroller, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-flowchat-retain-instance'] }); update(); return () => { + disposed = true; + scheduleRef.current = () => {}; cancelAnimationFrame(frame); window.removeEventListener('resize', schedule); mutations.disconnect(); scroller.removeEventListener('scroll', schedule); scroller.removeEventListener('focusin', update); scroller.removeEventListener('click', activate, true); scroller.removeEventListener('keydown', keyActivation, true); @@ -125,5 +136,8 @@ export function useTimelineInteraction( holds.forEach(release => release()); }; }, [reader, scrollerRef, rowSelector]); + useEffect(() => { + if (isViewportActive) scheduleRef.current(); + }, [isViewportActive]); return pinnedKeys; } diff --git a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.test.ts b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.test.ts index 396e531a96..3800db3ce4 100644 --- a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.test.ts +++ b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.test.ts @@ -279,3 +279,13 @@ describe('AgentAPI', () => { }); }); + + +describe('optional catalog projection', () => { + it('requests counts without changing the workspace identity or requiring them on legacy hosts', async () => { + const modes = [{ id: 'Cowork', manageableSubagentCount: 2 }]; + invokeMock.mockResolvedValueOnce(modes); + await expect(agentAPI.getAvailableModes({ workspaceId: 'remote-workspace-id', includeSubagentCounts: true })).resolves.toEqual(modes); + expect(invokeMock).toHaveBeenLastCalledWith('get_available_modes', { request: { workspaceId: 'remote-workspace-id', includeSubagentCounts: true } }); + }); +}); diff --git a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts index 7384d91976..dc6564865f 100644 --- a/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/AgentAPI.ts @@ -616,6 +616,8 @@ export interface ListBackgroundCommandActivitiesResponse { export interface ModeInfo { + /** Present when the host honored includeSubagentCounts. */ + manageableSubagentCount?: number; id: string; name: string; description: string; @@ -1752,11 +1754,14 @@ export class AgentAPI { - async getAvailableModes(request: { workspaceId?: string } = {}): Promise { + async getAvailableModes(request: { workspaceId?: string; includeSubagentCounts?: boolean } = {}): Promise { try { if (request.workspaceId !== undefined && !request.workspaceId.trim()) throw new Error('Workspace identity is unresolved'); return translateAgentIdentityFields(await invokePrepared('get_available_modes', async () => ({ - request: request.workspaceId !== undefined ? await workspaceIdRequest(request.workspaceId, 'workspacePath') : {}, + request: { + ...(request.workspaceId !== undefined ? await workspaceIdRequest(request.workspaceId, 'workspacePath') : {}), + ...(request.includeSubagentCounts ? { includeSubagentCounts: true } : {}), + }, })), 'canonical'); } catch (error) { throw createTauriCommandError('get_available_modes', error); diff --git a/src/web-ui/src/infrastructure/api/service-api/ConfigAPI.test.ts b/src/web-ui/src/infrastructure/api/service-api/ConfigAPI.test.ts index 5dd3b22748..77b5fed1e5 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ConfigAPI.test.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ConfigAPI.test.ts @@ -281,3 +281,26 @@ describe('reviewed Skill import wire compatibility', () => { expect((await new ConfigAPI().getSkillScanReport()).importOperationsVersion).toBe(3); }); }); + + +describe('versioned Agent skill summaries', () => { + beforeEach(() => { invokeMock.mockReset(); }); + it('uses one read for a supported batch projection and deduplicates mode ids', async () => { + invokeMock.mockResolvedValue({ skills: [], diagnostics: [], skillCountsVersion: 1, enabledSkillCounts: { Cowork: 3, review: 0 } }); + await expect(new ConfigAPI().getModeSkillCounts(['Cowork', 'review', 'Cowork'])).resolves.toEqual({ Cowork: 3, review: 0 }); + expect(invokeMock).toHaveBeenCalledTimes(1); + expect(invokeMock.mock.calls[0][1]).toMatchObject({ modeId: 'Cowork', includeDiagnostics: true, summaryModeIds: ['Cowork', 'review'] }); + }); + it.each([false, true])('keeps old host payloads working (diagnostics: %s)', async diagnostics => { + const skills = [{ effectiveEnabled: true }, { effectiveEnabled: false }]; + invokeMock.mockResolvedValueOnce(diagnostics ? { skills, diagnostics: [] } : skills).mockResolvedValueOnce([]); + await expect(new ConfigAPI().getModeSkillCounts(['Cowork', 'review'])).resolves.toEqual({ Cowork: 1, review: 0 }); + expect(invokeMock).toHaveBeenCalledTimes(2); + expect(invokeMock.mock.calls[1][1]).toMatchObject({ modeId: 'review' }); + }); + it('reports incomplete summaries instead of pretending their counts are zero', async () => { + invokeMock.mockResolvedValue({ skills: [], diagnostics: [], skillCountsVersion: 1, enabledSkillCounts: { Cowork: 2 } }); + await expect(new ConfigAPI().getModeSkillCounts(['Cowork', 'review'])).rejects.toThrow('Invalid Agent skill count summary'); + expect(invokeMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/web-ui/src/infrastructure/api/service-api/ConfigAPI.ts b/src/web-ui/src/infrastructure/api/service-api/ConfigAPI.ts index 248f7ba220..52f6820483 100644 --- a/src/web-ui/src/infrastructure/api/service-api/ConfigAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/ConfigAPI.ts @@ -46,6 +46,7 @@ export interface GetModeSkillConfigsParams { modeId: string; forceRefresh?: boolean; workspaceId?: string; + summaryModeIds?: string[]; } export interface SetGlobalSkillDisabledParams { @@ -433,10 +434,10 @@ export class ConfigAPI { } } - async getModeSkillScanReport({ modeId, forceRefresh, workspaceId }: GetModeSkillConfigsParams): Promise> { + async getModeSkillScanReport({ modeId, forceRefresh, workspaceId, summaryModeIds }: GetModeSkillConfigsParams): Promise> { try { const response = await invokePrepared, 'diagnosticsAvailable'>>( - 'get_mode_skill_configs', async () => (await workspaceScopedRequest({ modeId, forceRefresh, workspaceId, includeDiagnostics: true })), + 'get_mode_skill_configs', async () => (await workspaceScopedRequest({ modeId, forceRefresh, workspaceId, includeDiagnostics: true, ...(summaryModeIds ? { summaryModeIds } : {}) })), { timeout: SKILL_CONFIG_REQUEST_TIMEOUT_MS }, ); return normalizeSkillScanReport(response); @@ -445,6 +446,29 @@ export class ConfigAPI { } } + async getModeSkillCounts(modeIds: string[], workspaceId?: string): Promise> { + const scope = getActiveSurfaceScope(); + const ids = [...new Set(modeIds)]; + if (ids.length === 0) return {}; + const report = await this.getModeSkillScanReport({ modeId: ids[0], summaryModeIds: ids, workspaceId }); + scope.assertCurrent('Agent skill summaries'); + if (report.skillCountsVersion === 1) { + const counts = report.enabledSkillCounts; + if (!counts || ids.some(id => !Number.isSafeInteger(counts[id]) || counts[id] < 0)) { + throw new Error('Invalid Agent skill count summary'); + } + return counts; + } + // Legacy hosts still return the anchor mode's normal report. Its data is + // usable, and the remaining reads keep cross-version behavior intact. + const entries = await Promise.all(ids.map(async (id, index) => { + const skills = index === 0 ? report.skills : await this.getModeSkillConfigs({ modeId: id, workspaceId }); + return [id, skills.filter(skill => skill.effectiveEnabled).length] as const; + })); + scope.assertCurrent('Agent skill summaries'); + return Object.fromEntries(entries); + } + async getGlobalSkillSettings(workspaceId?: string): Promise { try { return await invokePrepared('get_global_skill_settings', async () => (workspaceId !== undefined ? { request: await workspaceScopedRequest({ workspaceId }) } : undefined)); diff --git a/src/web-ui/src/infrastructure/config/types/index.ts b/src/web-ui/src/infrastructure/config/types/index.ts index 3bb6aae862..27938e7ae5 100644 --- a/src/web-ui/src/infrastructure/config/types/index.ts +++ b/src/web-ui/src/infrastructure/config/types/index.ts @@ -606,6 +606,9 @@ export interface SkillScanDiagnostic { } export interface SkillScanReport { + /** Optional projection; absent on hosts that only support individual reads. */ + skillCountsVersion?: number; + enabledSkillCounts?: Record; /** Negotiated host support for durable external copies and identity-checked undo. */ importOperationsVersion?: number; skills: T[]; diff --git a/src/web-ui/src/infrastructure/markdown/markdownSections.test.ts b/src/web-ui/src/infrastructure/markdown/markdownSections.test.ts index 4fc1148802..5497dbf6a2 100644 --- a/src/web-ui/src/infrastructure/markdown/markdownSections.test.ts +++ b/src/web-ui/src/infrastructure/markdown/markdownSections.test.ts @@ -10,6 +10,16 @@ const clean = (value: unknown): unknown => JSON.parse(JSON.stringify(value, (key const prefix = ('A paragraph with **bold**, `inline`, [link](https://example.org) and Unicode δΈ­ζ–‡ πŸ‘©πŸ½β€πŸ’».\n\n').repeat(170); describe('Markdown presentation sections', () => { + it('keeps the same semantic boundaries when journal blank lines cross the section budget', () => { + const source = Array.from({ length: 40 }, (_, index) => `Paragraph ${index}: ${'x'.repeat(970)}\n\n\n\n`).join(''); + const normalized = source.replace(/\n{3,}/g, '\n\n'); + const slices = markdownSections(source).map(section => source.slice(section.start, section.end)); + expect(slices.join('')).toBe(source); + expect(slices.map(slice => slice.replace(/\n{3,}/g, '\n\n'))) + .toEqual(markdownSections(normalized).map(section => normalized.slice(section.start, section.end))); + expect(clean(slices.flatMap(slice => parser.parse(slice).children))).toEqual(clean(parser.parse(source).children)); + }); + it.each(['\n', '\r\n', '\r'])('keeps complete semantic blocks and exact source with %j line endings', newline => { const document = (prefix + [ '# Heading\n\nSetext heading\n---\n\n', diff --git a/src/web-ui/src/infrastructure/markdown/markdownSections.ts b/src/web-ui/src/infrastructure/markdown/markdownSections.ts index e4eee487c8..2c9aed201d 100644 --- a/src/web-ui/src/infrastructure/markdown/markdownSections.ts +++ b/src/web-ui/src/infrastructure/markdown/markdownSections.ts @@ -37,8 +37,20 @@ export function markdownSections(source: string): readonly MarkdownSection[] { const starts = tokens.filter(token => token.level === 0 && token.map && token.nesting !== -1) .map(token => offsets[token.map![0]]).filter((value): value is number => value !== undefined); const boundaries = [0]; + // Streaming coalesces blank lines; journal records retain the original + // source. Budget in the same coordinates while returning exact raw ranges. + const blankRuns = source.matchAll(/\n{3,}/g); + let blankRun = blankRuns.next(), removed = 0, normalizedBoundary = 0; for (const start of starts) { - if (start - boundaries[boundaries.length - 1] >= SECTION_CHARS) boundaries.push(start); + while (!blankRun.done && blankRun.value.index + blankRun.value[0].length <= start) { + removed += blankRun.value[0].length - 2; + blankRun = blankRuns.next(); + } + const normalizedStart = start - removed; + if (normalizedStart - normalizedBoundary >= SECTION_CHARS) { + boundaries.push(start); + normalizedBoundary = normalizedStart; + } } sections = boundaries.map((start, index) => ({ start, end: boundaries[index + 1] ?? source.length })); } diff --git a/src/web-ui/src/tools/editor/AGENTS.md b/src/web-ui/src/tools/editor/AGENTS.md index 90481b841f..6db4be5ebf 100644 --- a/src/web-ui/src/tools/editor/AGENTS.md +++ b/src/web-ui/src/tools/editor/AGENTS.md @@ -37,6 +37,11 @@ This directory follows `src/web-ui/AGENTS.md`. ## Focused verification +During first Monaco creation, resolve computed typography after asynchronous +configuration/library loading and before model/view writes. Keep late configuration +updates and retained document/view state; repeated style reads across those writes +can synchronously lay out the surrounding workbench. + Document-backed code editors may suspend inactive Monaco views after 30 seconds; at most three inactive views stay warm across hosts. Visible views and active IME composition are protected. Find/replace widgets and nonempty queries also keep diff --git a/src/web-ui/src/tools/editor/components/CodeEditor.tsx b/src/web-ui/src/tools/editor/components/CodeEditor.tsx index f17961b5cf..254479a193 100644 --- a/src/web-ui/src/tools/editor/components/CodeEditor.tsx +++ b/src/web-ui/src/tools/editor/components/CodeEditor.tsx @@ -676,12 +676,12 @@ const CodeEditor: React.FC = ({ } let createFontSize = DEFAULT_EDITOR_FONT_SIZE; - let createFontFamily = resolveEditorFontFamily(editorConfigRuntimeRef.current.font_family); + let createFontFamilyOption = editorConfigRuntimeRef.current.font_family; let createFontWeight = editorConfigRuntimeRef.current.font_weight || DEFAULT_EDITOR_FONT_WEIGHT; let createLineHeight = 0; const applyFontConfig = (c: Partial) => { createFontSize = c.font_size ?? DEFAULT_EDITOR_FONT_SIZE; - createFontFamily = resolveEditorFontFamily(c.font_family); + createFontFamilyOption = c.font_family; createFontWeight = c.font_weight || createFontWeight; createLineHeight = c.line_height ? Math.round(createFontSize * c.line_height) : 0; }; @@ -698,6 +698,12 @@ const CodeEditor: React.FC = ({ const monacoRuntime = await monacoInitManager.initialize(); if (cancelled) return; + // Resolve typography together after async configuration/library loading, + // before model/view writes. Reading it on both sides of those writes + // repeatedly flushed the entire workbench during first editor creation. + const createFontFamily = resolveEditorFontFamily(createFontFamilyOption); + const createInlayFontFamily = resolveEditorFontFamily(); + model = monacoModelManager.getOrCreateModel( filePath, detectedLanguage, @@ -773,7 +779,7 @@ const CodeEditor: React.FC = ({ inlayHints: { enabled: initialLargeFileMode ? 'off' : 'on', fontSize: DEFAULT_EDITOR_INLAY_FONT_SIZE, - fontFamily: resolveEditorFontFamily(), + fontFamily: createInlayFontFamily, padding: false }, diff --git a/src/web-ui/src/tools/generative-ui/AGENTS.md b/src/web-ui/src/tools/generative-ui/AGENTS.md index d2de4911ed..414c8b7a5b 100644 --- a/src/web-ui/src/tools/generative-ui/AGENTS.md +++ b/src/web-ui/src/tools/generative-ui/AGENTS.md @@ -46,6 +46,17 @@ Run from repository root: pnpm --dir src/web-ui exec node scripts/run-vitest.mjs run src/tools/generative-ui src/tools/generative-widget/GenerativeWidgetPanel.test.tsx src/flow_chat/utils/generativeWidgetProjection.test.ts src/flow_chat/services/flow-chat-manager/PersistenceModule.test.ts src/flow_chat/services/FlowChatManager.test.ts --maxWorkers=50% pnpm run check:web +For globally loaded component spacing styles, use the focused selector contract: + + pnpm --dir src/web-ui exec node scripts/run-vitest.mjs run src/tools/generative-ui/genUISpacing.test.ts --maxWorkers=2 + +Keep element-child gap matching and selector specificity stable. Universal sibling +rules in these styles can invalidate unrelated FlowChat rows even when no GenUI +document is open. Use native invalidation/Selector Stats evidence to locate a +hotspot, then ordinary traces to verify the gain; matching counts alone are not +performance evidence. Preserve hidden-child and nested-stack spacing when changing +the selector or considering layout gap. + For shared schema or tool changes: cargo test --locked -p openbitfun-product-domains --no-default-features --lib generative_ui diff --git a/src/web-ui/src/tools/generative-ui/components/components.scss b/src/web-ui/src/tools/generative-ui/components/components.scss index 51febd1777..f308e5ea26 100644 --- a/src/web-ui/src/tools/generative-ui/components/components.scss +++ b/src/web-ui/src/tools/generative-ui/components/components.scss @@ -20,7 +20,10 @@ .gen-ui-oi-col, .gen-ui-oi-box { display: flex; flex-direction: column; min-width: 0; } .gen-ui-oi-col { gap: 24px; } .gen-ui-oi-col.gen-ui-oi-flow, .gen-ui-oi-card.gen-ui-oi-flow { gap: 0; } -.gen-ui-oi-flow > * + * { margin-top: 24px; } +// These globally loaded rules must not register universal sibling invalidation +// for unrelated transcript rows. Element-child order preserves the exact gap, +// including hidden children and text nodes, without changing the flex layout. +.gen-ui-oi-flow > :where(:not(:first-child)) { margin-top: 24px; } .gen-ui-oi-row { display: flex; flex-direction: row; align-items: center; gap: 8px; min-width: 0; } .gen-ui-oi-row > *, .gen-ui-oi-grid > *, .gen-ui-oi-card > * { min-width: 0; } .gen-ui-oi-grid { display: grid; min-width: 0; } @@ -39,7 +42,7 @@ .gen-ui-oi-caption { margin: 0; color: var(--openbitfun-color-content-secondary); font-size: var(--openbitfun-type-body-xs-font-size); line-height: var(--openbitfun-type-body-md-line-height); overflow-wrap: anywhere; }.gen-ui-oi-label { color: var(--openbitfun-color-content-primary); font-size: var(--openbitfun-type-body-sm-font-size); line-height: var(--openbitfun-type-body-sm-line-height); font-weight: var(--openbitfun-type-label-selected-font-weight); } .gen-ui-oi-badge { display: inline-flex; align-items: center; align-self: flex-start; gap: 5px; width: fit-content; max-width: 100%; min-height: 26px; padding: 3px 10px; border-radius: 999px; background: color-mix(in srgb, var(--openbitfun-color-content-primary) 8%, transparent); color: var(--openbitfun-color-content-primary); font-size: var(--openbitfun-type-body-sm-font-size); line-height: 18px; font-weight: var(--openbitfun-type-label-selected-font-weight); white-space: nowrap; }.gen-ui-oi-badge-info { background: color-mix(in srgb, var(--openbitfun-color-status-info-content) 12%, transparent); color: var(--openbitfun-color-status-info-content); }.gen-ui-oi-badge-success { background: color-mix(in srgb, var(--openbitfun-color-status-success-content) 12%, transparent); color: var(--openbitfun-color-status-success-content); }.gen-ui-oi-badge-warning { background: color-mix(in srgb, var(--openbitfun-color-status-warning-content) 12%, transparent); color: var(--openbitfun-color-status-warning-content); }.gen-ui-oi-badge-danger { background: color-mix(in srgb, var(--openbitfun-color-status-danger-content) 12%, transparent); color: var(--openbitfun-color-status-danger-content); }.gen-ui-oi-badge-purple { color: var(--openbitfun-color-accent-default); }.gen-ui-oi-badge-pink { color: var(--openbitfun-color-accent-default); } .gen-ui-oi-link { color: inherit; text-decoration: underline; text-decoration-color: var(--openbitfun-color-border-strong); text-underline-offset: 3px; }.gen-ui-oi-link:hover { text-decoration-color: currentColor; } -.gen-ui-oi-markdown { display: flex; flex-direction: column; min-width: 0; font-size: var(--openbitfun-type-body-md-font-size); line-height: var(--openbitfun-type-body-md-line-height); overflow-wrap: anywhere; }.gen-ui-oi-markdown > * { margin: 0; }.gen-ui-oi-markdown > * + * { margin-top: 12px; }.gen-ui-oi-markdown ul, .gen-ui-oi-markdown ol { padding-inline-start: 1.4em; display: flex; flex-direction: column; gap: 6px; }.gen-ui-oi-markdown blockquote { padding: 12px 16px; border-inline-start: 3px solid var(--openbitfun-color-border-default); border-radius: 0 12px 12px 0; background: var(--openbitfun-color-surface-panel); } +.gen-ui-oi-markdown { display: flex; flex-direction: column; min-width: 0; font-size: var(--openbitfun-type-body-md-font-size); line-height: var(--openbitfun-type-body-md-line-height); overflow-wrap: anywhere; }.gen-ui-oi-markdown > * { margin: 0; }.gen-ui-oi-markdown > :where(:not(:first-child)) { margin-top: 12px; }.gen-ui-oi-markdown ul, .gen-ui-oi-markdown ol { padding-inline-start: 1.4em; display: flex; flex-direction: column; gap: 6px; }.gen-ui-oi-markdown blockquote { padding: 12px 16px; border-inline-start: 3px solid var(--openbitfun-color-border-default); border-radius: 0 12px 12px 0; background: var(--openbitfun-color-surface-panel); } .gen-ui-oi-quote { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 14px 16px; border-inline-start: 3px solid var(--openbitfun-color-content-primary); border-radius: 0 12px 12px 0; background: var(--openbitfun-color-surface-panel); }.gen-ui-oi-quote > p { margin: 0; font-size: var(--openbitfun-type-body-md-font-size); line-height: var(--openbitfun-type-body-md-line-height); }.gen-ui-oi-quote > cite { color: var(--openbitfun-color-content-secondary); font-size: var(--openbitfun-type-body-sm-font-size); font-style: normal; } .gen-ui-oi-code-block { min-width: 0; overflow: hidden; border: 1px solid var(--openbitfun-color-border-default); border-radius: var(--openbitfun-radius-lg); background: var(--openbitfun-color-surface-panel); }.gen-ui-oi-code-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 6px 8px 6px 14px; border-bottom: 1px solid var(--openbitfun-color-border-default); color: var(--openbitfun-color-content-secondary); font-size: var(--openbitfun-type-body-xs-font-size); }.gen-ui-oi-code-head button { padding: 4px 8px; border: 0; border-radius: 6px; background: transparent; color: inherit; cursor: pointer; }.gen-ui-oi-code-head button:hover { background: color-mix(in srgb, var(--openbitfun-color-content-primary) 8%, transparent); color: var(--openbitfun-color-content-primary); }.gen-ui-oi-code { display: block; overflow: auto; margin: 0; padding: 14px 16px; font-family: var(--openbitfun-type-code-md-font-family); font-size: var(--openbitfun-type-code-md-font-size); line-height: var(--openbitfun-type-code-md-line-height); }.gen-ui-oi-math { display: block; overflow: auto; padding: 4px 0; }.gen-ui-oi-math-inline { display: inline-block; } diff --git a/src/web-ui/src/tools/generative-ui/components/openui/components.css b/src/web-ui/src/tools/generative-ui/components/openui/components.css index 6470c3439f..4f83697e9e 100644 --- a/src/web-ui/src/tools/generative-ui/components/openui/components.css +++ b/src/web-ui/src/tools/generative-ui/components/openui/components.css @@ -105,7 +105,7 @@ blocks, more air above a heading than below it, lists tucked under their lead-in. */ .iui-markdown { display: flex; flex-direction: column; min-width: 0; font-size: 16px; line-height: 1.65; overflow-wrap: anywhere; } .iui-markdown > * { margin: 0; } -.iui-markdown > * + * { margin-top: 12px; } +.iui-markdown > :where(:not(:first-child)) { margin-top: 12px; } .iui-markdown > p + :is(ul, ol) { margin-top: 6px; } .iui-markdown > * + .iui-md-h { margin-top: 26px; } .iui-markdown > .iui-md-h + * { margin-top: 8px; } @@ -367,9 +367,11 @@ to the block it introduces. - inner (8px): a title to its own subtitle, tags or paragraph; tight (4px) for an eyebrow caption above a title. */ -.iui-flow > * + * { margin-top: var(--iui-space-section); } +/* Preserve element-child spacing without invalidating unrelated virtual rows + whenever this globally loaded stylesheet sees sibling insertion/removal. */ +.iui-flow > :where(:not(:first-child)) { margin-top: var(--iui-space-section); } .iui-flow > .iui-title + * { margin-top: var(--iui-space-group); } -:is(.iui-flow .iui-flow, .iui-card.iui-flow) > * + * { margin-top: var(--iui-space-group); } +:is(.iui-flow .iui-flow, .iui-card.iui-flow) > :where(:not(:first-child)) { margin-top: var(--iui-space-group); } .iui-flow > .iui-text + .iui-text { margin-top: var(--iui-space-group); } .iui-flow > .iui-title + :is(.iui-text, .iui-caption, .iui-row:has(> .iui-badge)) { margin-top: var(--iui-space-inner); } .iui-flow > .iui-caption + .iui-title { margin-top: var(--iui-space-tight); } diff --git a/src/web-ui/src/tools/generative-ui/genUISpacing.test.ts b/src/web-ui/src/tools/generative-ui/genUISpacing.test.ts new file mode 100644 index 0000000000..0d080a3084 --- /dev/null +++ b/src/web-ui/src/tools/generative-ui/genUISpacing.test.ts @@ -0,0 +1,41 @@ +// @vitest-environment jsdom +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +const readSource = (relativePath: string) => readFileSync(new URL(relativePath, import.meta.url), 'utf8'); +const sheets = [readSource('./components/components.scss'), readSource('./components/openui/components.css')]; + +describe('generated content spacing selector equivalence', () => { + it('keeps gaps on the same mixed element children through insertion, hiding and removal', () => { + const host = document.createElement('div'); + host.innerHTML = ` +
text +
B
+

Heading

text

Paragraph

  • List
Code
Cell
+
+
Title

Text

+
+
A

B
+

Prose

Heading

  • A
Quote
Raw block
+
`; + const rules = sheets.flatMap(source => [...source.matchAll(/([^{}\n]+)\{\s*margin-top:\s*([^;}]+);?\s*\}/g)]) + .filter(match => match[1].includes(':where(:not(:first-child))')); + expect(rules).toHaveLength(5); + const verify = () => { + // Query a fresh tree: jsdom caches structural-pseudo matches across + // queries on mutated nested stacks. Native mutation coverage is separate. + const snapshot = host.cloneNode(true) as HTMLElement; + for (const [, selector] of rules) { + const legacy = selector.replace('> :where(:not(:first-child))', '> * + *'); + expect(new Set(snapshot.querySelectorAll(selector.trim()))).toEqual(new Set(snapshot.querySelectorAll(legacy.trim()))); + } + }; + verify(); + for (const parent of host.querySelectorAll('.iui-flow, .gen-ui-oi-flow, .iui-markdown, .gen-ui-oi-markdown')) { + const node = document.createElement('aside'); + parent.prepend(node); verify(); + node.hidden = true; verify(); + node.remove(); verify(); + } + }); +});