diff --git a/src/apps/desktop/src/api/commands.rs b/src/apps/desktop/src/api/commands.rs index af989e85ec..8ed0296d57 100644 --- a/src/apps/desktop/src/api/commands.rs +++ b/src/apps/desktop/src/api/commands.rs @@ -1636,6 +1636,38 @@ pub async fn set_primary_assistant_workspace( Ok(WorkspaceInfoDto::from_workspace_info(&workspace)) } +/// How deleting an assistant workspace record may touch its directory. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum AssistantWorkspaceDirectoryPlan { + /// Managed layout (current or legacy): delete the directory when present. + DeleteDirectoryWhenPresent, + /// The directory does not exist: remove the registry entry only. + RegistryEntryOnly, +} + +/// Guards `delete_assistant_workspace` against deleting arbitrary directories. +/// +/// Existing directories outside the managed assistant roots (the current +/// layout and the pre-rename layout left behind by the brand migration) are +/// refused; a record whose directory is already gone resolves to a +/// registry-only cleanup. +fn assistant_workspace_directory_plan( + path: &Path, + is_managed_path: bool, +) -> Result { + if is_managed_path { + return Ok(AssistantWorkspaceDirectoryPlan::DeleteDirectoryWhenPresent); + } + if path.exists() { + Err(format!( + "Workspace path is not a managed assistant workspace: {}", + path.display() + )) + } else { + Ok(AssistantWorkspaceDirectoryPlan::RegistryEntryOnly) + } +} + #[tauri::command] pub async fn delete_assistant_workspace( state: State<'_, AppState>, @@ -1663,15 +1695,11 @@ pub async fn delete_assistant_workspace( return Err("Primary assistant workspace cannot be deleted".to_string()); } - if !state + let is_managed_path = state .workspace_service - .is_assistant_workspace_path(&workspace_info.root_path) - { - return Err(format!( - "Workspace path is not a managed assistant workspace: {}", - workspace_info.root_path.display() - )); - } + .is_manageable_assistant_workspace_path(&workspace_info.root_path); + let directory_plan = + assistant_workspace_directory_plan(&workspace_info.root_path, is_managed_path)?; let is_active_workspace = state .workspace_service @@ -1690,11 +1718,26 @@ pub async fn delete_assistant_workspace( let workspace_path = workspace_info.root_path.to_string_lossy().to_string(); - state - .filesystem_service - .delete_directory(&workspace_path, true) - .await - .map_err(|e| format!("Failed to delete assistant workspace files: {}", e))?; + // Re-check presence so a directory that disappears between the guard and + // the deletion still resolves as a registry-only cleanup. + let delete_files = matches!( + directory_plan, + AssistantWorkspaceDirectoryPlan::DeleteDirectoryWhenPresent + ) && workspace_info.root_path.exists(); + + if delete_files { + state + .filesystem_service + .delete_directory(&workspace_path, true) + .await + .map_err(|e| format!("Failed to delete assistant workspace files: {}", e))?; + } else { + info!( + "Assistant workspace directory is missing; removing registry entry only: workspace_id={}, path={}", + request.workspace_id, + workspace_info.root_path.display() + ); + } state .workspace_service @@ -1784,6 +1827,47 @@ async fn clear_directory_contents(directory: &Path) -> Result<(), String> { Ok(()) } +#[cfg(test)] +mod assistant_workspace_delete_tests { + use super::{assistant_workspace_directory_plan, AssistantWorkspaceDirectoryPlan}; + + #[test] + fn managed_paths_may_delete_even_when_the_directory_is_missing() { + let temp = tempfile::tempdir().expect("temp root"); + let missing = temp.path().join("workspace-44e0e781"); + + assert_eq!( + assistant_workspace_directory_plan(&missing, true), + Ok(AssistantWorkspaceDirectoryPlan::DeleteDirectoryWhenPresent) + ); + } + + #[test] + fn unmanaged_existing_directories_are_refused() { + let temp = tempfile::tempdir().expect("temp root"); + let unmanaged = temp.path().join("Documents").join("foo"); + std::fs::create_dir_all(&unmanaged).expect("create unmanaged directory"); + + let error = assistant_workspace_directory_plan(&unmanaged, false) + .expect_err("an existing unmanaged directory must be refused"); + + assert!(error.starts_with("Workspace path is not a managed assistant workspace")); + assert!(error.contains(&unmanaged.to_string_lossy().to_string())); + assert!(unmanaged.exists(), "the guard must not delete anything"); + } + + #[test] + fn unmanaged_missing_records_resolve_to_registry_only_cleanup() { + let temp = tempfile::tempdir().expect("temp root"); + let orphan = temp.path().join("missing-root").join("workspace-44e0e781"); + + assert_eq!( + assistant_workspace_directory_plan(&orphan, false), + Ok(AssistantWorkspaceDirectoryPlan::RegistryEntryOnly) + ); + } +} + #[tauri::command] pub async fn reset_assistant_workspace( state: State<'_, AppState>, @@ -1805,7 +1889,7 @@ pub async fn reset_assistant_workspace( if !state .workspace_service - .is_assistant_workspace_path(&workspace_info.root_path) + .is_manageable_assistant_workspace_path(&workspace_info.root_path) { return Err(format!( "Workspace path is not a managed assistant workspace: {}", @@ -3171,7 +3255,7 @@ pub async fn reset_workspace_persona_files( }; if workspace.workspace_kind != WorkspaceKind::Assistant - || !service.is_assistant_workspace_path(&workspace.root_path) + || !service.is_manageable_assistant_workspace_path(&workspace.root_path) { return Err(format!( "Workspace {} is not a managed assistant workspace", diff --git a/src/crates/assembly/core/src/legacy_migration/assistant_workspace_root.rs b/src/crates/assembly/core/src/legacy_migration/assistant_workspace_root.rs new file mode 100644 index 0000000000..eb5f85804a --- /dev/null +++ b/src/crates/assembly/core/src/legacy_migration/assistant_workspace_root.rs @@ -0,0 +1,58 @@ +//! Pre-rename personal-assistant root for records the data migrator left behind. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +/// `~/.bitfun/personal_assistant/`. +/// +/// `BITFUN_HOME` / `BITFUN_E2E_HOME` replace the `.bitfun` data root itself, +/// with the precedence of `MigrationRoots` in `openbitfun-legacy-migration`, so +/// both sides resolve one root. That crate stays an offline dependency, which +/// is why the resolution is repeated here. Returns `None` when no user home +/// directory is available. +pub(crate) fn legacy_assistant_workspace_root() -> Option { + resolve_root( + std::env::var_os("BITFUN_HOME"), + std::env::var_os("BITFUN_E2E_HOME"), + dirs::home_dir().as_deref(), + ) +} + +fn resolve_root( + bitfun_home: Option, + bitfun_e2e_home: Option, + user_home: Option<&Path>, +) -> Option { + let non_empty = + |value: Option| value.filter(|path| !path.is_empty()).map(PathBuf::from); + let legacy_home_root = non_empty(bitfun_home) + .or_else(|| non_empty(bitfun_e2e_home)) + .or_else(|| user_home.map(|home| home.join(".bitfun")))?; + Some(legacy_home_root.join("personal_assistant")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn root_follows_the_migrator_data_root_precedence() { + let home = Path::new("/home/dev"); + let explicit = OsString::from("/custom/legacy"); + let e2e = OsString::from("/e2e/legacy"); + + assert_eq!( + resolve_root(Some(explicit), Some(e2e.clone()), Some(home)), + Some(PathBuf::from("/custom/legacy/personal_assistant")) + ); + assert_eq!( + resolve_root(Some(OsString::new()), Some(e2e), Some(home)), + Some(PathBuf::from("/e2e/legacy/personal_assistant")) + ); + assert_eq!( + resolve_root(None, None, Some(home)), + Some(PathBuf::from("/home/dev/.bitfun/personal_assistant")) + ); + assert_eq!(resolve_root(None, None, None), None); + } +} diff --git a/src/crates/assembly/core/src/legacy_migration/mod.rs b/src/crates/assembly/core/src/legacy_migration/mod.rs index 128df8d991..3348fe1986 100644 --- a/src/crates/assembly/core/src/legacy_migration/mod.rs +++ b/src/crates/assembly/core/src/legacy_migration/mod.rs @@ -1,2 +1,7 @@ -//! Compatibility export; the standalone migration service owns these adapters. +//! Pre-rename data boundary. The adapters are a compatibility export; the +//! standalone migration service owns them. +mod assistant_workspace_root; + +pub(crate) use assistant_workspace_root::legacy_assistant_workspace_root; +#[cfg(feature = "legacy-migration")] pub use openbitfun_legacy_migration_adapters::adapters_for_groups; diff --git a/src/crates/assembly/core/src/lib.rs b/src/crates/assembly/core/src/lib.rs index 784e6e8188..9ad531279c 100644 --- a/src/crates/assembly/core/src/lib.rs +++ b/src/crates/assembly/core/src/lib.rs @@ -32,7 +32,6 @@ pub mod function_agents; // Function-based agents pub mod infrastructure; // AI clients, storage, logging, events #[cfg(feature = "external-sources")] mod instruction_sources; -#[cfg(feature = "legacy-migration")] pub mod legacy_migration; #[cfg(feature = "tools-miniapp")] pub mod miniapp; // AI-generated instant apps (Zero-Dialect Runtime) diff --git a/src/crates/assembly/core/src/service/workspace/service.rs b/src/crates/assembly/core/src/service/workspace/service.rs index 03deea13c4..e4d2243459 100644 --- a/src/crates/assembly/core/src/service/workspace/service.rs +++ b/src/crates/assembly/core/src/service/workspace/service.rs @@ -16,6 +16,7 @@ use super::persistence::{ use super::WorktreeTopologyFreshness; use crate::infrastructure::storage::{PersistenceService, StorageOptions}; use crate::infrastructure::{try_get_path_manager_arc, PathManager}; +use crate::legacy_migration::legacy_assistant_workspace_root; use crate::service::bootstrap::{ ensure_workspace_gitignore_ignores_openbitfun, initialize_workspace_persona_files, }; @@ -139,6 +140,43 @@ struct AssistantWorkspaceDescriptor { display_name: String, } +/// Assistant workspace layout check against one personal-assistant root. +/// +/// A path belongs to the layout when it is the default `/workspace` +/// directory or a named `/workspace-` sibling. Comparison is +/// literal, matching how those directories are created and how their paths +/// are persisted in workspace records; the directory does not need to exist. +/// The current root and the pre-rename root are checked with the same layout +/// rules, so records written before the brand migration stay recognizable. +fn assistant_descriptor_in_root( + path: &Path, + assistant_root: &Path, +) -> Option { + if path == assistant_root.join("workspace") { + return Some(AssistantWorkspaceDescriptor { + path: path.to_path_buf(), + assistant_id: None, + display_name: WorkspaceService::assistant_display_name(None), + }); + } + + if path.parent()? != assistant_root { + return None; + } + + let file_name = path.file_name()?.to_string_lossy(); + let assistant_id = file_name.strip_prefix("workspace-")?; + if assistant_id.trim().is_empty() { + return None; + } + + Some(AssistantWorkspaceDescriptor { + path: path.to_path_buf(), + assistant_id: Some(assistant_id.to_string()), + display_name: WorkspaceService::assistant_display_name(Some(assistant_id)), + }) +} + impl WorkspaceService { fn normalize_workspace_name(name: String) -> OpenBitFunResult { let name = name.trim(); @@ -2159,31 +2197,7 @@ impl WorkspaceService { } fn assistant_descriptor_from_path(&self, path: &Path) -> Option { - let default_workspace = self.path_manager.default_assistant_workspace_dir(None); - if path == default_workspace { - return Some(AssistantWorkspaceDescriptor { - path: path.to_path_buf(), - assistant_id: None, - display_name: Self::assistant_display_name(None), - }); - } - - let assistant_root = self.path_manager.assistant_workspace_base_dir(None); - if path.parent()? != assistant_root { - return None; - } - - let file_name = path.file_name()?.to_string_lossy(); - let assistant_id = file_name.strip_prefix("workspace-")?; - if assistant_id.trim().is_empty() { - return None; - } - - Some(AssistantWorkspaceDescriptor { - path: path.to_path_buf(), - assistant_id: Some(assistant_id.to_string()), - display_name: Self::assistant_display_name(Some(assistant_id)), - }) + assistant_descriptor_in_root(path, &self.path_manager.assistant_workspace_base_dir(None)) } fn normalize_workspace_options_for_path( @@ -2419,6 +2433,21 @@ impl WorkspaceService { self.assistant_descriptor_from_path(path).is_some() } + /// Returns whether a path is an assistant workspace record the product can + /// still manage: either the current layout or the pre-rename layout left + /// behind by the brand migration. Deletion and reset guards must accept + /// both so a pre-migration record stays an explicit user action + /// instead of being rejected as an unmanaged path. + pub fn is_manageable_assistant_workspace_path(&self, path: &Path) -> bool { + self.is_assistant_workspace_path(path) || self.is_legacy_assistant_workspace_path(path) + } + + fn is_legacy_assistant_workspace_path(&self, path: &Path) -> bool { + legacy_assistant_workspace_root().is_some_and(|assistant_root| { + assistant_descriptor_in_root(path, &assistant_root).is_some() + }) + } + /// Clears all persisted data. pub async fn clear_persistent_data(&self) -> OpenBitFunResult<()> { self.persistence @@ -3825,6 +3854,114 @@ mod tests { Some("Legacy TypeScript implementation".to_string()) ); } + + #[test] + fn assistant_layout_check_accepts_only_managed_layouts_under_its_root() { + let temp = tempfile::tempdir().expect("temp root"); + let assistant_root = temp.path().join(".legacy-data").join("personal_assistant"); + + let named = assistant_root.join("workspace-abc"); + assert_eq!( + assistant_descriptor_in_root(&named, &assistant_root) + .expect("named legacy layout should be recognized") + .assistant_id + .as_deref(), + Some("abc") + ); + assert!( + assistant_descriptor_in_root(&assistant_root.join("workspace"), &assistant_root) + .is_some(), + "default legacy layout should be recognized" + ); + assert!( + assistant_descriptor_in_root(&assistant_root.join("workspace-"), &assistant_root) + .is_none(), + "a blank assistant id must not be recognized" + ); + assert!( + assistant_descriptor_in_root( + &temp + .path() + .join(".legacy-data") + .join("other") + .join("workspace-x"), + &assistant_root + ) + .is_none(), + "directories outside the personal_assistant root must be rejected" + ); + assert!( + assistant_descriptor_in_root( + &temp.path().join("Documents").join("foo"), + &assistant_root + ) + .is_none(), + "unrelated directories must be rejected" + ); + } + + #[tokio::test] + async fn manageable_check_still_accepts_current_assistant_layout() { + let env = TestEnvironment::new(); + let service = build_test_workspace_service(env.path_manager.clone()).await; + let assistant_root = env.path_manager.assistant_workspace_base_dir(None); + let named = assistant_root.join("workspace-current-id"); + + assert!(service.is_manageable_assistant_workspace_path(&named)); + assert!(service.is_manageable_assistant_workspace_path( + &env.path_manager.default_assistant_workspace_dir(None) + )); + assert!( + !service.is_manageable_assistant_workspace_path(&named.join("child")), + "paths below an assistant workspace are not assistant workspaces" + ); + assert!(!service + .is_manageable_assistant_workspace_path(&env.root.join("Documents").join("foo"))); + assert_eq!( + service.is_manageable_assistant_workspace_path(&named), + service.is_assistant_workspace_path(&named), + "current-layout behavior must not regress" + ); + } + + #[tokio::test] + async fn manageable_check_accepts_legacy_assistant_roots() { + let env = TestEnvironment::new(); + let service = build_test_workspace_service(env.path_manager.clone()).await; + let legacy_assistant_root = + legacy_assistant_workspace_root().expect("legacy assistant root"); + + assert!( + service.is_manageable_assistant_workspace_path( + &legacy_assistant_root.join("workspace-44e0e781") + ), + "pre-rename assistant workspaces must stay manageable" + ); + assert!( + service + .is_manageable_assistant_workspace_path(&legacy_assistant_root.join("workspace")), + "the legacy default assistant workspace must stay manageable" + ); + assert!( + !service.is_assistant_workspace_path(&legacy_assistant_root.join("workspace-44e0e781")), + "legacy paths must not be classified as current assistant workspaces" + ); + assert!( + !service.is_manageable_assistant_workspace_path( + &legacy_assistant_root + .parent() + .expect("legacy data root") + .join("other") + .join("workspace-x") + ), + "directories outside the legacy personal_assistant root must be rejected" + ); + assert!( + !service + .is_manageable_assistant_workspace_path(&env.root.join("Documents").join("foo")), + "unrelated directories must be rejected" + ); + } } fn workspace_catalog_revision() -> &'static tokio::sync::watch::Sender { 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 9e4465bfc5..5a13def3bc 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -999,6 +999,134 @@ describe('FlowChatStore session removal active selection', () => { }); }); +describe('FlowChatStore session deletion persistence', () => { + beforeEach(() => { + apiMocks.deleteSession.mockClear(); + }); + + afterEach(() => { + resetStore(); + }); + + it('deletes a session without any workspace path by workspace ID', async () => { + // Regression: invalid session projects (lost workspace directory) keep + // their workspace ID but have no path fields; the ID-first backend API + // must still be called instead of failing on the missing path. + const session = createSession({ + sessionId: 'orphan-1', + title: 'Orphaned session', + workspacePath: undefined, + config: { agentType: 'Standard' }, + }); + expect(session.workspaceId).toBeTruthy(); + expect(session.projectWorkspacePath).toBeUndefined(); + expect(session.config.workspacePath).toBeUndefined(); + + flowChatStore.setState(() => ({ + sessions: new Map([[session.sessionId, session]]), + activeSessionId: session.sessionId, + })); + + await flowChatStore.deleteSession('orphan-1', { nextActiveSessionId: null }); + + expect(apiMocks.deleteSession).toHaveBeenCalledTimes(1); + expect(apiMocks.deleteSession).toHaveBeenCalledWith('orphan-1', session.workspaceId); + expect(flowChatStore.getState().sessions.has('orphan-1')).toBe(false); + expect(flowChatStore.getState().activeSessionId).toBeNull(); + }); + + it('rejects loudly and keeps a pre-ID session when no workspace ID exists', async () => { + const session = createSession({ + sessionId: 'pre-id-1', + title: 'Pre-ID session', + workspaceId: undefined, + workspacePath: undefined, + config: { agentType: 'Standard' }, + }); + + flowChatStore.setState(() => ({ + sessions: new Map([[session.sessionId, session]]), + activeSessionId: session.sessionId, + })); + + await expect(flowChatStore.deleteSession('pre-id-1')).rejects.toThrow( + 'Workspace ID is unavailable for session: pre-id-1', + ); + expect(apiMocks.deleteSession).not.toHaveBeenCalled(); + expect(flowChatStore.getState().sessions.has('pre-id-1')).toBe(true); + }); + + it('keeps a pathless session when the backend delete rejects', async () => { + apiMocks.deleteSession.mockRejectedValueOnce(new Error('backend unavailable')); + const session = createSession({ + sessionId: 'reject-1', + title: 'Rejected session', + workspacePath: undefined, + config: { agentType: 'Standard' }, + }); + + flowChatStore.setState(() => ({ + sessions: new Map([[session.sessionId, session]]), + activeSessionId: session.sessionId, + })); + + await expect(flowChatStore.deleteSession('reject-1', { nextActiveSessionId: null })) + .rejects.toThrow('backend unavailable'); + + expect(apiMocks.deleteSession).toHaveBeenCalledWith('reject-1', session.workspaceId); + expect(flowChatStore.getState().sessions.has('reject-1')).toBe(true); + expect(flowChatStore.getState().activeSessionId).toBe('reject-1'); + }); + + it('resolves without error when all backend deletes succeed', async () => { + const session = createSession({ sessionId: 'success-1', title: 'Success session' }); + + flowChatStore.setState(() => ({ + sessions: new Map([[session.sessionId, session]]), + activeSessionId: session.sessionId, + })); + + await expect(flowChatStore.deleteSession('success-1', { nextActiveSessionId: null })) + .resolves.toBeUndefined(); + + expect(apiMocks.deleteSession).toHaveBeenCalledTimes(1); + expect(apiMocks.deleteSession).toHaveBeenCalledWith('success-1', session.workspaceId); + expect(flowChatStore.getState().sessions.has('success-1')).toBe(false); + expect(flowChatStore.getState().activeSessionId).toBeNull(); + }); + + it('deletes every cascade member by workspace ID even when children lack paths', async () => { + const parent = createSession({ + sessionId: 'cascade-parent', + title: 'Cascade parent', + workspacePath: undefined, + config: { agentType: 'Standard' }, + }); + const child = createSession({ + sessionId: 'cascade-child', + title: 'Cascade child', + parentSessionId: 'cascade-parent', + workspacePath: undefined, + config: { agentType: 'Standard' }, + }); + + flowChatStore.setState(() => ({ + sessions: new Map([ + [parent.sessionId, parent], + [child.sessionId, child], + ]), + activeSessionId: parent.sessionId, + })); + + await flowChatStore.deleteSession('cascade-parent', { nextActiveSessionId: null }); + + expect(apiMocks.deleteSession).toHaveBeenCalledTimes(2); + expect(apiMocks.deleteSession).toHaveBeenCalledWith('cascade-parent', parent.workspaceId); + expect(apiMocks.deleteSession).toHaveBeenCalledWith('cascade-child', child.workspaceId); + expect(Array.from(flowChatStore.getState().sessions.keys())).toEqual([]); + }); +}); + describe('FlowChatStore token usage', () => { afterEach(() => { resetStore(); diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 15da114de7..0031057a50 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -5408,9 +5408,9 @@ export class FlowChatStore { scope.assertCurrent('delete session'); const sess = this.state.sessions.get(id); if (sess?.draft?.phase !== 'editing') { - if (!sess || !sessionProjectWorkspacePath(sess)) { - throw new Error(`Workspace path not found for session ${id}`); - } + // Session storage is resolved by workspace ID, so a session whose + // workspace directory is gone must still reach the backend. Pre-ID + // sessions fail loudly in sessionHistoryWorkspaceId. await agentAPI.deleteSession(id, this.sessionHistoryWorkspaceId(id)); scope.assertCurrent('complete session deletion'); }