Skip to content
Merged
114 changes: 99 additions & 15 deletions src/apps/desktop/src/api/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AssistantWorkspaceDirectoryPlan, String> {
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>,
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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>,
Expand All @@ -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: {}",
Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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<PathBuf> {
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<OsString>,
bitfun_e2e_home: Option<OsString>,
user_home: Option<&Path>,
) -> Option<PathBuf> {
let non_empty =
|value: Option<OsString>| 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);
}
}
7 changes: 6 additions & 1 deletion src/crates/assembly/core/src/legacy_migration/mod.rs
Original file line number Diff line number Diff line change
@@ -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;
1 change: 0 additions & 1 deletion src/crates/assembly/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading