From 5e973e122a05ebe159727931502441368213a704 Mon Sep 17 00:00:00 2001 From: GCWing Date: Mon, 9 Nov 2026 11:18:41 +0800 Subject: [PATCH] Improve session history and workspace navigation --- docs/interactive-capabilities/README.md | 4 +- .../technical/tauri-command-map.json | 22 +- src/apps/cli/src/peer_host/commands/git.rs | 12 ++ src/apps/cli/src/peer_host/commands/mod.rs | 2 + src/apps/desktop/src/api/git_api.rs | 75 ++++++- src/apps/desktop/src/lib.rs | 1 + .../core/src/agentic/persistence/manager.rs | 196 ++++++++++++------ .../persistence/manager/turn_window_index.rs | 164 +++++++++++++++ .../generated/remote-surface-registry.json | 22 +- .../src/remote_surface/capabilities.rs | 6 + .../src/remote_surface/table.rs | 1 + .../services/services-integrations/AGENTS.md | 4 + .../services-integrations/src/git/service.rs | 22 +- .../src/remote_ssh/mod.rs | 4 +- .../src/remote_ssh/remote_git.rs | 21 ++ .../tests/git_contracts.rs | 77 +++++++ .../interactive-capabilities/catalog.json | 1 + .../sections/devices/CatalogSessionMenu.tsx | 6 +- .../sections/devices/openOnDevice.test.ts | 10 + .../NavPanel/sections/devices/openOnDevice.ts | 27 +-- .../ArchivedSessionMenuItems.test.tsx | 11 +- .../sessions/ArchivedSessionMenuItems.tsx | 2 +- .../sessions/SessionDeleteMenuItem.test.tsx | 43 +++- .../sections/sessions/SessionsSection.scss | 1 + .../sections/sessions/SessionsSection.tsx | 10 +- .../sections/sessions/sessionRowActions.ts | 12 ++ .../src/app/components/panels/FilesPanel.tsx | 25 ++- .../ProjectDirectoriesSection.test.tsx | 22 +- .../ProjectDirectoriesSection.tsx | 7 +- .../ProjectResourcesScene.test.tsx | 32 ++- .../ProjectResourcesScene.tsx | 12 +- .../app/scenes/project-resources/README.md | 2 +- .../app/scenes/workspace-resources/README.md | 7 +- .../WorkspaceResourcePanel.test.tsx | 63 ++++++ .../WorkspaceResourcePanel.tsx | 45 ++-- src/web-ui/src/app/stores/navSceneStore.ts | 7 +- .../components/WelcomePanel.appearance.ts | 1 + .../src/flow_chat/components/WelcomePanel.css | 11 + .../components/WelcomePanel.test.tsx | 30 ++- .../src/flow_chat/components/WelcomePanel.tsx | 15 +- .../components/WelcomeWorkspaceChanges.tsx | 21 ++ ...FlowChatContainer.history-restore.test.tsx | 1 + .../modern/ModernFlowChatContainer.tsx | 13 +- .../src/flow_chat/store/FlowChatStore.test.ts | 12 +- .../src/flow_chat/store/FlowChatStore.ts | 16 +- .../api/generated/remoteSurface.ts | 5 +- .../infrastructure/api/service-api/GitAPI.ts | 6 + .../peer-device/PeerConnectionManager.ts | 3 + src/web-ui/src/locales/en-US/common.json | 3 +- src/web-ui/src/locales/en-US/flow-chat.json | 2 + .../src/locales/en-US/panels/files.json | 3 +- .../en-US/scenes/project-resources.json | 1 - src/web-ui/src/locales/zh-CN/common.json | 3 +- src/web-ui/src/locales/zh-CN/flow-chat.json | 2 + .../src/locales/zh-CN/panels/files.json | 3 +- .../zh-CN/scenes/project-resources.json | 1 - src/web-ui/src/locales/zh-TW/common.json | 3 +- src/web-ui/src/locales/zh-TW/flow-chat.json | 2 + .../src/locales/zh-TW/panels/files.json | 3 +- .../zh-TW/scenes/project-resources.json | 1 - .../controller/ExplorerController.test.ts | 22 ++ .../controller/ExplorerController.ts | 4 +- .../git/hooks/useTrackedChangeCount.test.tsx | 135 ++++++++++++ .../tools/git/hooks/useTrackedChangeCount.ts | 113 ++++++++++ 64 files changed, 1232 insertions(+), 181 deletions(-) create mode 100644 src/crates/assembly/core/src/agentic/persistence/manager/turn_window_index.rs create mode 100644 src/web-ui/src/app/scenes/workspace-resources/WorkspaceResourcePanel.test.tsx create mode 100644 src/web-ui/src/flow_chat/components/WelcomeWorkspaceChanges.tsx create mode 100644 src/web-ui/src/tools/git/hooks/useTrackedChangeCount.test.tsx create mode 100644 src/web-ui/src/tools/git/hooks/useTrackedChangeCount.ts diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index 6d7d04187f..767f94ec1a 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -27,9 +27,9 @@ OpenBitFun Playbook currently contains **22 features**, **22 settings pages**, a - Generated per-item interaction audit: `docs/interactive-capabilities/technical/product-control-open-audit.json` - Generated low-level audit map: `docs/interactive-capabilities/technical/tauri-command-map.json` -说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **705** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 +说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **706** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 -Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **705** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes. +Docs, website, search, and agents see only features, settings, and documented sub-capabilities. Every sub-capability must reference a registered Tauri command or a resolvable source marker; evidence is stripped from public projections. The **706** Tauri commands remain implementation-audit evidence only. Product UI interaction sources are scanned and validated during generation and checks, but are not stored as a versioned snapshot that churns with ordinary UI changes. ## 控制边界 / Control boundary diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 2501934ccc..b17a2f36a8 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -2,10 +2,10 @@ "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", "catalogDigest": "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575", - "commandCount": 705, + "commandCount": 706, "coverage": { - "commandCount": 705, - "documentedCommandCount": 644, + "commandCount": 706, + "documentedCommandCount": 645, "implementationCommandCount": 61, "implementationDigest": "fdb6f78b009b95270d26834349aade36e0987553167f325a9c674a085b876a2d" }, @@ -4806,6 +4806,22 @@ "signature": "fn git_get_status( state: State<'_, AppState>, mut request: GitRepositoryRequest, ) -> Result", "remoteWorkspacePolicy": "RemoteRouted" }, + { + "id": "git_get_tracked_change_count", + "moduleId": "git", + "capabilityId": "feature.git", + "capabilityIds": [ + "feature.git" + ], + "documentedItemIds": [ + "feature.git:status-diff" + ], + "visibility": "documented", + "rustPath": "git_get_tracked_change_count", + "sourceFile": "src/apps/desktop/src/api/git_api.rs", + "signature": "fn git_get_tracked_change_count( state: State<'_, AppState>, request: GitTrackedChangeCountRequest, ) -> Result, String>", + "remoteWorkspacePolicy": "RemoteRouted" + }, { "id": "git_is_repository", "moduleId": "git", diff --git a/src/apps/cli/src/peer_host/commands/git.rs b/src/apps/cli/src/peer_host/commands/git.rs index b690240cb1..4c2d479bba 100644 --- a/src/apps/cli/src/peer_host/commands/git.rs +++ b/src/apps/cli/src/peer_host/commands/git.rs @@ -50,6 +50,11 @@ fn resolved_repository_path( /// repository so an SSH workspace can never fall back to a same-named local path. pub(crate) async fn read(command: &str, args: &Value) -> Result { let request = request_value(args); + if command == "git_get_tracked_change_count" + && optional_string(request, "workspaceId").is_none() + { + return Err("Workspace ID is required".into()); + } let path = repository_path_for_workspace(request).await?; read_at_path(command, &path, request).await } @@ -80,6 +85,9 @@ async fn read_at_path(command: &str, path: &str, request: &Value) -> Result git_result(command, GitService::get_status(path).await), + "git_get_tracked_change_count" => { + git_result(command, GitService::get_tracked_change_count(path).await) + } "git_get_branches" | "git_get_enhanced_branches" => { let options: BranchOptions = serde_json::from_value(request.clone()) .map_err(|error| format!("Invalid Git branch request: {error}"))?; @@ -211,6 +219,10 @@ mod tests { .unwrap(); assert_eq!(status["unstaged"][0]["path"], "tracked.txt"); assert_eq!(status["untracked"][0], "untracked.txt"); + let count = read_at_path("git_get_tracked_change_count", path, &json!({})) + .await + .unwrap(); + assert_eq!(count, 1); for command in ["git_get_branches", "git_get_enhanced_branches"] { let branches = read_at_path(command, path, &json!({"includeRemote": false})) .await diff --git a/src/apps/cli/src/peer_host/commands/mod.rs b/src/apps/cli/src/peer_host/commands/mod.rs index e3466d012f..6432c20ef7 100644 --- a/src/apps/cli/src/peer_host/commands/mod.rs +++ b/src/apps/cli/src/peer_host/commands/mod.rs @@ -224,6 +224,7 @@ pub(crate) fn dispatch<'a>( "git_get_repository" | "git_get_repository_basic" | "git_get_status" + | "git_get_tracked_change_count" | "git_get_branches" | "git_get_enhanced_branches" | "git_get_commits" @@ -374,6 +375,7 @@ pub(crate) const HANDLED_COMMANDS: &[&str] = &[ "git_get_repository", "git_get_repository_basic", "git_get_status", + "git_get_tracked_change_count", "git_get_branches", "git_get_enhanced_branches", "git_get_commits", diff --git a/src/apps/desktop/src/api/git_api.rs b/src/apps/desktop/src/api/git_api.rs index 29f0133ebe..a68ea86ca4 100644 --- a/src/apps/desktop/src/api/git_api.rs +++ b/src/apps/desktop/src/api/git_api.rs @@ -16,7 +16,12 @@ use openbitfun_core::service::git::{ use openbitfun_core::service::remote_ssh::{ build_remote_git_command as build_remote_git_command_shared, normalize_remote_workspace_path, }; -use openbitfun_core::service::workspace::WorktreeTopologyFreshness; +use openbitfun_core::service::workspace::{ + WorkspaceInfo, WorkspaceKind, WorktreeTopologyFreshness, +}; +use openbitfun_services_integrations::remote_ssh::{ + build_remote_git_tracked_change_count_command, SSHCommandOptions, +}; use serde::{Deserialize, Serialize}; use std::time::Instant; use tauri::State; @@ -67,7 +72,14 @@ async fn resolve_remote_git_target( .require_workspace(workspace_id) .await .map_err(|e| e.to_string())?; - if workspace.workspace_kind != openbitfun_core::service::workspace::WorkspaceKind::Remote { + remote_git_target_for_workspace(&workspace, repository_path) +} + +fn remote_git_target_for_workspace( + workspace: &WorkspaceInfo, + repository_path: &str, +) -> Result, String> { + if workspace.workspace_kind != WorkspaceKind::Remote { return Ok(None); } let connection_id = workspace @@ -431,6 +443,12 @@ pub struct GitRepositoryRequest { pub repository_path: String, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GitTrackedChangeCountRequest { + pub workspace_id: String, +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GitResolveRevisionRequest { @@ -997,6 +1015,59 @@ pub async fn git_resolve_revision( .map_err(|e| git_error_message("Failed to resolve Git revision", &e)) } +#[tauri::command] +pub async fn git_get_tracked_change_count( + state: State<'_, AppState>, + request: GitTrackedChangeCountRequest, +) -> Result, String> { + let workspace = openbitfun_core::service::workspace::get_global_workspace_service() + .ok_or("Workspace service is unavailable")? + .require_workspace(&request.workspace_id) + .await + .map_err(|e| e.to_string())?; + if let Some(target) = + remote_git_target_for_workspace(&workspace, &workspace.root_path.to_string_lossy())? + { + let manager = state + .get_ssh_manager_async() + .await + .map_err(|e| e.to_string())?; + let command = build_remote_git_tracked_change_count_command(&target.repository_path); + let output = manager + .execute_command_with_options( + &target.connection_id, + &command, + SSHCommandOptions { + timeout_ms: Some(5_000), + ..Default::default() + }, + ) + .await + .map_err(|e| e.to_string())?; + if output.timed_out || output.interrupted { + return Err("Remote Git change count was interrupted".into()); + } + if output.exit_code != 0 { + if trust::is_missing_repository_message(&output.stderr) { + return Ok(None); + } + return Err(remote_git_error_message( + &target.repository_path, + format!("Failed to count tracked changes: {}", output.stderr.trim()), + )); + } + return output + .stdout + .trim() + .parse() + .map(Some) + .map_err(|_| "Invalid remote Git change count".into()); + } + GitService::get_tracked_change_count(&workspace.root_path) + .await + .map_err(|error| git_error_message("Failed to count tracked changes", &error)) +} + #[tauri::command] pub async fn git_get_status( state: State<'_, AppState>, diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index b10e3f36c4..98bc1ced3d 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -1683,6 +1683,7 @@ pub async fn run() { review_platform_update_auth_token, review_platform_clear_auth_token, git_get_status, + git_get_tracked_change_count, git_get_branches, git_get_enhanced_branches, git_get_commits, diff --git a/src/crates/assembly/core/src/agentic/persistence/manager.rs b/src/crates/assembly/core/src/agentic/persistence/manager.rs index 56d3467e5b..3466c59930 100644 --- a/src/crates/assembly/core/src/agentic/persistence/manager.rs +++ b/src/crates/assembly/core/src/agentic/persistence/manager.rs @@ -7,6 +7,7 @@ mod external_history; #[cfg(feature = "external-sources")] pub(crate) use external_history::external_history_catalog; mod session_catalog; +mod turn_window_index; mod usage_context; pub(crate) use usage_context::SessionUsageContextSnapshot; @@ -72,6 +73,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use tokio::fs; use tokio::io::AsyncWriteExt; use tokio::sync::{Mutex, Semaphore}; +use turn_window_index::{TurnWindowIndex, TurnWindowIndexCache}; pub use openbitfun_services_core::session::SessionMetadataPage; @@ -574,6 +576,7 @@ pub struct PersistenceManager { path_manager: Arc, runtime_service: Arc, catalog_cache: Mutex, + turn_window_index_cache: Mutex, #[cfg(test)] fail_next_session_state_write: std::sync::Mutex>, #[cfg(test)] @@ -592,6 +595,7 @@ impl PersistenceManager { runtime_service: Arc::new(WorkspaceRuntimeService::new(path_manager.clone())), path_manager, catalog_cache: Mutex::new(session_catalog::CatalogCache::default()), + turn_window_index_cache: Mutex::new(TurnWindowIndexCache::default()), #[cfg(test)] fail_next_session_state_write: std::sync::Mutex::new(None), #[cfg(test)] @@ -3509,15 +3513,21 @@ impl PersistenceManager { self.ensure_external_session_materialized(workspace_path, session_id) .await?; let _session_write = self.lock_session_write_operation(workspace_path, session_id)?; + let persistence_lock = self + .get_session_persistence_lock(workspace_path, session_id) + .await; + let _persistence_guard = persistence_lock.lock().await; + let observed_revision = self.turn_window_revision(workspace_path, session_id).await; + let mut scanned_paths = None; let (physical_indices, can_persist_physical_projection) = match self .list_indexed_turn_paths(workspace_path, session_id) .await { Ok(paths) => { let persisted_indices = paths - .into_iter() - .map(|(index, _)| index) + .iter() + .map(|(index, _)| *index) .collect::>() .into_iter() .collect::>(); @@ -3529,6 +3539,9 @@ impl PersistenceManager { visible_total_turn_count, ); let can_persist = projected_indices == persisted_indices; + if can_persist && paths.len() == persisted_indices.len() { + scanned_paths = Some(paths); + } (projected_indices, can_persist) } Err(error) => { @@ -3555,20 +3568,36 @@ impl PersistenceManager { visible_total_turn_count, ) .await?; + let mut catalog_replaced = false; if can_persist_physical_projection && projection.physical_changed { - if let Err(error) = self + match self .write_json_atomic( &self.turn_catalog_path(workspace_path, session_id), &projection.physical, ) .await { - warn!( + Ok(()) => catalog_replaced = true, + Err(error) => warn!( "Failed to persist incrementally repaired Session Turn catalog: session_id={} error={}", session_id, error - ); + ), } } + if let (Some(paths), Some(revision)) = (scanned_paths, observed_revision.as_ref()) { + self.remember_turn_window_index( + workspace_path, + session_id, + revision, + catalog_replaced, + Arc::new(TurnWindowIndex { + paths: Arc::new(paths), + catalog: projection.physical, + needs_catalog_repair: projection.physical_changed && !catalog_replaced, + }), + ) + .await; + } Ok(projection.visible) } @@ -3668,56 +3697,57 @@ impl PersistenceManager { .await?; let _session_write = self.lock_session_write_operation(&request.workspace_path, &request.session_id)?; + let persistence_lock = self + .get_session_persistence_lock(&request.workspace_path, &request.session_id) + .await; + let _persistence_guard = persistence_lock.lock().await; let boundary_turn = self .load_session_revert_state(&request.workspace_path, &request.session_id) .await? .map(|state| state.boundary_turn); - let physical_indexed_paths = self - .list_indexed_turn_paths(&request.workspace_path, &request.session_id) + let (index, observed_revision) = self + .load_turn_window_index(&request.workspace_path, &request.session_id) .await?; - let physical_indices = physical_indexed_paths - .iter() - .map(|(index, _)| *index) - .collect::>(); - let indexed_paths = physical_indexed_paths - .into_iter() - .filter(|(index, _)| boundary_turn.is_none_or(|boundary| *index < boundary)) - .collect::>(); - let visible_indices = indexed_paths - .iter() - .map(|(index, _)| *index) - .collect::>(); - let catalog = self - .build_session_turn_catalog_projection( - &request.workspace_path, + let visible_count = boundary_turn.map_or(index.paths.len(), |boundary| { + index.paths.partition_point(|(index, _)| *index < boundary) + }); + let indexed_paths = &index.paths[..visible_count]; + let catalog = if visible_count == index.paths.len() { + Cow::Borrowed(&index.catalog) + } else { + Cow::Owned(build_turn_catalog( &request.session_id, - visible_indices.clone(), - &[], - visible_indices.len(), - ) - .await?; + index.catalog.entries[..visible_count].to_vec(), + )) + }; if request .expected_catalog_revision .as_deref() .is_some_and(|revision| revision != catalog.revision) { - return Ok(SessionTurnWindowResponse::Stale { catalog }); + return Ok(SessionTurnWindowResponse::Stale { + catalog: catalog.into_owned(), + }); } - let Some(target_ordinal) = catalog - .entries - .iter() - .position(|entry| entry.storage_turn_index == request.target_storage_turn_index) - else { - return Ok(SessionTurnWindowResponse::NotFound { catalog }); - }; + let target_ordinal = + indexed_paths.partition_point(|(index, _)| *index < request.target_storage_turn_index); + if indexed_paths.get(target_ordinal).map(|(index, _)| *index) + != Some(request.target_storage_turn_index) + { + return Ok(SessionTurnWindowResponse::NotFound { + catalog: catalog.into_owned(), + }); + } if let (Some(expected_turn_id), Some(catalog_turn_id)) = ( request.expected_turn_id.as_deref(), catalog.entries[target_ordinal].turn_id.as_deref(), ) { if expected_turn_id != catalog_turn_id { - return Ok(SessionTurnWindowResponse::Stale { catalog }); + return Ok(SessionTurnWindowResponse::Stale { + catalog: catalog.into_owned(), + }); } } @@ -3739,6 +3769,8 @@ impl PersistenceManager { if read_result.missing_turn_file_count > 0 || read_result.turns.len() != selected_indices.len() { + self.forget_turn_window_index(&request.workspace_path, &request.session_id) + .await; let refreshed_indices = self .list_indexed_turn_paths(&request.workspace_path, &request.session_id) .await? @@ -3767,27 +3799,42 @@ impl PersistenceManager { } } - let repaired_projection = self - .build_session_turn_catalog_projection_with_physical( - &request.workspace_path, - &request.session_id, - physical_indices.clone(), - &read_result.turns, - physical_indices.len(), - ) - .await?; - if repaired_projection.physical_changed { - if let Err(error) = self - .write_json_atomic( + let page_matches_catalog = read_result.turns.iter().enumerate().all(|(offset, turn)| { + let ordinal = start_ordinal + offset; + turn_catalog_entry(turn, ordinal) == index.catalog.entries[ordinal] + }); + if index.needs_catalog_repair || !page_matches_catalog { + let repaired_projection = self + .build_session_turn_catalog_projection_with_physical( + &request.workspace_path, + &request.session_id, + index.paths.iter().map(|(index, _)| *index).collect(), + &read_result.turns, + index.paths.len(), + ) + .await?; + if repaired_projection.physical_changed { + match self.write_json_atomic( &self.turn_catalog_path(&request.workspace_path, &request.session_id), &repaired_projection.physical, - ) - .await - { - warn!( - "Failed to persist Session Turn catalog metadata loaded by a window request: session_id={} start_ordinal={} end_ordinal_exclusive={} error={}", - request.session_id, start_ordinal, end_ordinal_exclusive, error - ); + ).await { + Ok(()) => { + if let Some(revision) = &observed_revision { + self.remember_turn_window_index( + &request.workspace_path, &request.session_id, revision, true, + Arc::new(TurnWindowIndex { + paths: Arc::clone(&index.paths), + catalog: repaired_projection.physical, + needs_catalog_repair: false, + }), + ).await; + } + } + Err(error) => warn!( + "Failed to persist Session Turn catalog metadata loaded by a window request: session_id={} start_ordinal={} end_ordinal_exclusive={} error={}", + request.session_id, start_ordinal, end_ordinal_exclusive, error + ), + } } } @@ -3802,7 +3849,7 @@ impl PersistenceManager { .build_session_turn_catalog_projection( &request.workspace_path, &request.session_id, - visible_indices, + indexed_paths.iter().map(|(index, _)| *index).collect(), &read_result.turns, indexed_paths.len(), ) @@ -3811,7 +3858,7 @@ impl PersistenceManager { } Ok(SessionTurnWindowResponse::Ready { - catalog_revision: catalog.revision, + catalog_revision: catalog.revision.clone(), total_turn_count: catalog.total_turn_count, start_ordinal, end_ordinal_exclusive, @@ -7316,6 +7363,10 @@ mod tests { .load_session_turn_catalog(workspace.path(), &session_id, &[], 30) .await .expect("catalog should load"); + let (initial_index, _) = manager + .load_turn_window_index(workspace.path(), &session_id) + .await + .expect("Turn window index should load"); let request = SessionTurnWindowRequest { workspace_path: workspace.path().to_path_buf(), session_id: session_id.clone(), @@ -7352,6 +7403,28 @@ mod tests { response => panic!("unexpected response: {response:?}"), } + let (reused_index, _) = manager + .load_turn_window_index(workspace.path(), &session_id) + .await + .expect("unchanged Turn window index should load"); + assert!(Arc::ptr_eq(&initial_index, &reused_index)); + + let mut repaired_catalog = initial_index.catalog.clone(); + repaired_catalog.entries[0].preview = Some("updated preview".to_string()); + manager + .write_json_atomic( + &manager.turn_catalog_path(workspace.path(), &session_id), + &repaired_catalog, + ) + .await + .expect("catalog metadata should be replaceable"); + let (updated_index, _) = manager + .load_turn_window_index(workspace.path(), &session_id) + .await + .expect("Turn window index should pick up the replacement"); + assert_eq!(updated_index.catalog, repaired_catalog); + assert!(Arc::ptr_eq(&initial_index.paths, &updated_index.paths)); + let mut stale_revision_request = request.clone(); stale_revision_request.expected_catalog_revision = Some("obsolete".to_string()); assert!(matches!( @@ -7372,6 +7445,13 @@ mod tests { SessionTurnWindowResponse::Stale { .. } )); + std::fs::remove_file(manager.turn_path(workspace.path(), &session_id, 29)) + .expect("Turn should be removable outside the index cache"); + assert!(matches!( + manager.load_session_turn_window(&request).await.unwrap(), + SessionTurnWindowResponse::Stale { catalog } if catalog.total_turn_count == 29 + )); + manager .save_session_revert_state( workspace.path(), @@ -7379,7 +7459,7 @@ mod tests { &SessionRevertState { schema_version: SESSION_REVERT_SCHEMA_VERSION, boundary_turn: 8, - original_turn_end: 30, + original_turn_end: 29, phase: SessionRevertPhase::Staged, workspace_checkpoint: Vec::new(), }, diff --git a/src/crates/assembly/core/src/agentic/persistence/manager/turn_window_index.rs b/src/crates/assembly/core/src/agentic/persistence/manager/turn_window_index.rs new file mode 100644 index 0000000000..940f70196c --- /dev/null +++ b/src/crates/assembly/core/src/agentic/persistence/manager/turn_window_index.rs @@ -0,0 +1,164 @@ +//! Versioned physical index used by native Turn window reads. + +use super::*; +use openbitfun_services_core::json_store::JsonFileRevision; +use std::collections::VecDeque; + +const MAX_INDEXES: usize = 4; +const MAX_INDEX_BYTES: u64 = 32 * 1024 * 1024; + +#[derive(Default)] +pub(super) struct TurnWindowIndexCache { + entries: VecDeque, +} + +#[derive(Clone, PartialEq, Eq)] +pub(super) struct TurnWindowRevision { + turns: Option, + catalog: Option, +} + +pub(super) struct TurnWindowIndex { + pub paths: Arc>, + pub catalog: SessionTurnCatalog, + pub needs_catalog_repair: bool, +} + +struct CachedIndex { + key: PathBuf, + revision: TurnWindowRevision, + index: Arc, + bytes: u64, +} + +impl PersistenceManager { + pub(super) async fn turn_window_revision( + &self, + workspace_path: &Path, + session_id: &str, + ) -> Option { + let turns_dir = self.turns_dir(workspace_path, session_id); + let catalog_path = self.turn_catalog_path(workspace_path, session_id); + let (turns, catalog) = tokio::try_join!( + JsonFileStore.revision(&turns_dir), + JsonFileStore.revision(&catalog_path), + ) + .ok()?; + Some(TurnWindowRevision { turns, catalog }) + } + + pub(super) async fn remember_turn_window_index( + &self, + workspace_path: &Path, + session_id: &str, + observed: &TurnWindowRevision, + catalog_replaced: bool, + index: Arc, + ) { + let Some(revision) = self.turn_window_revision(workspace_path, session_id).await else { + return; + }; + if revision.turns != observed.turns + || (!catalog_replaced && revision.catalog != observed.catalog) + { + return; + } + let bytes = revision + .catalog + .as_ref() + .map_or(0, |file| file.len.saturating_mul(2)) + .saturating_add( + index + .paths + .iter() + .map(|(_, path)| { + (std::mem::size_of::<(usize, PathBuf)>() + + std::mem::size_of::() + + path.as_os_str().len()) as u64 + }) + .sum(), + ); + if bytes > MAX_INDEX_BYTES { + return; + } + let key = self.turn_catalog_path(workspace_path, session_id); + let mut cache = self.turn_window_index_cache.lock().await; + cache.entries.retain(|entry| entry.key != key); + while cache.entries.len() >= MAX_INDEXES + || cache.entries.iter().map(|entry| entry.bytes).sum::() + bytes > MAX_INDEX_BYTES + { + cache.entries.pop_front(); + } + cache.entries.push_back(CachedIndex { + key, + revision, + index, + bytes, + }); + } + + pub(super) async fn forget_turn_window_index(&self, workspace_path: &Path, session_id: &str) { + let key = self.turn_catalog_path(workspace_path, session_id); + self.turn_window_index_cache + .lock() + .await + .entries + .retain(|entry| entry.key != key); + } + + pub(super) async fn load_turn_window_index( + &self, + workspace_path: &Path, + session_id: &str, + ) -> OpenBitFunResult<(Arc, Option)> { + let revision = self.turn_window_revision(workspace_path, session_id).await; + let key = self.turn_catalog_path(workspace_path, session_id); + let mut unchanged_paths = None; + if let Some(revision) = &revision { + let mut cache = self.turn_window_index_cache.lock().await; + if let Some(position) = cache.entries.iter().position(|entry| entry.key == key) { + let entry = cache.entries.remove(position).expect("located Turn index"); + if entry.revision == *revision { + let index = Arc::clone(&entry.index); + cache.entries.push_back(entry); + return Ok((index, Some(revision.clone()))); + } + if entry.revision.turns == revision.turns { + unchanged_paths = Some(Arc::clone(&entry.index.paths)); + } + } + } + let paths = match unchanged_paths { + Some(paths) => paths, + None => Arc::new( + self.list_indexed_turn_paths(workspace_path, session_id) + .await?, + ), + }; + let projection = self + .build_session_turn_catalog_projection_with_physical( + workspace_path, + session_id, + paths.iter().map(|(index, _)| *index).collect(), + &[], + paths.len(), + ) + .await?; + let index = Arc::new(TurnWindowIndex { + paths, + catalog: projection.physical, + needs_catalog_repair: projection.physical_changed, + }); + if let Some(revision) = &revision { + self.remember_turn_window_index( + workspace_path, + session_id, + revision, + false, + Arc::clone(&index), + ) + .await; + } + Ok((index, revision)) + } +} diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index 512cc2ec40..ad7ebde85b 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:416c934dda520065", + "digest": "fnv1a64:a7e5f2b6b738cb96", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -55,7 +55,8 @@ "user_question_response", "user_question_interaction_v1", "ssh_none_auth_v1", - "terminal_cursor_replay_v1" + "terminal_cursor_replay_v1", + "git_tracked_change_count_v1" ], "desktop": [ "gen_ui_libraries_v1", @@ -103,7 +104,8 @@ "session_reference_browse_v1", "user_question_response", "user_question_interaction_v1", - "ssh_none_auth_v1" + "ssh_none_auth_v1", + "git_tracked_change_count_v1" ], "cli": [ "model_routing_v1", @@ -131,7 +133,8 @@ "workspace_html_preview_v1", "user_question_response", "user_question_interaction_v1", - "terminal_cursor_replay_v1" + "terminal_cursor_replay_v1", + "git_tracked_change_count_v1" ] }, "operations": [ @@ -3825,6 +3828,17 @@ "kind": "handled" } }, + { + "id": "git_get_tracked_change_count", + "surface": "tauri_command", + "remoteWorkspace": "RemoteRouted", + "peer": { + "kind": "proxied" + }, + "cliPeer": { + "kind": "handled" + } + }, { "id": "git_is_repository", "surface": "tauri_command", diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index 37b89ad5d5..365225a6ba 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -121,6 +121,8 @@ pub enum PeerHostCapability { /// on the `terminal-` host stream instead of `terminal_event` fan-out. /// This selects a delivery path, so only a host using that path advertises it. TerminalCursorReplayV1, + /// `git_get_tracked_change_count` returns a workspace-scoped count. + GitTrackedChangeCountV1, } impl PeerHostCapability { @@ -173,6 +175,7 @@ impl PeerHostCapability { Self::UserQuestionInteractionV1, Self::SshNoneAuthV1, Self::TerminalCursorReplayV1, + Self::GitTrackedChangeCountV1, ]; /// The key used in the `peer_mode_ping` `capabilities` object. @@ -225,6 +228,7 @@ impl PeerHostCapability { Self::UserQuestionInteractionV1 => "user_question_interaction_v1", Self::SshNoneAuthV1 => "ssh_none_auth_v1", Self::TerminalCursorReplayV1 => "terminal_cursor_replay_v1", + Self::GitTrackedChangeCountV1 => "git_tracked_change_count_v1", } } @@ -283,6 +287,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::UserQuestionResponse, PeerHostCapability::UserQuestionInteractionV1, PeerHostCapability::SshNoneAuthV1, + PeerHostCapability::GitTrackedChangeCountV1, ]; /// The CLI peer host has no MiniApp runtime, WSL or SSH connection setup, @@ -314,6 +319,7 @@ const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::UserQuestionResponse, PeerHostCapability::UserQuestionInteractionV1, PeerHostCapability::TerminalCursorReplayV1, + PeerHostCapability::GitTrackedChangeCountV1, ]; /// The capabilities a peer host of the given kind publishes. diff --git a/src/crates/contracts/product-domains/src/remote_surface/table.rs b/src/crates/contracts/product-domains/src/remote_surface/table.rs index 52e84a6183..b5a1ef97a4 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -409,6 +409,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("git_get_repository_basic", Routed, Proxied, HANDLED), op("git_get_repository_trust", Routed, Proxied, HANDLED), op("git_get_status", Routed, Proxied, HANDLED), + op("git_get_tracked_change_count", Routed, Proxied, HANDLED), op("git_is_repository", Routed, Proxied, HANDLED), op("git_list_worktrees", Unsupported, Proxied, CLI_NOT_IMPLEMENTED), op("git_pull", Routed, Proxied, CLI_NOT_IMPLEMENTED), diff --git a/src/crates/services/services-integrations/AGENTS.md b/src/crates/services/services-integrations/AGENTS.md index f6bb5bb009..80bd5486b7 100644 --- a/src/crates/services/services-integrations/AGENTS.md +++ b/src/crates/services/services-integrations/AGENTS.md @@ -196,6 +196,7 @@ cargo test --locked -p openbitfun-services-integrations --no-default-features -- cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::host_stream:: cargo test --locked -p openbitfun-services-integrations --no-default-features --features remote-connect --lib remote_connect::host_stream_subscriber::tests:: cargo test -p openbitfun-services-integrations --no-default-features --features file-watch --test file_watch_contracts +cargo test --locked -p openbitfun-services-integrations --no-default-features --features git,remote-ssh --test git_contracts tracked_change_count cargo test --locked -p openbitfun-services-integrations --no-default-features --features workspace-search --test workspace_search_contracts cargo test --locked -p openbitfun-services-integrations --no-default-features --features deep-research --lib deep_research::tests:: cargo test --locked -p openbitfun-services-integrations --no-default-features --features web-tools --lib web_tools::tests @@ -206,6 +207,9 @@ pnpm run check:core-boundaries Other family-specific targets remain in `Cargo.toml`; add a guide command only for a recurring workflow, not to mirror every test target. +The tracked-change count fixture exercises the SSH command through a local +POSIX shell on Unix. It does not establish live SSH or container routing. + For persistent public marketplace image caching (restart/offline reuse, URL boundaries, and bounded disk storage), run: diff --git a/src/crates/services/services-integrations/src/git/service.rs b/src/crates/services/services-integrations/src/git/service.rs index a5cf63e578..f7f92dbb1d 100644 --- a/src/crates/services/services-integrations/src/git/service.rs +++ b/src/crates/services/services-integrations/src/git/service.rs @@ -2,7 +2,7 @@ use super::*; /** * Git service implementation */ -use git2::{BranchType, Commit, ErrorCode, Repository}; +use git2::{BranchType, Commit, ErrorCode, Repository, StatusOptions}; use std::io::Write; use std::path::Path; use std::time::Duration; @@ -287,6 +287,26 @@ impl GitService { .map_err(|e| GitError::CommandFailed(format!("spawn_blocking join: {e}")))? } + /// Counts changed tracked entries across the index and working tree in one scan. + pub async fn get_tracked_change_count>( + path: P, + ) -> Result, GitError> { + let path = path.as_ref().to_path_buf(); + task::spawn_blocking(move || { + let repo = match open_repository(&path) { + Ok(repo) if !repo.is_bare() => repo, + Ok(_) | Err(GitError::RepositoryNotFound(_)) => return Ok(None), + Err(error) => return Err(error), + }; + let mut options = StatusOptions::new(); + options.include_untracked(false).renames_head_to_index(true); + let statuses = repo.statuses(Some(&mut options))?; + Ok(Some(statuses.len())) + }) + .await + .map_err(|error| GitError::CommandFailed(format!("spawn_blocking join: {error}")))? + } + /// Gets repository status. pub async fn get_status>(path: P) -> Result { let path_buf = path.as_ref().to_path_buf(); diff --git a/src/crates/services/services-integrations/src/remote_ssh/mod.rs b/src/crates/services/services-integrations/src/remote_ssh/mod.rs index b9efac1515..f535e5ef06 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/mod.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/mod.rs @@ -47,7 +47,9 @@ mod ssh_config_loader; pub use file_name_search::{search_remote_file_names, RemoteFileNameSearch}; pub use paths::*; -pub use remote_git::{build_remote_git_command, shell_quote_posix}; +pub use remote_git::{ + build_remote_git_command, build_remote_git_tracked_change_count_command, shell_quote_posix, +}; #[cfg(feature = "remote-ssh-concrete")] pub use transport::{ WorkspaceProcessCompletion, WorkspaceProcessControl, WorkspaceProcessExit, diff --git a/src/crates/services/services-integrations/src/remote_ssh/remote_git.rs b/src/crates/services/services-integrations/src/remote_ssh/remote_git.rs index 5bb92546c1..b3bdb610dd 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/remote_git.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/remote_git.rs @@ -40,6 +40,27 @@ where parts.join(" ") } +/// Counts porcelain records on the workspace host. Porcelain quotes embedded +/// newlines. The trailing blank record proves Git exited successfully without +/// requiring the remote shell to support pipefail. +pub fn build_remote_git_tracked_change_count_command(repository_path: &str) -> String { + let git = build_remote_git_command( + repository_path, + [ + "--no-optional-locks", + "status", + "--porcelain=v1", + "--untracked-files=no", + "--ignore-submodules=untracked", + "--renames", + ], + ); + format!( + "(GIT_NO_LAZY_FETCH=1 GIT_TERMINAL_PROMPT=0 {git} && printf '\\n') | \ + awk '{{ complete = ($0 == \"\") }} END {{ if (!complete) exit 1; print NR - 1 }}'" + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/crates/services/services-integrations/tests/git_contracts.rs b/src/crates/services/services-integrations/tests/git_contracts.rs index 1cb573edc2..9e04ff34a4 100644 --- a/src/crates/services/services-integrations/tests/git_contracts.rs +++ b/src/crates/services/services-integrations/tests/git_contracts.rs @@ -238,6 +238,82 @@ async fn git_service_preserves_repository_status_contract() { .any(|path| path == "new-file.txt" || path == "new-file.txt/")); } +#[tokio::test] +async fn tracked_change_count_excludes_untracked_and_counts_each_file_once() { + let repo_dir = TempRepoDir::new("tracked change count"); + let root = repo_dir.path(); + assert_eq!( + GitService::get_tracked_change_count(root).await.unwrap(), + None + ); + #[cfg(all(unix, feature = "remote-ssh"))] + assert!(!run_remote_tracked_change_count(root).status.success()); + run_git(root, &["init"]); + run_git(root, &["config", "user.name", "OpenBitFun Tests"]); + run_git(root, &["config", "user.email", "tests@openbitfun.dev"]); + fs::write(root.join("both.txt"), "base\n").unwrap(); + fs::write(root.join("old.txt"), "rename me\n").unwrap(); + run_git(root, &["add", "--", "both.txt", "old.txt"]); + assert_tracked_change_count(root, 2).await; + run_git(root, &["commit", "-m", "base"]); + + fs::create_dir(root.join("untracked")).unwrap(); + fs::write(root.join("untracked/file.txt"), "ignored by count\n").unwrap(); + assert_tracked_change_count(root, 0).await; + + fs::write(root.join("both.txt"), "staged\n").unwrap(); + run_git(root, &["add", "--", "both.txt"]); + fs::write(root.join("both.txt"), "staged and unstaged\n").unwrap(); + run_git(root, &["mv", "old.txt", "renamed.txt"]); + assert_tracked_change_count(root, 2).await; + + let worktree = TempRepoDir::new("tracked-change-count-worktree"); + run_git( + root, + &[ + "worktree", + "add", + "--detach", + worktree.path().to_str().unwrap(), + ], + ); + assert_tracked_change_count(worktree.path(), 0).await; + fs::remove_file(worktree.path().join("both.txt")).unwrap(); + assert_tracked_change_count(worktree.path(), 1).await; +} + +async fn assert_tracked_change_count(root: &std::path::Path, expected: usize) { + assert_eq!( + GitService::get_tracked_change_count(root).await.unwrap(), + Some(expected) + ); + #[cfg(all(unix, feature = "remote-ssh"))] + { + let output = run_remote_tracked_change_count(root); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8_lossy(&output.stdout).trim(), + expected.to_string() + ); + } +} + +#[cfg(all(unix, feature = "remote-ssh"))] +fn run_remote_tracked_change_count(root: &std::path::Path) -> std::process::Output { + let command = + openbitfun_services_integrations::remote_ssh::build_remote_git_tracked_change_count_command( + &root.to_string_lossy(), + ); + openbitfun_services_core::process_manager::create_command("sh") + .args(["-c", &command]) + .output() + .unwrap() +} + #[tokio::test] async fn workspace_diff_port_reports_staged_unstaged_and_untracked_changes() { let repo_dir = TempRepoDir::new("workspace-diff-port"); @@ -420,6 +496,7 @@ async fn workspace_diff_port_marks_conflicts_without_projecting_an_incomplete_pa .iter() .find(|file| file.path == "conflict.txt") .expect("conflicted file"); + assert_tracked_change_count(repo_dir.path(), 1).await; assert_eq!(conflict.status, WorkspaceDiffFileStatus::Conflicted); assert!(matches!( diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 164dce4d18..2f27184a64 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -1980,6 +1980,7 @@ }, "evidence": [ "command:git_get_status", + "command:git_get_tracked_change_count", "command:git_get_changed_files", "command:git_get_diff", "command:git_get_repository", diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx b/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx index 90b5c7d923..1422b0ad24 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx @@ -100,6 +100,7 @@ export const CatalogSessionMenu: React.FC<{ const isArchived = session.persistedStatus === 'archived'; const isDispatched = isNonLocalDispatchTarget(session.config.dispatchTarget); + const sessionMutationDisabledReason = isDispatched ? t('nav.sessions.dispatchMutationUnsupported') : undefined; const capabilities = slot.isLocal ? null : peer?.attachments.find(attachment => attachment.deviceId === slot.deviceId)?.capabilities ?? null; @@ -266,6 +267,8 @@ export const CatalogSessionMenu: React.FC<{ type="button" leading={} onClick={event => run(event, { kind: 'archive' })} + disabled={Boolean(sessionMutationDisabledReason)} + title={sessionMutationDisabledReason} data-testid="nav-device-session-menu-archive" > {t('nav.sessions.archive')} @@ -275,7 +278,8 @@ export const CatalogSessionMenu: React.FC<{ sessionId={session.sessionId} testId="nav-device-session-menu-delete" label={t(session.externalHistory?.mode === 'follow' ? 'nav.sessions.removeSource' : 'nav.sessions.delete')} - description={t(session.externalHistory?.mode === 'follow' ? 'nav.sessions.removeSourceConfirmMessage' : 'nav.sessions.deleteConfirmMessage', { name: title })} + disabled={Boolean(sessionMutationDisabledReason)} + description={sessionMutationDisabledReason ?? t(session.externalHistory?.mode === 'follow' ? 'nav.sessions.removeSourceConfirmMessage' : 'nav.sessions.deleteConfirmMessage', { name: title })} onConfirm={() => { close(); runCatalogSessionAction(actions, peer, slot, session.sessionId, { kind: 'delete' }, t); diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts index 5782cedacc..b35e5707b5 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts @@ -212,6 +212,16 @@ describe('openOnDevice', () => { expect(mocks.deleteRow).not.toHaveBeenCalled(); }); + it.each(['archive', 'delete'] as const)('does not %s after switching devices during metadata promotion', async kind => { + mocks.sessions.set('s-1', seeded); + mocks.promote.mockImplementationOnce(async () => { + activateSurface(localSlot.surfaceId); + }); + await runDeviceSessionAction(peerContext(), peerSlot, 's-1', { kind }, t); + expect(mocks.archiveRow).not.toHaveBeenCalled(); + expect(mocks.deleteRow).not.toHaveBeenCalled(); + }); + it.each(['archive', 'delete'] as const)('fails %s when the rendered device no longer has the session', async kind => { await expect(runDeviceSessionAction(peerContext(), peerSlot, 'gone', { kind }, t)) .rejects.toThrow('common:nav.devices.sessionUnavailable'); diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts index 38b9dfb1c6..0c00b4d3bd 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts @@ -30,7 +30,6 @@ import { } from '../workspaces/pendingWorkspaceAction'; import { sessionSceneWorkspaceKey } from '@/app/services/sessionSceneTarget'; import type { SidebarDeviceSlot } from './useSidebarDevices'; -import type { Session } from '@/flow_chat/types/flow-chat'; import { isNonLocalDispatchTarget } from '@/features/dispatch/types'; import { sessionAPI } from '@/infrastructure/api/service-api/SessionAPI'; import { peerConnectionManager } from '@/infrastructure/peer-device/PeerConnectionManager'; @@ -195,23 +194,6 @@ export type DeviceSessionAction = | { kind: 'archive' } | { kind: 'delete' }; -/** - * Render `slot`'s device and return the session as the rendered surface knows - * it, or null when a newer switch won. A session the host no longer lists - * fails loudly instead of acting on a stale catalog row. - */ -export async function activateDeviceForSession( - peer: PeerDeviceContextValue | null, - slot: SidebarDeviceSlot, - sessionId: string, -): Promise { - if (await activateDeviceSlot(peer, slot) !== 'activated') return null; - await flowChatStore.promoteSeededSessions(sessionId); - const session = flowChatStore.getState().sessions.get(sessionId); - if (!session) throw new Error(i18nService.t('common:nav.devices.sessionUnavailable')); - return session; -} - /** Whole-session copy is negotiated per host; this machine always has it. */ function deviceCanCopySessions(slot: SidebarDeviceSlot): boolean { if (slot.isLocal) return true; @@ -232,8 +214,13 @@ export async function runDeviceSessionAction( action: DeviceSessionAction, t: SessionRowTranslate, ): Promise { - const session = await activateDeviceForSession(peer, slot, sessionId); - if (!session) return; + if (await activateDeviceSlot(peer, slot) !== 'activated') return; + const scope = getActiveSurfaceScope(); + if (scope.surfaceId !== slot.surfaceId) return; + await flowChatStore.promoteSeededSessions(sessionId); + if (!scope.isCurrent()) return; + const session = flowChatStore.getState().sessions.get(sessionId); + if (!session) throw new Error(i18nService.t('common:nav.devices.sessionUnavailable')); const dispatched = isNonLocalDispatchTarget(session.config.dispatchTarget); switch (action.kind) { case 'rename': diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.test.tsx b/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.test.tsx index 810014d43a..2d7f37c368 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.test.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.test.tsx @@ -66,11 +66,12 @@ describe('archived session row menu', () => { await act(async () => container.querySelector(`[data-testid="nav-session-menu-${action}"]`)!.click()); }; - it('offers exactly Restore and Delete for native and external archived sessions', async () => { - for (const overrides of [{}, { externalHistory: { mode: 'follow' as const }, importedSource: 'codex' as const }]) { - await render(overrides); - expect([...container.querySelectorAll('[role="menuitem"]')].map(item => item.textContent)).toEqual(['Restore', 'Delete']); - } + it('distinguishes deleting a session from removing an external source', async () => { + const menuLabels = () => [...container.querySelectorAll('[role="menuitem"]')].map(item => item.textContent); + await render(); + expect(menuLabels()).toEqual(['Restore', 'Delete session']); + await render({ externalHistory: { mode: 'follow' }, importedSource: 'codex' }); + expect(menuLabels()).toEqual(['Restore', 'Remove from OpenBitFun']); }); it('restores immediately using the owning workspace and refreshes navigation', async () => { diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.tsx b/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.tsx index b46b2fd5e6..d7adfd2a97 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.tsx @@ -100,7 +100,7 @@ export default function ArchivedSessionMenuItems({ session, title, workspaceName ({ delete: vi.fn(), error: vi.fn(), confirm: vi.fn() })); +const mocks = vi.hoisted(() => ({ + delete: vi.fn(), archive: vi.fn(), error: vi.fn(), confirm: vi.fn(), + notifyError: vi.fn(), notifySuccess: vi.fn(), + sessions: new Map(), +})); vi.mock('@/flow_chat/services/FlowChatManager', () => ({ - flowChatManager: { deleteChatSession: mocks.delete }, + flowChatManager: { deleteChatSession: mocks.delete, archiveChatSession: mocks.archive }, +})); +vi.mock('@/flow_chat/store/FlowChatStore', () => ({ + flowChatStore: { getState: () => ({ sessions: mocks.sessions }) }, })); vi.mock('@/infrastructure/services/business/workspaceManager', () => ({ workspaceManager: {} })); -vi.mock('@/shared/notification-system', () => ({ notificationService: {} })); +vi.mock('@/shared/notification-system', () => ({ + notificationService: { error: mocks.notifyError, success: mocks.notifySuccess }, +})); vi.mock('@/shared/utils/logger', () => ({ createLogger: () => ({ error: mocks.error, warn: vi.fn(), info: vi.fn(), debug: vi.fn() }), })); vi.mock('@/infrastructure/confirm-dialog', () => ({ confirmDanger: mocks.confirm })); vi.mock('@/infrastructure/i18n', async () => { const { createTestI18nT } = await import('@/test/i18nTestUtils'); - return { useI18n: () => ({ t: createTestI18nT('common') }) }; + const t = createTestI18nT('common'); + return { i18nService: { t }, useI18n: () => ({ t }) }; }); import SessionDeleteMenuItem from './SessionDeleteMenuItem'; -import { deleteSessionRow } from './sessionRowActions'; +import { archiveSessionRow, deleteSessionRow } from './sessionRowActions'; describe('session menu inline deletion confirmation', () => { let container: HTMLDivElement; @@ -32,7 +42,7 @@ describe('session menu inline deletion confirmation', () => { const render = async (open = true, sessionId = 'session-one') => { await act(async () => root.render(open ? ( - Archive + void archiveSessionRow(sessionId, key => key)}>Archive deleteSessionRow(sessionId)} @@ -45,6 +55,7 @@ describe('session menu inline deletion confirmation', () => { vi.resetAllMocks(); vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); resetDeviceSurfaceForTest(); + mocks.sessions.clear(); mocks.delete.mockResolvedValue(undefined); container = document.createElement('div'); document.body.appendChild(container); @@ -69,6 +80,26 @@ describe('session menu inline deletion confirmation', () => { expect(container.querySelector('[role="dialog"], [role="alertdialog"]')).toBeNull(); await click('confirm'); expect(mocks.delete).toHaveBeenCalledExactlyOnceWith('session-one'); + expect(mocks.archive).not.toHaveBeenCalled(); + }); + + it('archives immediately through the archive action', async () => { + await act(async () => container.querySelector('[data-testid="archive"]')!.click()); + expect(mocks.archive).toHaveBeenCalledExactlyOnceWith('session-one'); + expect(mocks.delete).not.toHaveBeenCalled(); + expect(mocks.confirm).not.toHaveBeenCalled(); + }); + + it('refuses to archive or delete an observer projection as if it were a stored session', async () => { + await click(); + // The observer can bind the job while confirmation is open. + mocks.sessions.set('session-one', { config: { dispatchJobId: 'job-one' } }); + await click('confirm'); + await act(async () => container.querySelector('[data-testid="archive"]')!.click()); + expect(mocks.delete).not.toHaveBeenCalled(); + expect(mocks.archive).not.toHaveBeenCalled(); + expect(mocks.notifyError).toHaveBeenCalledTimes(2); + expect(mocks.notifyError).toHaveBeenCalledWith('Archive or delete this session on the device that owns the task.'); }); it('restores the delete row and focus when Cancel is selected', async () => { diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.scss b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.scss index dedda9d6f9..90a2d29bf4 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.scss +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.scss @@ -526,6 +526,7 @@ &__inline-item-menu-popover { position: fixed; z-index: var(--openbitfun-layer-popover); + max-block-size: min(var(--openbitfun-overlay-menu-max-block-size), calc(100vh - 16px)); } &__inline-item-edit { diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.tsx b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.tsx index 53b0809695..eac161243c 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.tsx @@ -99,6 +99,7 @@ import { } from '@/features/dispatch/types'; import { useDispatchJobStore } from '@/features/dispatch/dispatchJobStore'; import { resolveDispatchNavPresentation } from '@/features/dispatch/dispatchNavPresentation'; +import { resolveSessionDriverId } from '@/flow_chat/session-drivers/resolve'; import { ensureCronJobCountsListener, getCronJobCountsSnapshot, @@ -1444,6 +1445,10 @@ const SessionsSection: React.FC = ({ const showAssistantInTooltip = trimmedAssistant.length > 0; const dispatchTarget = session.config.dispatchTarget; const isDispatched = isNonLocalDispatchTarget(dispatchTarget); + const sessionMutationDisabledReason = openMenuSessionId === session.sessionId + && resolveSessionDriverId(session.sessionId, session) === 'dispatch' + ? t('nav.sessions.dispatchMutationUnsupported') + : undefined; const worktreeIsolated = isWorktreeIsolatedSession(session); const worktreeRootPath = sessionWorktreeRootPath(session) ?? ''; const dispatchTargetLabel = @@ -1925,6 +1930,8 @@ const SessionsSection: React.FC = ({ type="button" leading={} onClick={e => { closeSessionMenu(); void handleArchive(e, session.sessionId); }} + disabled={Boolean(sessionMutationDisabledReason)} + title={sessionMutationDisabledReason} data-testid="nav-session-menu-archive" data-session-id={session.sessionId} > @@ -1934,7 +1941,8 @@ const SessionsSection: React.FC = ({ sessionId={session.sessionId} testId="nav-session-menu-delete" label={t(session.externalHistory?.mode === 'follow' ? 'nav.sessions.removeSource' : 'nav.sessions.delete')} - description={t(session.externalHistory?.mode === 'follow' ? 'nav.sessions.removeSourceConfirmMessage' : 'nav.sessions.deleteConfirmMessage', { name: sessionTitle })} + disabled={Boolean(sessionMutationDisabledReason)} + description={sessionMutationDisabledReason ?? t(session.externalHistory?.mode === 'follow' ? 'nav.sessions.removeSourceConfirmMessage' : 'nav.sessions.deleteConfirmMessage', { name: sessionTitle })} onConfirm={() => { closeSessionMenu(); return deleteSessionRow(session.sessionId); }} /> diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/sessionRowActions.ts b/src/web-ui/src/app/components/NavPanel/sections/sessions/sessionRowActions.ts index f411bc4d7e..2e249b54db 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/sessionRowActions.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/sessionRowActions.ts @@ -7,7 +7,10 @@ */ import { flowChatManager } from '@/flow_chat/services/FlowChatManager'; +import { resolveSessionDriverId } from '@/flow_chat/session-drivers/resolve'; +import { flowChatStore } from '@/flow_chat/store/FlowChatStore'; import { isOutcomeUnknownError } from '@/infrastructure/api/errors/TauriCommandError'; +import { i18nService } from '@/infrastructure/i18n'; import { isSurfaceChangedError } from '@/infrastructure/peer-device/deviceSurface'; import { workspaceManager } from '@/infrastructure/services/business/workspaceManager'; import { notificationService } from '@/shared/notification-system'; @@ -18,8 +21,16 @@ const log = createLogger('SessionRowActions'); export type SessionRowTranslate = (key: string, options?: Record) => string; +function refuseDispatchSessionMutation(sessionId: string): boolean { + const session = flowChatStore.getState().sessions.get(sessionId); + if (resolveSessionDriverId(sessionId, session) !== 'dispatch') return false; + notificationService.error(i18nService.t('common:nav.sessions.dispatchMutationUnsupported')); + return true; +} + /** Delete after menu confirmation; the session module reports failures. */ export async function deleteSessionRow(sessionId: string): Promise { + if (refuseDispatchSessionMutation(sessionId)) return; try { await flowChatManager.deleteChatSession(sessionId); } catch (error) { @@ -30,6 +41,7 @@ export async function deleteSessionRow(sessionId: string): Promise { /** Archive a session; the archive module reports its own failures. */ export async function archiveSessionRow(sessionId: string, t: SessionRowTranslate): Promise { + if (refuseDispatchSessionMutation(sessionId)) return; try { await flowChatManager.archiveChatSession(sessionId); window.dispatchEvent(new CustomEvent('openbitfun:session-archived')); diff --git a/src/web-ui/src/app/components/panels/FilesPanel.tsx b/src/web-ui/src/app/components/panels/FilesPanel.tsx index a850694491..a8cc800ff7 100644 --- a/src/web-ui/src/app/components/panels/FilesPanel.tsx +++ b/src/web-ui/src/app/components/panels/FilesPanel.tsx @@ -120,6 +120,8 @@ interface FilesPanelProps { /** Hide the in-explorer floating toolbar; parent can render equivalent actions (e.g. file viewer nav header). */ hideExplorerToolbar?: boolean; onExplorerToolbarApi?: (api: FileExplorerToolbarHandlers | null) => void; + revealDirectoryPath?: string; + onRevealHandled?: () => void; } const FilesPanel: React.FC = ({ @@ -133,6 +135,8 @@ const FilesPanel: React.FC = ({ onViewModeChange, hideExplorerToolbar = false, onExplorerToolbarApi, + revealDirectoryPath, + onRevealHandled, }) => { const { t } = useTranslation('panels/files'); const { t: tComponents } = useI18n('components'); @@ -142,10 +146,11 @@ const FilesPanel: React.FC = ({ // Identity is (surface, workspace ID). The path and connection are IO // projections that downstream openers still record for legacy tab data. const currentWorkspaceId = currentWorkspace?.id; + const ownerRoot = currentWorkspace?.rootPath ?? workspacePath; const resourceScope = useMemo(() => ({ surfaceId: surface.surfaceId, workspaceId: currentWorkspaceId, - workspacePath, remoteConnectionId: currentWorkspace?.connectionId, - }), [surface.surfaceId, currentWorkspaceId, currentWorkspace?.connectionId, workspacePath]); + workspacePath: ownerRoot, remoteConnectionId: currentWorkspace?.connectionId, + }), [surface.surfaceId, currentWorkspaceId, currentWorkspace?.connectionId, ownerRoot]); const panelRef = useRef(null); const navigationRequestRef = useRef(0); @@ -394,12 +399,11 @@ const FilesPanel: React.FC = ({ openFileInBestTarget({ filePath: data.path, scope: resourceScope, - workspacePath, ...(data.line ? { jumpToLine: data.line } : {}), ...(data.column ? { jumpToColumn: data.column } : {}), }, { source: 'project-nav' }); }); - }, [workspacePath, shouldOpenLargeFile, surface, resourceScope]); + }, [shouldOpenLargeFile, surface, resourceScope]); const handleNewFile = useCallback((data: { parentPath: string }) => { setInputDialog({ @@ -643,6 +647,12 @@ const FilesPanel: React.FC = ({ })(); }, [workspacePath, isRemoteCurrentWorkspace, expandFolderEnsure, selectFile]); + useEffect(() => { + if (!revealDirectoryPath || viewMode !== 'tree' || loading || !fileTree.length) return; + onRevealHandled?.(); + handleNavigateToPath({ path: revealDirectoryPath, scrollIntoView: true }); + }, [revealDirectoryPath, viewMode, loading, fileTree.length, onRevealHandled, handleNavigateToPath]); + const findNode = useCallback((nodes: FileSystemNode[], path: string): FileSystemNode | null => { for (const node of nodes) { if (pathsEquivalentFs(node.path, path)) return node; @@ -837,7 +847,6 @@ const FilesPanel: React.FC = ({ globalEventBus.on('file:decompress', handleDecompress); globalEventBus.on('file:paste', handlePasteFromContextMenu); globalEventBus.on('file-tree:refresh', handleFileTreeRefresh); - globalEventBus.on('file-explorer:navigate', handleNavigateToPath); return () => { globalEventBus.off('file:open', handleOpenFile); @@ -850,9 +859,8 @@ const FilesPanel: React.FC = ({ globalEventBus.off('file:decompress', handleDecompress); globalEventBus.off('file:paste', handlePasteFromContextMenu); globalEventBus.off('file-tree:refresh', handleFileTreeRefresh); - globalEventBus.off('file-explorer:navigate', handleNavigateToPath); }; - }, [handleOpenFile, handleNewFile, handleNewFolder, handleStartRename, handleDelete, handleFileDownload, handleCompress, handleDecompress, handlePasteFromContextMenu, handleFileTreeRefresh, handleNavigateToPath]); + }, [handleOpenFile, handleNewFile, handleNewFolder, handleStartRename, handleDelete, handleFileDownload, handleCompress, handleDecompress, handlePasteFromContextMenu, handleFileTreeRefresh]); useEffect(() => { if (typeof window === 'undefined') { @@ -968,12 +976,11 @@ const FilesPanel: React.FC = ({ openFileInBestTarget({ filePath, fileName, - workspacePath, scope: resourceScope, }, { source: 'project-nav' }); }); } - }, [selectFile, onFileSelect, workspacePath, fileTree, findNode, shouldOpenLargeFile, surface, resourceScope]); + }, [selectFile, onFileSelect, fileTree, findNode, shouldOpenLargeFile, surface, resourceScope]); const handleFileDoubleClick = useCallback((filePath: string) => { onFileDoubleClick?.(filePath); diff --git a/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.test.tsx b/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.test.tsx index ecddc0fc96..7b7770b34d 100644 --- a/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.test.tsx +++ b/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.test.tsx @@ -58,14 +58,14 @@ afterEach(() => { vi.unstubAllGlobals(); }); -it('keeps the primary directory first and routes browsing and related-directory editing separately', async () => { +it('opens each directory from its card and opens the editor from Manage', async () => { await render(); expect(track().querySelectorAll('.project-resource-cards__cell')).toHaveLength(5); expect(track().firstElementChild?.textContent).toContain('/repodirectories.primary'); await act(async () => button('directories.openDirectory:Project')!.click()); - expect(browse).toHaveBeenCalledOnce(); - await act(async () => button('directories.editDirectory:0')!.click()); - expect(manage).toHaveBeenCalledOnce(); + await act(async () => button('directories.openDirectory:0')!.click()); + expect(browse.mock.calls).toEqual([[undefined], ['/related/0']]); + expect(manage).not.toHaveBeenCalled(); expect(button('directories.removeDirectory:Project')).toBeNull(); const revealButton = button('directories.revealDirectory:Project')!; expect(revealButton.getAttribute('data-openbitfun-variant')).toBe('glass'); @@ -73,25 +73,29 @@ it('keeps the primary directory first and routes browsing and related-directory await act(async () => revealButton.click()); await act(async () => button('directories.revealDirectory:0')!.click()); expect(reveal.mock.calls).toEqual([['/repo'], ['/related/0']]); - expect(browse).toHaveBeenCalledOnce(); - expect(manage).toHaveBeenCalledOnce(); + expect(browse).toHaveBeenCalledTimes(2); const deleteButton = button('directories.removeDirectory:0')!; expect(deleteButton.getAttribute('data-openbitfun-variant')).toBe('glass'); expect(deleteButton.getAttribute('data-openbitfun-shape')).toBe('circle'); await act(async () => deleteButton.click()); expect(remove).toHaveBeenCalledExactlyOnceWith('/related/0', deleteButton); - expect(manage).toHaveBeenCalledOnce(); + expect(manage).not.toHaveBeenCalled(); expect(container.querySelector('.project-resource-cards__add')).toBeNull(); await act(async () => [...container.querySelectorAll('.project-resources__section-actions button')] .find(button => button.textContent === 'directories.add')!.click()); expect(add).toHaveBeenCalledOnce(); + const manageButton = [...container.querySelectorAll('.project-resources__section-actions button')] + .find(button => button.textContent === 'directories.manage')!; + await act(async () => manageButton.click()); + expect(manage).toHaveBeenCalledOnce(); await render(workspace, false); expect(button('directories.openDirectory:Project')?.disabled).toBe(true); - expect(button('directories.editDirectory:0')?.disabled).toBe(false); + expect(button('directories.openDirectory:0')?.disabled).toBe(true); + expect(manageButton.disabled).toBe(false); await render(workspace, true, false); expect(button('directories.revealDirectory:Project')?.disabled).toBe(true); expect(button('directories.revealDirectory:0')?.disabled).toBe(true); - expect(button('directories.editDirectory:0')?.disabled).toBe(false); + expect(button('directories.openDirectory:0')?.disabled).toBe(false); }); it('supports bounded card navigation, keyboard and reduced motion, and updates overflow when resized or edited', async () => { diff --git a/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.tsx b/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.tsx index ef96ea961e..8b6b6ea5c7 100644 --- a/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.tsx +++ b/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.tsx @@ -9,7 +9,7 @@ export function ProjectDirectoriesSection({ workspace, fileAccess, onBrowse, onM canReveal, onReveal, revealingPath, error }: { workspace: WorkspaceInfo; fileAccess: boolean; - onBrowse: () => void; + onBrowse: (directoryPath?: string) => void; onManage: () => void; onAdd: () => void; onRemove: (path: string, trigger?: HTMLElement) => void; @@ -44,8 +44,9 @@ export function ProjectDirectoriesSection({ workspace, fileAccess, onBrowse, onM resetKey={JSON.stringify([workspace.id, ...directories.map(directory => directory.path)])}> {directories.map((directory, index) =>
  • onBrowse(directory.primary ? undefined : directory.path)} + aria-label={t('directories.openDirectory', { name: directory.name })} actions={[{ id: 'reveal', label: t('directories.revealDirectory', { name: directory.name }), tooltip: t(canReveal ? 'directories.reveal' : 'directories.revealUnavailable'), icon: , disabled: !canReveal || !!revealingPath || !!removingPath, diff --git a/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.test.tsx b/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.test.tsx index 152b558955..0a19daac46 100644 --- a/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.test.tsx +++ b/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.test.tsx @@ -4,6 +4,8 @@ import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { WorkspaceKind, WorkspaceType, type WorkspaceInfo } from '@/shared/types'; import { resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; +import { appManager } from '@/app/services/AppManager'; +import { useWorkspaceResourceState } from '../workspace-resources/workspaceResourceState'; import ProjectResourcesScene from './ProjectResourcesScene'; import { projectResourceSceneId } from './projectResourceTarget'; @@ -12,7 +14,10 @@ const mocks = vi.hoisted(() => ({ activate: vi.fn(), refresh: vi.fn(), agentDialog: vi.fn(), skillDialog: vi.fn(), grants: vi.fn(), rules: vi.fn(), iconDialog: vi.fn(), directoryDialog: vi.fn(), jobsDialog: vi.fn(), })); -vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string) => key, formatNumber: String, formatDate: String }) })); +vi.mock('@/infrastructure/i18n', () => ({ + useI18n: () => ({ t: (key: string) => key, formatNumber: String, formatDate: String }), + i18nService: { t: (key: string) => key }, +})); vi.mock('@/infrastructure/contexts/WorkspaceContext', () => ({ useWorkspaceContext: () => ({ openedWorkspaces: mocks.workspaces, activeWorkspace: mocks.active, setActiveWorkspace: mocks.activate }), })); @@ -106,16 +111,33 @@ it('renders project defaults above metrics and inline project permissions withou }); it('opens files with the project and SSH identity rather than the current conversation', async () => { - mocks.workspaces.set('a', { ...workspace, workspaceKind: WorkspaceKind.Remote, connectionId: 'ssh-a' }); + const relatedPath = '/srv/ref\\docs'; + mocks.workspaces.set('a', { ...workspace, workspaceKind: WorkspaceKind.Remote, connectionId: 'ssh-a', relatedPaths: [{ path: relatedPath }] }); await render(); await act(async () => [...container.querySelectorAll('.project-resource-list__row')].find(button => button.textContent?.includes('Project agent'))!.click()); await act(async () => [...document.querySelectorAll('button')].find(button => button.textContent === 'capabilities.openDefinition')!.click()); expect(mocks.openFile).toHaveBeenCalledWith({ filePath: '/a/agent.md', scope: { surfaceId: 'local', workspaceId: 'a', workspacePath: '/a', remoteConnectionId: 'ssh-a', } }); - const directory = container.querySelector('button[aria-label="directories.openDirectory"]')!; - await act(async () => directory.click()); - expect(mocks.browse).toHaveBeenCalledWith('a'); + const [primary, related] = container.querySelectorAll('button[aria-label="directories.openDirectory"]'); + const previousLayout = appManager.getState().layout; + const layoutStore = useWorkspaceResourceState.getState(); + const resourceKey = JSON.stringify(['local', 'workspace-resources', 'a']); + const legacyKey = JSON.stringify(['local', 'workspace-resources', 'ssh-a', 'a', '/a']); + try { + appManager.updateLayout({ leftPanelCollapsed: true }); + layoutStore.updateLayout(legacyKey, { filesCollapsed: true, fileView: 'search', terminalFraction: 0.5 }); + await act(async () => related.click()); + expect(mocks.browse).toHaveBeenLastCalledWith('a', relatedPath); + expect(mocks.directoryDialog).not.toHaveBeenCalled(); + expect(appManager.getState().layout.leftPanelCollapsed).toBe(false); + expect(useWorkspaceResourceState.getState().layouts[resourceKey]).toMatchObject({ filesCollapsed: false, fileView: 'tree', terminalFraction: 0.5 }); + await act(async () => primary.click()); + expect(mocks.browse).toHaveBeenLastCalledWith('a', undefined); + } finally { + appManager.updateLayout({ leftPanelCollapsed: previousLayout.leftPanelCollapsed, leftPanelActiveTab: previousLayout.leftPanelActiveTab }); + useWorkspaceResourceState.setState({ layouts: layoutStore.layouts }); + } expect(mocks.activate).not.toHaveBeenCalled(); }); diff --git a/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.tsx b/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.tsx index 8b73492786..9924388bae 100644 --- a/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.tsx +++ b/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.tsx @@ -10,6 +10,8 @@ import { getSkillSourceLabel } from '@/infrastructure/config/skillSourcePresenta import { fileTabManager } from '@/shared/services/FileTabManager'; import { isRemoteWorkspace, type WorkspaceInfo } from '@/shared/types'; import { useNavSceneStore } from '@/app/stores/navSceneStore'; +import { appManager } from '@/app/services/AppManager'; +import { useWorkspaceResourceState } from '../workspace-resources/workspaceResourceState'; import { lazyWithRecovery } from '@/shared/utils/lazyWithRecovery'; import { WorkspaceIcon } from '@/app/components/WorkspaceIcon/WorkspaceIcon'; import { parseProjectResourceTarget } from './projectResourceTarget'; @@ -72,8 +74,14 @@ function ProjectResourcesContent({ workspace, scope, isActive }: { workspace: Wo useEffect(() => { if (!isActive) { setDialog(null); setDetail(null); setCapabilityList(null); } }, [isActive]); const current = () => alive.current && scope.isCurrent(); const closeDialog = () => { setDialog(null); data.refresh(); }; - const browseFiles = () => { - if (current() && fileAccess) useNavSceneStore.getState().openWorkspaceResources(workspace.id); + const browseFiles = (directoryPath?: string) => { + if (!isActive || !current() || !fileAccess) return; + const resourceLayout = useWorkspaceResourceState.getState(); + const resourceKey = scope.key('workspace-resources', workspace.id); + resourceLayout.migrateLayout(scope.key('workspace-resources', workspace.connectionId, workspace.id, workspace.rootPath), resourceKey); + resourceLayout.updateLayout(resourceKey, { filesCollapsed: false, fileView: 'tree' }); + useNavSceneStore.getState().openWorkspaceResources(workspace.id, directoryPath); + appManager.updateLayout({ leftPanelActiveTab: 'files', leftPanelCollapsed: false }); }; const openFile = (path: string) => { if (!current() || !fileAccess) return; diff --git a/src/web-ui/src/app/scenes/project-resources/README.md b/src/web-ui/src/app/scenes/project-resources/README.md index 87e4e4f8ed..ea5bd0da6b 100644 --- a/src/web-ui/src/app/scenes/project-resources/README.md +++ b/src/web-ui/src/app/scenes/project-resources/README.md @@ -63,7 +63,7 @@ new-conversation action. Files carry the owning workspace and connection into the workbench. Directory management uses the Home device strip's horizontal cards, icon/name/path hierarchy and status pills. The primary directory leads, followed by related directories; overflowing cards have scroll controls. -The primary card opens files, while related cards and the header action open the editor. Editing reuses +Each directory card opens its directory in the left file tree. The header's Manage action reuses the existing directory dialog, with an External Import-style list of directory paths, descriptions and row actions. Related rows expand inline for editing; external references remain read-only, and changes are only persisted on Save. Project guides are not listed in this section. diff --git a/src/web-ui/src/app/scenes/workspace-resources/README.md b/src/web-ui/src/app/scenes/workspace-resources/README.md index 3f759e2bee..3494e25ce9 100644 --- a/src/web-ui/src/app/scenes/workspace-resources/README.md +++ b/src/web-ui/src/app/scenes/workspace-resources/README.md @@ -12,8 +12,9 @@ popped out from its menu or dragged onto the top tab bar. There is no File View content scene or intermediate container in the main tab bar. Resource navigation owns an explicit `(device surface, workspace id)` browse target -in `navSceneStore`. The folder action updates only that target; it never activates -the global workspace, initializes/selects a chat, or creates an empty session. +in `navSceneStore`. A related-directory card also supplies the directory path as +the file-tree root. Workspace search returns to the project root. Folder actions +leave the active workspace and conversation selection intact. Back/forward navigation retains the target. A closed target or another device cannot fall back to the active workspace. Legacy untargeted entry points still use the current workspace. @@ -107,7 +108,7 @@ mobile Remote Control, or Detached Dispatch end-to-end behavior. ## Focused verification ```bash -pnpm --dir src/web-ui run test:run src/tools/terminal/services/terminalWorkspaceScope.test.ts src/tools/terminal/services/manualTerminalProfileService.test.ts src/tools/file-system/utils/fileTreeReveal.test.ts src/app/scenes/workspace-resources/workspaceResources.test.ts src/app/scenes/workspace-resources/terminalViewLifecycle.test.tsx +pnpm --dir src/web-ui run test:run src/tools/terminal/services/terminalWorkspaceScope.test.ts src/tools/terminal/services/manualTerminalProfileService.test.ts src/tools/file-system/utils/fileTreeReveal.test.ts src/app/scenes/workspace-resources pnpm --dir src/web-ui run test:run src/app/scenes/terminal/TerminalActionBridge.test.tsx src/tools/file-explorer/controller/ExplorerController.test.ts src/infrastructure/api/service-api/WorkspaceAPI.test.ts src/shared/context-menu-system/core/ContextResolver.resourceScope.test.ts src/shared/context-menu-system/commands/builtin/file/RevealInExplorerCommand.test.ts cargo test -p terminal-core --lib workspace_origin_contract_tests pnpm run check:web diff --git a/src/web-ui/src/app/scenes/workspace-resources/WorkspaceResourcePanel.test.tsx b/src/web-ui/src/app/scenes/workspace-resources/WorkspaceResourcePanel.test.tsx new file mode 100644 index 0000000000..0023635e27 --- /dev/null +++ b/src/web-ui/src/app/scenes/workspace-resources/WorkspaceResourcePanel.test.tsx @@ -0,0 +1,63 @@ +/** @vitest-environment jsdom */ +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { expect, it, vi } from 'vitest'; +import { activateSurface, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; +import { WorkspaceKind, WorkspaceType, type WorkspaceInfo } from '@/shared/types'; +import { useNavSceneStore } from '../../stores/navSceneStore'; +import WorkspaceResourcePanel from './WorkspaceResourcePanel'; + +const fixtures = vi.hoisted(() => ({ workspaces: new Map(), files: vi.fn() })); +vi.mock('@/infrastructure/contexts/WorkspaceContext', () => ({ + useWorkspaceContext: () => ({ activeWorkspace: fixtures.workspaces.get('project'), openedWorkspaces: fixtures.workspaces }), +})); +vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string) => key, formatNumber: String }) })); +vi.mock('../../components/panels/FilesPanel', () => ({ default: (props: unknown) => { + fixtures.files(props); + return null; +} })); +vi.mock('../../components/panels/TerminalEditModal', () => ({ default: () => null })); +vi.mock('../shell/hooks', () => ({ useShellEntries: () => ({ entries: [] }) })); +vi.mock('@/tools/terminal/services/TerminalService', () => ({ getTerminalService: () => ({ getAvailableShells: async () => [] }) })); +vi.mock('./WorkspaceTerminals', () => ({ default: ({ onReveal }: { onReveal: (path: string) => void }) => ( + +) })); + +it('browses a linked SSH directory on its peer and can return to the project tree from a terminal', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const directoryPath = '/reference/docs\\api'; + const workspace: WorkspaceInfo = { + id: 'project', rootPath: '/repo', name: 'Project', workspaceKind: WorkspaceKind.Remote, connectionId: 'ssh-a', + relatedPaths: [{ path: directoryPath }], workspaceType: WorkspaceType.SingleProject, + languages: [], tags: [], openedAt: '', lastAccessed: '', + }; + fixtures.workspaces.set(workspace.id, workspace); + const container = document.createElement('div'); + const root = createRoot(container); + const nav = useNavSceneStore.getState(); + activateSurface('peer:project'); + try { + nav.openWorkspaceResources(workspace.id, directoryPath); + await act(async () => root.render()); + expect(fixtures.files).toHaveBeenLastCalledWith(expect.objectContaining({ workspace, workspacePath: directoryPath })); + + await act(async () => [...container.querySelectorAll('button')] + .find(button => button.textContent === 'Reveal terminal directory')!.click()); + expect(fixtures.files).toHaveBeenLastCalledWith(expect.objectContaining({ + workspace, workspacePath: workspace.rootPath, revealDirectoryPath: '/repo/src', + })); + + await act(async () => nav.openWorkspaceResources(workspace.id, directoryPath)); + await act(async () => container.querySelector('[aria-label="actions.switchToSearch"]')!.click()); + expect(fixtures.files).toHaveBeenLastCalledWith(expect.objectContaining({ workspacePath: workspace.rootPath, viewMode: 'search' })); + + await act(async () => nav.openWorkspaceResources(workspace.id, directoryPath)); + fixtures.files.mockClear(); + await act(async () => { activateSurface('local'); }); + expect(fixtures.files).not.toHaveBeenCalled(); + } finally { + act(() => root.unmount()); + nav.closeNavScene(); + resetDeviceSurfaceForTest(); + } +}); diff --git a/src/web-ui/src/app/scenes/workspace-resources/WorkspaceResourcePanel.tsx b/src/web-ui/src/app/scenes/workspace-resources/WorkspaceResourcePanel.tsx index 855c391d9a..4c48c2f456 100644 --- a/src/web-ui/src/app/scenes/workspace-resources/WorkspaceResourcePanel.tsx +++ b/src/web-ui/src/app/scenes/workspace-resources/WorkspaceResourcePanel.tsx @@ -7,7 +7,6 @@ import { import { useI18n } from '@/infrastructure/i18n'; import { useWorkspaceContext } from '@/infrastructure/contexts/WorkspaceContext'; import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; -import { globalEventBus } from '@/infrastructure/event-bus'; import type { FileExplorerToolbarHandlers } from '@/tools/file-system'; import { isTerminalPathInside } from '@/tools/terminal/services/terminalWorkspaceScope'; import type { ShellInfo } from '@/tools/terminal/types/session'; @@ -19,7 +18,7 @@ import { DEFAULT_RESOURCE_LAYOUT, useWorkspaceResourceState } from './workspaceR import WorkspaceTerminals from './WorkspaceTerminals'; import { useResourceSplit } from './useResourceSplit'; import { showResourceMenu } from './resourceMenus'; -import { resolveResourceWorkspace, useNavSceneStore } from '../../stores/navSceneStore'; +import { resolveResourceWorkspace, useNavSceneStore, type ResourceWorkspaceTarget } from '../../stores/navSceneStore'; import type { WorkspaceInfo } from '@/shared/types'; import '../file-viewer/FileViewerNav.scss'; @@ -38,10 +37,12 @@ export default function WorkspaceResourcePanel() { resourceKey, ); }, [migrateLayout, resourceKey, scope, workspace]); - return ; + return ; } -function WorkspaceResourceContent({ resourceKey, workspace }: { resourceKey: string; workspace: WorkspaceInfo | null }) { +function WorkspaceResourceContent({ resourceKey, workspace, target }: { + resourceKey: string; workspace: WorkspaceInfo | null; target: ResourceWorkspaceTarget | null; +}) { const { t, formatNumber } = useI18n('common'); const { t: tFiles } = useI18n('panels/files'); const { t: tTools } = useI18n('tools'); @@ -55,7 +56,7 @@ function WorkspaceResourceContent({ resourceKey, workspace }: { resourceKey: str const mounted = useRef(true); const [actionError, setActionError] = useState(null); const [selectedTerminal, setSelectedTerminal] = useState(null); - const [pendingReveal, setPendingReveal] = useState(null); + const [pendingReveal, setPendingReveal] = useState<{ path: string; target: ResourceWorkspaceTarget | null } | null>(null); const [shells, setShells] = useState([]); const container = useRef(null); const filesId = useId(); @@ -64,6 +65,9 @@ function WorkspaceResourceContent({ resourceKey, workspace }: { resourceKey: str const hasTerminalContent = terminals.entries.length > 0 || Boolean(terminals.error || actionError); const showSplit = !layout.filesCollapsed && !layout.terminalsCollapsed && hasTerminalContent; const isRemote = workspace?.workspaceKind === 'remote'; + const directoryPath = target?.directoryPath; + const fileRoot = directoryPath === undefined ? workspace?.rootPath + : workspace?.relatedPaths?.find(directory => directory.path === directoryPath)?.path; useEffect(() => { mounted.current = true; @@ -94,15 +98,21 @@ function WorkspaceResourceContent({ resourceKey, workspace }: { resourceKey: str }); }, [scope]); const revealDirectory = useCallback((path: string) => { - if (!mounted.current || !scope.isCurrent()) return; + if (!workspace || !mounted.current || !scope.isCurrent()) return; + const nav = useNavSceneStore.getState(); + if (directoryPath !== undefined && !isTerminalPathInside(path, fileRoot ?? '', isRemote)) { + nav.openWorkspaceResources(workspace.id); + } updateLayout(resourceKey, { filesCollapsed: false, fileView: 'tree' }); - setPendingReveal(path); - }, [resourceKey, scope, updateLayout]); - useEffect(() => { - if (!pendingReveal || layout.filesCollapsed || layout.fileView !== 'tree') return; - globalEventBus.emit('file-explorer:navigate', { path: pendingReveal, scrollIntoView: true }); - setPendingReveal(null); - }, [pendingReveal, layout.filesCollapsed, layout.fileView]); + setPendingReveal({ path, target: useNavSceneStore.getState().resourceWorkspace }); + }, [directoryPath, fileRoot, isRemote, resourceKey, scope, updateLayout, workspace]); + const changeFileView = useCallback((fileView: 'tree' | 'search') => { + if (fileView === 'search' && directoryPath !== undefined && workspace) { + useNavSceneStore.getState().openWorkspaceResources(workspace.id); + } + updateLayout(resourceKey, { filesCollapsed: false, fileView }); + }, [directoryPath, resourceKey, updateLayout, workspace]); + const clearPendingReveal = useCallback(() => setPendingReveal(null), []); const error = actionError || terminals.error; const createTerminal = (shellType?: string, shellId?: string) => run(async () => { @@ -136,13 +146,16 @@ function WorkspaceResourceContent({ resourceKey, workspace }: { resourceKey: str : } - onClick={() => updateLayout(resourceKey, { filesCollapsed: false, fileView: layout.fileView === 'tree' ? 'search' : 'tree' })} /> + onClick={() => changeFileView(layout.fileView === 'tree' ? 'search' : 'tree')} /> {showSplit &&
    void; - openWorkspaceResources: (workspaceId: string) => void; + openWorkspaceResources: (workspaceId: string, directoryPath?: string) => void; closeNavScene: () => void; goBack: () => void; goForward: () => void; @@ -64,10 +65,10 @@ export const useNavSceneStore = create((set) => ({ navigationMotion: getInteractionMotion(), navigationSequence: state.navigationSequence + 1, })), - openWorkspaceResources: (workspaceId) => set(state => ({ + openWorkspaceResources: (workspaceId, directoryPath) => set(state => ({ showSceneNav: true, navSceneId: 'file-viewer', - resourceWorkspace: { surfaceId: getActiveSurfaceId(), workspaceId }, + resourceWorkspace: { surfaceId: getActiveSurfaceId(), workspaceId, ...(directoryPath !== undefined && { directoryPath }) }, navigationMotion: getInteractionMotion(), navigationSequence: state.navigationSequence + 1, })), diff --git a/src/web-ui/src/flow_chat/components/WelcomePanel.appearance.ts b/src/web-ui/src/flow_chat/components/WelcomePanel.appearance.ts index 60f612862e..e7b799d099 100644 --- a/src/web-ui/src/flow_chat/components/WelcomePanel.appearance.ts +++ b/src/web-ui/src/flow_chat/components/WelcomePanel.appearance.ts @@ -12,6 +12,7 @@ export const welcomePanelAppearanceDescriptor: AppearanceSurfaceDescriptor = { { id: 'modeOption', propertyProfile: 'control', visualRole: 'control' }, { id: 'modeName', propertyProfile: 'paint', visualRole: 'content' }, { id: 'heading', propertyProfile: 'paint', visualRole: 'content' }, + { id: 'workspaceChanges', propertyProfile: 'paint', visualRole: 'content' }, { id: 'tagline', propertyProfile: 'paint', visualRole: 'content' }, { id: 'divider', propertyProfile: 'paint', visualRole: 'divider' }, { id: 'narrative', propertyProfile: 'paint', visualRole: 'content' }, diff --git a/src/web-ui/src/flow_chat/components/WelcomePanel.css b/src/web-ui/src/flow_chat/components/WelcomePanel.css index 0cb9fac98f..e8ee22d2e9 100644 --- a/src/web-ui/src/flow_chat/components/WelcomePanel.css +++ b/src/web-ui/src/flow_chat/components/WelcomePanel.css @@ -267,6 +267,17 @@ outline-offset: 2px; } +.welcome-panel__workspace-changes { + grid-row: 3; + align-self: start; + margin: var(--openbitfun-space-3) 0 0; + text-align: center; + color: var(--openbitfun-color-content-secondary); + font-family: var(--openbitfun-type-body-sm-font-family); + font-size: var(--openbitfun-type-body-sm-font-size); + line-height: var(--openbitfun-type-body-sm-line-height); +} + .welcome-panel__details { grid-row: 3; align-self: start; diff --git a/src/web-ui/src/flow_chat/components/WelcomePanel.test.tsx b/src/web-ui/src/flow_chat/components/WelcomePanel.test.tsx index a5515e532b..639d92482f 100644 --- a/src/web-ui/src/flow_chat/components/WelcomePanel.test.tsx +++ b/src/web-ui/src/flow_chat/components/WelcomePanel.test.tsx @@ -25,6 +25,8 @@ const gitApiMock = vi.hoisted(() => ({ getStatus: vi.fn(), getRepositoryBasic: vi.fn(), })); +const useTrackedChangeCount = vi.hoisted(() => vi.fn()); +vi.mock('@/tools/git/hooks/useTrackedChangeCount', () => ({ useTrackedChangeCount })); const workspaceMocks = vi.hoisted(() => ({ hasWorkspace: true, @@ -103,7 +105,7 @@ vi.mock('@/app/scenes/my-agent/useAgentIdentityDocument', () => ({ useAgentIdentityDocument: () => ({ document: { name: '' } }), })); -// The composer still reads Git state; the welcome panel must not subscribe. +// The composer reads the full Git state; the welcome panel uses the count only. vi.mock('@/tools/git/hooks/useGitState', () => ({ useGitState: ({ repositoryPath, debugSource }: { repositoryPath: { workspaceId: string }; debugSource: string }) => { const workspaceId = repositoryPath.workspaceId; @@ -165,6 +167,7 @@ describe('WelcomePanel empty session presentation', () => { beforeEach(() => { vi.clearAllMocks(); + useTrackedChangeCount.mockReturnValue(null); workspaceMocks.hasWorkspace = true; workspaceMocks.selectDraftWorkspace.mockReset(); workspaceMocks.createChatDraft.mockResolvedValue('selected-workspace-draft'); @@ -323,7 +326,7 @@ describe('WelcomePanel empty session presentation', () => { expect(update).not.toHaveBeenCalled(); }); - it('includes the project in the greeting without the workspace and Git summary', async () => { + it('includes the project in the greeting without displaying an unavailable count', async () => { await act(async () => { root.render(); }); @@ -332,10 +335,33 @@ describe('WelcomePanel empty session presentation', () => { expect(container.querySelector('[data-openbitfun-product-part="narrative"]')).toBeNull(); expect(container.querySelector('[data-openbitfun-product-part="divider"]')).toBeNull(); expect(container.querySelector('.welcome-panel__details')).toBeNull(); + expect(container.querySelector('[data-openbitfun-product-part="workspaceChanges"]')).toBeNull(); expect(workspaceMocks.gitScopes).toEqual([]); expect(gitApiMock.getStatus).not.toHaveBeenCalled(); }); + it('shows only a positive count below the greeting and uses the execution workspace', async () => { + const { draft: _draft, ...session } = newDraft(); + const worktreeSession = { ...session, workspaceId: 'worktree-1', config: { + workspaceId: 'worktree-1', projectWorkspaceId: 'workspace-1', + } }; + useTrackedChangeCount.mockReturnValue(3); + await act(async () => root.render()); + const greeting = container.querySelector('[data-openbitfun-product-part="greeting"]')!; + const summary = greeting.nextElementSibling; + expect(summary?.textContent).toBe('工作区有动静,3 个文件改了还没提交。'); + expect(summary?.querySelector('strong')?.textContent).toBe('3'); + expect(useTrackedChangeCount).toHaveBeenLastCalledWith('worktree-1', false); + + useTrackedChangeCount.mockReturnValue(0); + await act(async () => root.render()); + expect(container.querySelector('[data-openbitfun-product-part="workspaceChanges"]')).toBeNull(); + + useTrackedChangeCount.mockClear(); + await act(async () => root.render()); + expect(useTrackedChangeCount).not.toHaveBeenCalled(); + }); + it('does not render the retired panda mascot', async () => { await act(async () => { root.render(); diff --git a/src/web-ui/src/flow_chat/components/WelcomePanel.tsx b/src/web-ui/src/flow_chat/components/WelcomePanel.tsx index f97eafce08..5c8aaf38ee 100644 --- a/src/web-ui/src/flow_chat/components/WelcomePanel.tsx +++ b/src/web-ui/src/flow_chat/components/WelcomePanel.tsx @@ -25,10 +25,11 @@ import { FlowChatManager } from '../services/FlowChatManager'; import { resolveChatInputExecutionLevelPolicy } from '../utils/chatInputExecutionLevelPolicy'; import { isSessionBindingLocked } from '../utils/sessionLifecycle'; import { acpAgentTypeFromSession } from '../utils/acpSession'; -import { sessionProjectWorkspacePath } from '../utils/sessionWorkspace'; +import { sessionProjectWorkspacePath, sessionWorkspaceId } from '../utils/sessionWorkspace'; import type { Session } from '../types/flow-chat'; import { useChatInputState } from '../store/chatInputStateStore'; import { computeFlowChatInputOverlayInsetPx } from '../utils/flowChatScrollLayout'; +import { WelcomeWorkspaceChanges } from './WelcomeWorkspaceChanges'; import './WelcomePanel.css'; const log = createLogger('WelcomePanel'); @@ -170,6 +171,7 @@ interface WelcomePanelProps { /** Owning workspace ID of the session being welcomed; selects the assistant identity document. */ workspaceId?: string; workspacePath?: string; + isActive?: boolean; } export const WelcomePanel: React.FC = ({ @@ -179,6 +181,7 @@ export const WelcomePanel: React.FC = ({ sessionMode: initialSessionMode, workspaceId: initialWorkspaceId, workspacePath: initialWorkspacePath = '', + isActive = true, }) => { const { t } = useTranslation('flow-chat'); const { t: tCommon } = useTranslation('common'); @@ -209,6 +212,11 @@ export const WelcomePanel: React.FC = ({ const sessionModeLower = (sessionMode || '').toLowerCase(); const isCoworkSession = sessionModeLower === 'cowork'; const isClawSession = sessionModeLower === 'claw'; + const executionWorkspaceId = session + ? session.draft?.workspaceId ?? sessionWorkspaceId(session) + : workspaceId; + const executionWorkspace = (executionWorkspaceId ? openedWorkspaces.get(executionWorkspaceId) : undefined) + ?? workspace; const harnessProfile = canonicalHarnessId(sessionMode || 'Standard'); const isModeExpanded = Boolean(harnessProfile && modeSelectorExpanded); const workspaceName = hasWorkspace ? workspace?.name.trim() : undefined; @@ -455,6 +463,11 @@ export const WelcomePanel: React.FC = ({
    + {isActive && hasWorkspace && !isCoworkSession && !isClawSession && executionWorkspaceId && ( + + )} + + }} /> +

    + ); +} diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx index cb0e1beb28..89cb1f1a74 100644 --- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx @@ -29,6 +29,7 @@ vi.mock('../../store/FlowChatStore', () => ({ flowChatStore: { releaseSessionHistoryCompletionAfterInitialPaint: () => false, extendSessionHistoryWindow: () => null, loadSessionTurnWindow: (...args: unknown[]) => fixture.loadTurnWindow(...args), + loadPreviousSessionTurnWindow: (...args: unknown[]) => fixture.loadTurnWindow(...args), activateSessionHistoryWindow: () => fixture.cached, } })); vi.mock('../../store/modernFlowChatStore', async importOriginal => { diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx index 5579c2a5ab..9c67658944 100644 --- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx @@ -2183,11 +2183,13 @@ export const ModernFlowChatContainer: React.FC = ( setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'loading' })); let viewportPreparationStarted = false; try { - const result = await flowChatStore.loadSessionTurnWindow(sessionId, targetOrdinal, { - source: 'prefetch', - before: direction === 'before' ? 12 : 4, - after: direction === 'after' ? 12 : 1, - }); + const result = direction === 'before' + ? await flowChatStore.loadPreviousSessionTurnWindow(sessionId, targetOrdinal) + : await flowChatStore.loadSessionTurnWindow(sessionId, targetOrdinal, { + source: 'prefetch', + before: 4, + after: 12, + }); if (!result.isCurrent || !isCurrent()) { recordHistoryPagingEvent(sessionId, 'outcome_cancelled', { direction, @@ -2789,6 +2791,7 @@ export const ModernFlowChatContainer: React.FC = ( key={surfaceScope.key('welcome', surfaceScope.epoch, activeSession?.sessionId ?? '', activeSession?.draft?.workspaceId ?? '')} session={activeSession} + isActive={isViewportActive} onQuickAction={(command) => { window.dispatchEvent(new CustomEvent('fill-chat-input', { detail: { message: command, sessionId: activeSession?.sessionId } diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index 95827eb2c6..fe491ac25e 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -6678,7 +6678,7 @@ describe('FlowChatStore historical session hydration state', () => { expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledTimes(1); }); - it.each(['local', 'ssh'])('opens %s history with one Turn and warms an adjacent range only after paint without replacing the tail', async location => { + it.each(['local', 'ssh'])('opens %s history with one Turn and shares the post-paint warm-up with older paging', async location => { const catalog = createTurnCatalog(100); const session = createSession({ sessionId: 'history-1', isHistorical: true, historyState: 'metadata-only', ...(location === 'ssh' ? { remoteConnectionId: 'ssh-host', remoteSshHost: 'host.example' } : {}), @@ -6690,8 +6690,8 @@ describe('FlowChatStore historical session hydration state', () => { }); apiMocks.loadSessionTurnWindow.mockResolvedValueOnce({ status: 'ready', catalogRevision: catalog.revision, totalTurnCount: 100, - startOrdinal: 98, endOrdinalExclusive: 100, targetTurnId: 'turn-98', - turns: [98, 99].map(index => createPersistedTurn(index)), + startOrdinal: 94, endOrdinalExclusive: 99, targetTurnId: 'turn-98', + turns: [94, 95, 96, 97, 98].map(index => createPersistedTurn(index)), }); flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]), activeSessionId: session.sessionId })); await flowChatStore.loadSessionHistory(session.sessionId); @@ -6700,9 +6700,13 @@ describe('FlowChatStore historical session hydration state', () => { const tail = flowChatStore.getState().sessions.get(session.sessionId)!.dialogTurns; expect(tail.map(turn => turn.id)).toEqual(['turn-99']); flowChatStore.releaseSessionHistoryCompletionAfterInitialPaint(session.sessionId); + await expect(flowChatStore.loadPreviousSessionTurnWindow(session.sessionId, 98)).resolves.toMatchObject({ + status: 'ready', + range: { startOrdinal: 94, endOrdinalExclusive: 100 }, + }); await flushAsyncWork(); expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledTimes(1); - expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledWith(expect.objectContaining({ targetStorageTurnIndex: 98, before: 0, after: 1 })); + expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledWith(expect.objectContaining({ targetStorageTurnIndex: 98, before: 12, after: 1 })); expect(flowChatStore.getState().sessions.get(session.sessionId)!.dialogTurns).toBe(tail); expect(flowChatStore.getSessionHistoryViewState(session.sessionId)?.activeRange).toBeNull(); expect(flowChatStore.hasPendingSessionHistoryCompletion(session.sessionId)).toBe(false); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 4c7f35d029..ccf03b053b 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -3716,6 +3716,18 @@ export class FlowChatStore { } } + public loadPreviousSessionTurnWindow( + sessionId: string, + targetOrdinal: number, + ): Promise { + // The tail warm-up and the older boundary must share the same request. + return this.loadSessionTurnWindow(sessionId, targetOrdinal, { + source: 'prefetch', + before: 12, + after: 1, + }); + } + public async loadSessionTurnWindow( sessionId: string, targetOrdinal: number, @@ -3917,6 +3929,8 @@ export class FlowChatStore { request.workspaceId ? '' : request.remoteSshHost ?? '', request.targetStorageTurnIndex, request.catalog.revision, + request.originalTargetTurnId ?? '', + request.includeInternal ? 'internal' : 'public', request.before, request.after, ); @@ -4103,7 +4117,7 @@ export class FlowChatStore { const first = canonicalSessionTurns(session)[0]; const firstOrdinal = session.turnCatalog.entries.find(entry => entry.turnId === first?.id)?.ordinal; if (firstOrdinal !== undefined && firstOrdinal > 0) { - void this.loadSessionTurnWindow(sessionId, firstOrdinal - 1, { before: 0, after: 1, source: 'prefetch' }) + void this.loadPreviousSessionTurnWindow(sessionId, firstOrdinal - 1) .catch(error => { if (!isSurfaceChangedError(error)) log.debug('Adjacent session history prefetch stopped', { sessionId, error }); }); diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index a22bafa49a..ba63634da5 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:416c934dda520065" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:a7e5f2b6b738cb96" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -217,6 +217,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "user_question_interaction_v1", "ssh_none_auth_v1", "terminal_cursor_replay_v1", + "git_tracked_change_count_v1", ] as const; export type PeerHostCapabilityId = (typeof PEER_HOST_CAPABILITY_IDS)[number]; @@ -272,6 +273,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "user_question_response", "user_question_interaction_v1", "ssh_none_auth_v1", + "git_tracked_change_count_v1", ], cli: [ "model_routing_v1", @@ -300,6 +302,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "user_question_response", "user_question_interaction_v1", "terminal_cursor_replay_v1", + "git_tracked_change_count_v1", ], }; diff --git a/src/web-ui/src/infrastructure/api/service-api/GitAPI.ts b/src/web-ui/src/infrastructure/api/service-api/GitAPI.ts index e1b7ac47e1..0537eac8e0 100644 --- a/src/web-ui/src/infrastructure/api/service-api/GitAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/GitAPI.ts @@ -230,6 +230,12 @@ export interface GitTrustOutcome { } export class GitAPI { + async getTrackedChangeCount(workspaceId: string): Promise { + return invokePrepared('git_get_tracked_change_count', async () => ({ + request: { workspaceId }, + }), { timeout: 8_000 }); + } + private repositoryProbeCache = new Map{{fileCount}} changed file hasn’t been committed.", + "workspaceChanges_other": "The workspace is stirring. {{fileCount}} changed files haven’t been committed.", "openingWorkspace": "Let's get to work in {{workspace}}.", "openingMorning": "Good morning. The day starts with you.", "openingAfternoon": "Good afternoon. Let's make today a little more interesting.", diff --git a/src/web-ui/src/locales/en-US/panels/files.json b/src/web-ui/src/locales/en-US/panels/files.json index 4373226ffd..9a783dabad 100644 --- a/src/web-ui/src/locales/en-US/panels/files.json +++ b/src/web-ui/src/locales/en-US/panels/files.json @@ -99,7 +99,8 @@ "loadingFileTree": "Loading file tree..." }, "empty": { - "selectWorkspace": "File tree will be displayed after selecting a workspace" + "selectWorkspace": "File tree will be displayed after selecting a workspace", + "directoryUnavailable": "The selected directory is unavailable." }, "dialog": { "newFile": { diff --git a/src/web-ui/src/locales/en-US/scenes/project-resources.json b/src/web-ui/src/locales/en-US/scenes/project-resources.json index 85deac09b1..efecc7aa17 100644 --- a/src/web-ui/src/locales/en-US/scenes/project-resources.json +++ b/src/web-ui/src/locales/en-US/scenes/project-resources.json @@ -33,7 +33,6 @@ "primary": "Primary directory", "related": "Associated directory", "openDirectory": "Open directory {{name}}", - "editDirectory": "Edit directory {{name}}", "scrollPrevious": "Previous directories", "scrollNext": "Next directories", "add": "Add directory", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index f88cd70512..c89a682dca 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -400,6 +400,7 @@ "duplicateEmpty": "请发送消息后再复制该会话。", "duplicateRunning": "请等待当前对话结束后再复制该会话。", "duplicateDispatchUnsupported": "运行在其他设备上的会话无法复制。", + "dispatchMutationUnsupported": "请在任务所属设备上归档或删除此会话。", "openStorageDirectory": "打开会话存储目录", "openStorageDirectoryFailed": "打开会话存储目录失败", "storageDirectoryDesktopOnly": "仅支持打开存储在当前桌面实例上的会话目录。", @@ -407,7 +408,7 @@ "exportMarkdown": "导出为 Markdown", "exportMarkdownFull": "导出完整过程", "exportMarkdownResult": "导出结果", - "delete": "删除", + "delete": "删除会话", "deleteConfirmTitle": "删除会话", "deleteConfirmMessage": "会话及其子会话将被永久删除,无法恢复。", "confirmEdit": "确认", diff --git a/src/web-ui/src/locales/zh-CN/flow-chat.json b/src/web-ui/src/locales/zh-CN/flow-chat.json index 5634798531..41dae38327 100644 --- a/src/web-ui/src/locales/zh-CN/flow-chat.json +++ b/src/web-ui/src/locales/zh-CN/flow-chat.json @@ -3505,6 +3505,8 @@ }, "welcome": { "openingWorkspace": "在 {{workspace}},开工。", + "workspaceChanges_one": "工作区有动静,{{fileCount}} 个文件改了还没提交。", + "workspaceChanges_other": "工作区有动静,{{fileCount}} 个文件改了还没提交。", "openingMorning": "早安,今天由你开场。", "openingAfternoon": "下午好,给今天加点意思。", "openingEvening": "晚上好,按你的节奏来。", diff --git a/src/web-ui/src/locales/zh-CN/panels/files.json b/src/web-ui/src/locales/zh-CN/panels/files.json index 32486c52ca..3ed45f1ca9 100644 --- a/src/web-ui/src/locales/zh-CN/panels/files.json +++ b/src/web-ui/src/locales/zh-CN/panels/files.json @@ -99,7 +99,8 @@ "loadingFileTree": "正在加载文件树..." }, "empty": { - "selectWorkspace": "选择工作区后将显示文件树" + "selectWorkspace": "选择工作区后将显示文件树", + "directoryUnavailable": "所选目录不可用。" }, "dialog": { "newFile": { diff --git a/src/web-ui/src/locales/zh-CN/scenes/project-resources.json b/src/web-ui/src/locales/zh-CN/scenes/project-resources.json index 0aacbf79b0..a545c39efd 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/project-resources.json +++ b/src/web-ui/src/locales/zh-CN/scenes/project-resources.json @@ -33,7 +33,6 @@ "primary": "主目录", "related": "关联目录", "openDirectory": "打开目录 {{name}}", - "editDirectory": "编辑目录 {{name}}", "scrollPrevious": "查看前面的目录", "scrollNext": "查看后面的目录", "add": "添加目录", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index d3f655f8b2..ece3f565b2 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -400,6 +400,7 @@ "duplicateEmpty": "請傳送訊息後再複製該會話。", "duplicateRunning": "請等待目前對話結束後再複製該會話。", "duplicateDispatchUnsupported": "執行在其他裝置上的會話無法複製。", + "dispatchMutationUnsupported": "請在任務所屬裝置上歸檔或刪除此會話。", "openStorageDirectory": "開啟會話儲存目錄", "openStorageDirectoryFailed": "開啟會話儲存目錄失敗", "storageDirectoryDesktopOnly": "僅支援開啟儲存在目前桌面執行個體上的會話目錄。", @@ -407,7 +408,7 @@ "exportMarkdown": "匯出為 Markdown", "exportMarkdownFull": "匯出完整過程", "exportMarkdownResult": "匯出結果", - "delete": "刪除", + "delete": "刪除會話", "deleteConfirmTitle": "刪除會話", "deleteConfirmMessage": "會話及其子會話將被永久刪除,無法復原。", "confirmEdit": "確認", diff --git a/src/web-ui/src/locales/zh-TW/flow-chat.json b/src/web-ui/src/locales/zh-TW/flow-chat.json index fbe36338c7..55b8dd356d 100644 --- a/src/web-ui/src/locales/zh-TW/flow-chat.json +++ b/src/web-ui/src/locales/zh-TW/flow-chat.json @@ -3504,6 +3504,8 @@ } }, "welcome": { + "workspaceChanges_one": "工作區有動靜,{{fileCount}} 個檔案改了還沒提交。", + "workspaceChanges_other": "工作區有動靜,{{fileCount}} 個檔案改了還沒提交。", "openingWorkspace": "在 {{workspace}},開工。", "openingMorning": "早安,今天由你開場。", "openingAfternoon": "下午好,給今天加點意思。", diff --git a/src/web-ui/src/locales/zh-TW/panels/files.json b/src/web-ui/src/locales/zh-TW/panels/files.json index 71e0d02a44..bc3b9e4bf3 100644 --- a/src/web-ui/src/locales/zh-TW/panels/files.json +++ b/src/web-ui/src/locales/zh-TW/panels/files.json @@ -99,7 +99,8 @@ "loadingFileTree": "正在載入檔案樹..." }, "empty": { - "selectWorkspace": "選擇工作區後將顯示檔案樹" + "selectWorkspace": "選擇工作區後將顯示檔案樹", + "directoryUnavailable": "所選目錄無法使用。" }, "dialog": { "newFile": { diff --git a/src/web-ui/src/locales/zh-TW/scenes/project-resources.json b/src/web-ui/src/locales/zh-TW/scenes/project-resources.json index 54f2e50e93..645ef3f0c0 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/project-resources.json +++ b/src/web-ui/src/locales/zh-TW/scenes/project-resources.json @@ -33,7 +33,6 @@ "primary": "主目錄", "related": "關聯目錄", "openDirectory": "開啟目錄 {{name}}", - "editDirectory": "編輯目錄 {{name}}", "scrollPrevious": "查看前面的目錄", "scrollNext": "查看後面的目錄", "add": "新增目錄", diff --git a/src/web-ui/src/tools/file-explorer/controller/ExplorerController.test.ts b/src/web-ui/src/tools/file-explorer/controller/ExplorerController.test.ts index 6d105b5704..ca96270261 100644 --- a/src/web-ui/src/tools/file-explorer/controller/ExplorerController.test.ts +++ b/src/web-ui/src/tools/file-explorer/controller/ExplorerController.test.ts @@ -206,4 +206,26 @@ describe('ExplorerController startup observability', () => { expect(unwatchSrc).toHaveBeenCalledTimes(1); expect(provider.watch).not.toHaveBeenCalled(); }); + + it('does not restart watchers when a directory read finishes after leaving its tree', async () => { + let finishDirectory!: (nodes: Awaited>) => void; + const unwatch = vi.fn(); + const provider: ExplorerFileSystemProvider = { + getChildren: vi.fn(({ path }) => path === '/reference' + ? Promise.resolve([{ path: '/reference/docs', name: 'docs', isDirectory: true }]) + : new Promise(resolve => { finishDirectory = resolve; })), + watch: vi.fn(() => unwatch), + }; + const controller = new ExplorerController(provider); + await controller.configure({ rootPath: '/reference', workspaceId: 'project' }); + + const expansion = controller.expandFolderLazy('/reference/docs'); + controller.dispose(); + expect(unwatch).toHaveBeenCalled(); + vi.mocked(provider.watch).mockClear(); + finishDirectory([]); + await expansion; + + expect(provider.watch).not.toHaveBeenCalled(); + }); }); diff --git a/src/web-ui/src/tools/file-explorer/controller/ExplorerController.ts b/src/web-ui/src/tools/file-explorer/controller/ExplorerController.ts index 23702bf12b..95d1ea915d 100644 --- a/src/web-ui/src/tools/file-explorer/controller/ExplorerController.ts +++ b/src/web-ui/src/tools/file-explorer/controller/ExplorerController.ts @@ -610,7 +610,7 @@ export class ExplorerController { private syncWatchers(): void { const rootPath = this.config.rootPath; - if (!rootPath || !this.config.enableAutoWatch) { + if (this.disposed || !rootPath || !this.config.enableAutoWatch) { this.stopWatchers(); return; } @@ -663,6 +663,6 @@ export class ExplorerController { } private isGenerationCurrent(generation: number, rootPath: string): boolean { - return generation === this.generation && pathsEquivalentFs(this.config.rootPath ?? '', rootPath); + return !this.disposed && generation === this.generation && pathsEquivalentFs(this.config.rootPath ?? '', rootPath); } } diff --git a/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.test.tsx b/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.test.tsx new file mode 100644 index 0000000000..a8e5c8ef5e --- /dev/null +++ b/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.test.tsx @@ -0,0 +1,135 @@ +// @vitest-environment jsdom + +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; +import { gitEventService } from '../services/GitEventService'; +import { useTrackedChangeCount } from './useTrackedChangeCount'; + +const mocks = vi.hoisted(() => ({ + getTrackedChangeCount: vi.fn<(id: string) => Promise>(), + peer: vi.fn(), + desktop: true, +})); +vi.mock('@/infrastructure/api/service-api/GitAPI', () => ({ + gitAPI: { getTrackedChangeCount: mocks.getTrackedChangeCount }, + gitWorkspaceKey: ({ workspaceId }: { workspaceId: string }) => workspaceId, +})); +vi.mock('@/infrastructure/peer-device/peerDeviceContextState', () => ({ + usePeerDeviceModeOptional: mocks.peer, +})); +vi.mock('@/infrastructure/runtime', () => ({ isTauriRuntime: () => mocks.desktop })); + +function Count({ id, remote = false }: { id: string; remote?: boolean }) { + return {useTrackedChangeCount(id, remote)}; +} + +async function advance(ms: number) { + await act(async () => { await vi.advanceTimersByTimeAsync(ms); }); +} + +describe('welcome tracked change count', () => { + let container: HTMLDivElement; + let root: Root; + + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true; + activateSurface('local'); + vi.useFakeTimers(); + mocks.getTrackedChangeCount.mockReset(); + mocks.peer.mockReturnValue(null); + mocks.desktop = true; + container = document.createElement('div'); + root = createRoot(container); + }); + + afterEach(() => { + act(() => root.unmount()); + vi.useRealTimers(); + }); + + it('coalesces visible readers, caches the result and never polls', async () => { + mocks.getTrackedChangeCount.mockResolvedValue(3); + await act(async () => root.render(<>)); + expect(mocks.getTrackedChangeCount).not.toHaveBeenCalled(); + await advance(200); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledExactlyOnceWith('same'); + expect(container.textContent).toBe('33'); + + await act(async () => root.render(null)); + await act(async () => root.render()); + await advance(200); + expect(container.textContent).toBe('3'); + await advance(60_000); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(1); + }); + + it('refreshes after a scoped operation and ignores its superseded in-flight count', async () => { + let finishFirst!: (count: number) => void; + mocks.getTrackedChangeCount.mockImplementationOnce(() => new Promise(resolve => { finishFirst = resolve; })) + .mockResolvedValue(1); + await act(async () => root.render()); + await advance(200); + await act(async () => gitEventService.emit('operation:completed', { + repositoryPath: { workspaceId: 'repo' }, timestamp: new Date(), operationType: 'commit', + description: 'Commit', + })); + await advance(200); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(1); + await act(async () => finishFirst(8)); + expect(container.textContent).toBe(''); + await advance(200); + expect(container.textContent).toBe('1'); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(2); + }); + + it('gates old peers and ignores a response from a previous device activation', async () => { + let finishLocal!: (count: number) => void; + mocks.getTrackedChangeCount.mockImplementationOnce(() => new Promise(resolve => { finishLocal = resolve; })) + .mockResolvedValue(2); + await act(async () => root.render()); + await advance(200); + await act(async () => activateSurface('peer')); + await act(async () => finishLocal(99)); + await advance(200); + expect(container.textContent).toBe(''); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(1); + + mocks.peer.mockReturnValue({ attachments: [{ deviceId: 'peer', health: 'ready', + capabilities: { gitTrackedChangeCountV1: true, hostKind: 'cli' }, + }] }); + await act(async () => root.render()); + await advance(200); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(1); + + await act(async () => root.render()); + await advance(200); + expect(container.textContent).toBe('2'); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(2); + }); + + it('discards an old workspace result and refreshes an inactive workspace on return after a Git operation', async () => { + let finishOld!: (count: number) => void; + mocks.getTrackedChangeCount.mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve; })) + .mockResolvedValueOnce(2).mockResolvedValueOnce(0); + await act(async () => root.render()); + await advance(200); + await act(async () => root.render()); + await advance(200); + await act(async () => finishOld(99)); + expect(container.textContent).toBe('2'); + + await act(async () => root.render(null)); + await act(async () => gitEventService.emit('operation:completed', { + repositoryPath: { workspaceId: 'current' }, timestamp: new Date(), operationType: 'commit', + description: 'Commit', + })); + await advance(200); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(2); + await act(async () => root.render()); + await advance(200); + expect(container.textContent).toBe('0'); + expect(mocks.getTrackedChangeCount).toHaveBeenCalledTimes(3); + }); +}); diff --git a/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.ts b/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.ts new file mode 100644 index 0000000000..6805d2f35d --- /dev/null +++ b/src/web-ui/src/tools/git/hooks/useTrackedChangeCount.ts @@ -0,0 +1,113 @@ +import { useEffect, useState, useSyncExternalStore } from 'react'; +import { gitAPI } from '@/infrastructure/api/service-api/GitAPI'; +import { getActiveSurfaceScope, isLocalSurface, onSurfaceActivated, type SurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState'; +import { isTauriRuntime } from '@/infrastructure/runtime'; +import { BoundedResourceCache } from '@/shared/utils/BoundedResourceCache'; +import { gitEventService } from '../services/GitEventService'; + +const REFRESH_DELAY_MS = 150; +const CACHE_TTL_MS = 30_000; +const ERROR_TTL_MS = 5_000; +type Count = number | null; +type PendingCount = { invalidated: boolean; result: Promise }; + +const cache = new BoundedResourceCache(64, 64); +const pending = new Map(); + +function invalidate(key: string) { + cache.delete(key); + const request = pending.get(key); + if (request) request.invalidated = true; +} + +// A Git action in a different scene can invalidate a cached welcome count. +function invalidateWorkspaceCount({ data }: { data: { repositoryPath: { workspaceId: string } } }) { + const surface = getActiveSurfaceScope(); + invalidate(surface.key('tracked-changes', surface.epoch, data.repositoryPath.workspaceId)); +} + +const stopOperationInvalidation = gitEventService.on('operation:completed', invalidateWorkspaceCount); +const stopBranchInvalidation = gitEventService.on('branch:changed', invalidateWorkspaceCount); +import.meta.hot?.dispose(() => { + stopOperationInvalidation(); + stopBranchInvalidation(); + cache.clear(); +}); + +function readCount(key: string, workspaceId: string, surface: SurfaceScope): Promise { + const cached = cache.get(key); + if (cached && cached.expiresAt > Date.now()) return Promise.resolve(cached.count); + const existing = pending.get(key); + if (existing) return existing.result; + + const request: PendingCount = { + invalidated: false, + result: gitAPI.getTrackedChangeCount(workspaceId) + .catch(() => null) + .then(count => { + if (request.invalidated || !surface.isCurrent()) return undefined; + cache.set(key, { count, expiresAt: Date.now() + (count === null ? ERROR_TTL_MS : CACHE_TTL_MS) }); + return count; + }) + .finally(() => pending.delete(key)), + }; + pending.set(key, request); + return request.result; +} + +/** A visible welcome page reads one number without registering Git polling demand. */ +export function useTrackedChangeCount(workspaceId: string, remoteWorkspace: boolean): Count { + const surface = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope); + const peer = usePeerDeviceModeOptional(); + const attachment = peer?.attachments.find(item => item.deviceId === surface.surfaceId); + const supported = isLocalSurface(surface.surfaceId) ? isTauriRuntime() + : attachment?.health === 'ready' && attachment.capabilities?.gitTrackedChangeCountV1 === true + && !(remoteWorkspace && attachment.capabilities.hostKind === 'cli'); + const key = surface.key('tracked-changes', surface.epoch, workspaceId); + const [snapshot, setSnapshot] = useState<{ key: string; count: Count }>(); + + useEffect(() => { + if (!supported) { + invalidate(key); + setSnapshot(undefined); + return; + } + let active = true; + let timer: ReturnType | undefined; + let revision = 0; + const canRead = () => active && surface.isCurrent() && document.visibilityState !== 'hidden'; + const refresh = () => { + clearTimeout(timer); + const currentRevision = ++revision; + if (!canRead()) return; + timer = setTimeout(async () => { + if (!canRead()) return; + const count = await readCount(key, workspaceId, surface); + if (!canRead() || currentRevision !== revision) return; + // An operation invalidated this scan while it was in flight. + if (count === undefined) { + refresh(); + return; + } + setSnapshot(previous => previous?.key === key && previous.count === count ? previous : { key, count }); + }, REFRESH_DELAY_MS); + }; + const scope = { repositoryPath: { workspaceId } }; + const stopOperations = gitEventService.on('operation:completed', refresh, scope); + const stopBranchChanges = gitEventService.on('branch:changed', refresh, scope); + window.addEventListener('focus', refresh); + document.addEventListener('visibilitychange', refresh); + refresh(); + return () => { + active = false; + clearTimeout(timer); + stopOperations(); + stopBranchChanges(); + window.removeEventListener('focus', refresh); + document.removeEventListener('visibilitychange', refresh); + }; + }, [key, supported, surface, workspaceId]); + + return supported && snapshot?.key === key ? snapshot.count : null; +}