From 08df524a24e4020bb15e48e120b32e4223ad5062 Mon Sep 17 00:00:00 2001 From: wsp Date: Mon, 23 Nov 2026 18:36:16 +0800 Subject: [PATCH 1/2] fix(snapshot): Bound memory use for file history --- .../tools/implementations/file_edit_tool.rs | 19 +- .../tools/implementations/file_write_tool.rs | 4 +- .../assembly/core/src/service/snapshot/mod.rs | 1 + .../core/src/service/snapshot/service.rs | 3 +- .../src/service/snapshot/snapshot_core.rs | 23 +- .../src/service/snapshot/snapshot_system.rs | 614 +++++++++++++----- .../core/src/service/snapshot/storage.rs | 218 +++++++ .../core/src/service/snapshot/types.rs | 30 + .../service/snapshot/workspace_io_tests.rs | 59 ++ 9 files changed, 796 insertions(+), 175 deletions(-) create mode 100644 src/crates/assembly/core/src/service/snapshot/storage.rs diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/file_edit_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/file_edit_tool.rs index f113cdcfd8..a9c81eb326 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/file_edit_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/file_edit_tool.rs @@ -50,16 +50,29 @@ impl FileEditTool { context: &ToolUseContext, resolved: &ToolPathResolution, ) -> OpenBitFunResult { - context + const MAX_EDIT_BYTES: usize = 8 * 1024 * 1024; + let bytes = context .file_system_for_path(resolved)? - .read_file_text(&resolved.resolved_path) + .read_file_bounded(&resolved.resolved_path, MAX_EDIT_BYTES) .await .map_err(|error| { OpenBitFunError::tool(format!( "Failed to read file {}: {:#}", resolved.logical_path, error )) - }) + })? + .ok_or_else(|| { + OpenBitFunError::tool(format!( + "Edit exceeds the {MAX_EDIT_BYTES} byte limit for {}", + resolved.logical_path + )) + })?; + String::from_utf8(bytes).map_err(|error| { + OpenBitFunError::tool(format!( + "Failed to decode {} as UTF-8: {error}", + resolved.logical_path + )) + }) } } diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/file_write_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/file_write_tool.rs index 92cec33c49..be6895d4f1 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/file_write_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/file_write_tool.rs @@ -79,7 +79,7 @@ impl FileWriteTool { ) -> OpenBitFunResult { let existing = context .file_system_for_path(resolved)? - .read_file(&resolved.resolved_path) + .read_file_bounded(&resolved.resolved_path, content.len()) .await .map_err(|error| { OpenBitFunError::tool(format!( @@ -87,7 +87,7 @@ impl FileWriteTool { resolved.logical_path, error )) })?; - Ok(existing == content.as_bytes()) + Ok(existing.as_deref() == Some(content.as_bytes())) } pub(crate) async fn preflight_write_error( diff --git a/src/crates/assembly/core/src/service/snapshot/mod.rs b/src/crates/assembly/core/src/service/snapshot/mod.rs index b1c006c86e..411d17bf57 100644 --- a/src/crates/assembly/core/src/service/snapshot/mod.rs +++ b/src/crates/assembly/core/src/service/snapshot/mod.rs @@ -5,6 +5,7 @@ pub mod manager; pub mod service; pub mod snapshot_core; pub mod snapshot_system; +pub(crate) mod storage; pub mod types; #[cfg(test)] diff --git a/src/crates/assembly/core/src/service/snapshot/service.rs b/src/crates/assembly/core/src/service/snapshot/service.rs index e31fac0a09..a4c20221f0 100644 --- a/src/crates/assembly/core/src/service/snapshot/service.rs +++ b/src/crates/assembly/core/src/service/snapshot/service.rs @@ -56,10 +56,11 @@ impl SnapshotService { workspace_dir.clone(), runtime_context.clone(), ))); - let snapshot_system = match &workspace_fs { + let mut snapshot_system = match &workspace_fs { Some(fs) => FileSnapshotSystem::with_workspace_fs(runtime_context.clone(), fs.clone()), None => FileSnapshotSystem::new(runtime_context.clone()), }; + snapshot_system.set_capture_budget_mb(config.max_snapshot_size_mb); let snapshot_core = Arc::new(RwLock::new(SnapshotCore::new( runtime_context.clone(), snapshot_system, diff --git a/src/crates/assembly/core/src/service/snapshot/snapshot_core.rs b/src/crates/assembly/core/src/service/snapshot/snapshot_core.rs index 007d224f0c..3af33cbff6 100644 --- a/src/crates/assembly/core/src/service/snapshot/snapshot_core.rs +++ b/src/crates/assembly/core/src/service/snapshot/snapshot_core.rs @@ -546,20 +546,9 @@ impl SnapshotCore { "Found baseline snapshot: file_path={:?} baseline_id={}", file_path, baseline_id ); - match self - .snapshot_system + self.snapshot_system .get_snapshot_content(&baseline_id) - .await - { - Ok(content) => content, - Err(e) => { - warn!( - "Failed to read baseline snapshot: baseline_id={} error={}", - baseline_id, e - ); - String::new() - } - } + .await? } else { debug!( "No baseline snapshot found, file may not have been modified: file_path={:?}", @@ -600,13 +589,13 @@ impl SnapshotCore { }; let before = self - .load_snapshot_text(boundary.before_snapshot_id.as_deref()) - .await; + .read_recorded_snapshot_text(boundary.before_snapshot_id.as_deref()) + .await?; let after = if boundary.file_deleted_in_session { String::new() } else { - self.load_snapshot_text(boundary.after_snapshot_id.as_deref()) - .await + self.read_recorded_snapshot_text(boundary.after_snapshot_id.as_deref()) + .await? }; debug!( diff --git a/src/crates/assembly/core/src/service/snapshot/snapshot_system.rs b/src/crates/assembly/core/src/service/snapshot/snapshot_system.rs index f233997e59..d0a11f2ae1 100644 --- a/src/crates/assembly/core/src/service/snapshot/snapshot_system.rs +++ b/src/crates/assembly/core/src/service/snapshot/snapshot_system.rs @@ -1,13 +1,15 @@ +use super::storage::{ + descriptor, limit_error, read_bounded, write_atomic, CONTENT_JOBS, CONTENT_LIMIT, +}; use crate::service::snapshot::isolation_manager::IsolationManager; use crate::service::snapshot::types::{ - FileMetadata, FileSnapshot, OptimizedContent, SnapshotError, SnapshotResult, SnapshotType, - StorageStats, + FileMetadata, FileSnapshot, SnapshotError, SnapshotResult, SnapshotType, StorageStats, }; use crate::service::workspace_runtime::{WorkspaceRuntimeContext, WorkspaceRuntimeTarget}; use log::{debug, error, info, warn}; use openbitfun_runtime_ports::{WorkspaceFileSystem, WorkspaceMetadata, WorkspacePathKind}; use openbitfun_services_core::workspace::LocalWorkspaceFs; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::ffi::OsString; use std::fs; use std::path::{Path, PathBuf}; @@ -92,8 +94,17 @@ impl BaselineCache { continue; } - let content = fs::read_to_string(&path).ok()?; - let metadata: FileSnapshot = serde_json::from_str(&content).ok()?; + let metadata = match descriptor(&path) { + Ok(metadata) => metadata, + Err(error) => { + warn!( + "Skipping unavailable baseline {}: {}", + path.display(), + error + ); + continue; + } + }; if metadata.snapshot_type == SnapshotType::Baseline && metadata.file_path.as_os_str() == file_path.as_os_str() @@ -142,14 +153,14 @@ impl BaselineCache { file_path: file_path.to_path_buf(), content_hash: before_snapshot.content_hash.clone(), snapshot_type: SnapshotType::Baseline, - compressed_content: before_snapshot.compressed_content.clone(), + compressed_content: Vec::new(), timestamp: SystemTime::now(), metadata: before_snapshot.metadata.clone(), }; let baseline_meta_path = self.baseline_dir.join(format!("{}.json", baseline_id)); let metadata_json = serde_json::to_string_pretty(&baseline_metadata)?; - fs::write(&baseline_meta_path, metadata_json)?; + write_atomic(&baseline_meta_path, metadata_json.as_bytes())?; debug!( "Created baseline snapshot: file_path={:?} baseline_id={} metadata_path={}", @@ -199,7 +210,7 @@ impl BaselineCache { let baseline_meta_path = self.baseline_dir.join(format!("{}.json", baseline_id)); let metadata_json = serde_json::to_string_pretty(&baseline_metadata)?; - fs::write(&baseline_meta_path, metadata_json)?; + write_atomic(&baseline_meta_path, metadata_json.as_bytes())?; { let mut cache = self.cache.write().await; @@ -224,6 +235,7 @@ pub struct FileSnapshotSystem { snapshot_metadata_dir: PathBuf, hash_to_path: HashMap, active_snapshots: HashMap, + capture_limit: usize, compression_enabled: bool, dedup_enabled: bool, baseline_cache: BaselineCache, @@ -267,12 +279,19 @@ impl FileSnapshotSystem { snapshot_dir, hash_to_path: HashMap::new(), active_snapshots: HashMap::new(), + capture_limit: super::types::SnapshotConfig::default() + .max_snapshot_size_mb + .saturating_mul(1024 * 1024), compression_enabled: true, dedup_enabled: true, baseline_cache: BaselineCache::new(runtime_context.snapshot_baselines_dir.clone()), } } + pub(super) fn set_capture_budget_mb(&mut self, mb: usize) { + self.capture_limit = mb.saturating_mul(1024 * 1024); + } + pub(crate) fn workspace_fs(&self) -> SnapshotResult<&dyn WorkspaceFileSystem> { self.workspace_fs.as_deref().ok_or_else(|| { SnapshotError::ConfigError( @@ -307,10 +326,15 @@ impl FileSnapshotSystem { pub(crate) async fn read_workspace_text(&self, path: &Path) -> SnapshotResult { self.validate_workspace_path(path).await?; + let _permit = CONTENT_JOBS + .acquire() + .await + .expect("snapshot semaphore stays open"); let bytes = self .workspace_fs()? - .read_file(path.to_string_lossy().as_ref()) - .await?; + .read_file_bounded(path.to_string_lossy().as_ref(), CONTENT_LIMIT) + .await? + .ok_or_else(|| limit_error(path, CONTENT_LIMIT))?; String::from_utf8(bytes).map_err(|error| { SnapshotError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, error)) }) @@ -405,12 +429,7 @@ impl FileSnapshotSystem { load_tasks.push(tokio::task::spawn_blocking(move || { let mut snapshots = Vec::with_capacity(chunk.len()); for path in chunk { - let parsed = fs::read_to_string(&path) - .map_err(SnapshotError::from) - .and_then(|content| { - serde_json::from_str::(&content) - .map_err(SnapshotError::from) - }); + let parsed = descriptor(&path); match parsed { Ok(snapshot) => snapshots.push(snapshot), Err(e) => { @@ -452,9 +471,7 @@ impl FileSnapshotSystem { /// Loads snapshot metadata. async fn load_snapshot_metadata(&self, path: &Path) -> SnapshotResult { - let content = fs::read_to_string(path)?; - let snapshot: FileSnapshot = serde_json::from_str(&content)?; - Ok(snapshot) + descriptor(path) } /// Creates a file snapshot. @@ -492,13 +509,52 @@ impl FileSnapshotSystem { file_path.display() ))); } - let content = self - .workspace_fs()? - .read_file(file_path.to_string_lossy().as_ref()) + let size = workspace_metadata.size.unwrap_or(0); + if size > self.capture_limit as u64 { + return Err(limit_error(file_path, self.capture_limit)); + } + let _permit = CONTENT_JOBS + .acquire() + .await + .expect("snapshot semaphore stays open"); + let (content_hash, metadata) = if size > CONTENT_LIMIT as u64 { + let (hash, recorded_size) = super::storage::stream_blob( + self.workspace_fs()?, + file_path, + &self.snapshot_by_hash_dir, + self.capture_limit, + ) .await?; - let metadata = Self::extract_file_metadata(&workspace_metadata, &content)?; - - let content_hash = self.calculate_content_hash(&content); + ( + hash, + Self::file_metadata(&workspace_metadata, recorded_size, "unknown")?, + ) + } else { + let limit = self.capture_limit.min(CONTENT_LIMIT); + let content = self + .workspace_fs()? + .read_file_bounded(file_path.to_string_lossy().as_ref(), limit) + .await? + .ok_or_else(|| limit_error(file_path, limit))?; + let metadata = Self::extract_file_metadata(&workspace_metadata, &content)?; + let content_hash = self.calculate_content_hash(&content); + let blob_path = self.get_content_path(&content_hash); + if !blob_path.exists() { + let gzip_input = content.starts_with(&[0x1f, 0x8b]); + let compressed = if gzip_input || (self.compression_enabled && content.len() > 1024) + { + Some(self.compress_content(&content)?) + } else { + None + }; + let stored = compressed + .as_deref() + .filter(|data| gzip_input || data.len() < content.len() * 4 / 5) + .unwrap_or(&content); + write_atomic(&blob_path, stored)?; + } + (content_hash, metadata) + }; if !independent_handle && self.dedup_enabled @@ -518,18 +574,12 @@ impl FileSnapshotSystem { ); } - let optimized_content = self.optimize_content(&content); - let snapshot = FileSnapshot { snapshot_id: Uuid::new_v4().to_string(), file_path: file_path.to_path_buf(), content_hash: content_hash.clone(), snapshot_type: SnapshotType::Before, - compressed_content: match optimized_content { - OptimizedContent::Raw(data) => data, - OptimizedContent::Compressed(data) => data, - OptimizedContent::Reference(_) => Vec::new(), - }, + compressed_content: Vec::new(), timestamp: SystemTime::now(), metadata, }; @@ -549,23 +599,31 @@ impl FileSnapshotSystem { fn extract_file_metadata( metadata: &WorkspaceMetadata, content: &[u8], + ) -> SnapshotResult { + let encoding = if content.is_ascii() { + "ascii" + } else if std::str::from_utf8(content).is_ok() { + "utf-8" + } else { + "binary" + }; + Self::file_metadata(metadata, content.len() as u64, encoding) + } + + fn file_metadata( + metadata: &WorkspaceMetadata, + size: u64, + encoding: &str, ) -> SnapshotResult { Ok(FileMetadata { - size: content.len() as u64, + size, permissions: metadata.permissions, last_modified: metadata.modified.ok_or_else(|| { SnapshotError::ConfigError( "Workspace provider did not supply a modification time for the snapshot".into(), ) })?, - encoding: if content.is_ascii() { - "ascii" - } else if std::str::from_utf8(content).is_ok() { - "utf-8" - } else { - "binary" - } - .into(), + encoding: encoding.into(), }) } @@ -574,32 +632,6 @@ impl FileSnapshotSystem { format!("{:x}", md5::compute(content)) } - /// Optimizes content storage. - fn optimize_content(&self, content: &[u8]) -> OptimizedContent { - if self.dedup_enabled { - let hash = self.calculate_content_hash(content); - let content_path = self.get_content_path(&hash); - if self.hash_to_path.contains_key(&hash) && content_path.exists() { - return OptimizedContent::Reference(hash); - } - } - - if self.compression_enabled && content.len() > 1024 { - match self.compress_content(content) { - Ok(compressed) => { - if compressed.len() < content.len() * 4 / 5 { - return OptimizedContent::Compressed(compressed); - } - } - Err(e) => { - warn!("Content compression failed: error={}", e); - } - } - } - - OptimizedContent::Raw(content.to_vec()) - } - /// Compresses content. fn compress_content(&self, content: &[u8]) -> Result, std::io::Error> { use flate2::write::GzEncoder; @@ -611,34 +643,11 @@ impl FileSnapshotSystem { encoder.finish() } - /// Decompresses content. - fn decompress_content(&self, compressed: &[u8]) -> Result, std::io::Error> { - use flate2::read::GzDecoder; - use std::io::Read; - - let mut decoder = GzDecoder::new(compressed); - let mut decompressed = Vec::new(); - decoder.read_to_end(&mut decompressed)?; - Ok(decompressed) - } - - /// Stores a snapshot. async fn store_snapshot(&self, snapshot: &FileSnapshot) -> SnapshotResult<()> { - let content_path = self.get_content_path(&snapshot.content_hash); - if !content_path.exists() { - fs::write(&content_path, &snapshot.compressed_content)?; - } - - let metadata_path = self.get_metadata_path(&snapshot.snapshot_id); - let metadata_json = serde_json::to_string_pretty(snapshot)?; - fs::write(&metadata_path, metadata_json)?; - - debug!( - "Snapshot stored: snapshot_id={} content_path={}", - snapshot.snapshot_id, - content_path.display() - ); - Ok(()) + write_atomic( + &self.get_metadata_path(&snapshot.snapshot_id), + &serde_json::to_vec_pretty(snapshot)?, + ) } /// Returns the content file path. @@ -707,38 +716,55 @@ impl FileSnapshotSystem { pub async fn restore_snapshot_content(&self, snapshot_id: &str) -> SnapshotResult> { let snapshot = self.load_snapshot_from_disk(snapshot_id).await?; - if !snapshot.compressed_content.is_empty() { - return self.extract_content_from_snapshot(&snapshot); + let path = self.get_content_path(&snapshot.content_hash); + if snapshot.metadata.size > CONTENT_LIMIT as u64 { + return Err(limit_error(&snapshot.file_path, CONTENT_LIMIT)); } - - let content_path = self.get_content_path(&snapshot.content_hash); - if !content_path.exists() { - return Err(SnapshotError::SnapshotNotFound(format!( - "content file not found: {}", - content_path.display() - ))); - } - - let compressed_content = fs::read(&content_path)?; - - match self.decompress_content(&compressed_content) { - Ok(decompressed) => Ok(decompressed), - Err(_) => Ok(compressed_content), - } - } - - /// Extracts content from a snapshot. - fn extract_content_from_snapshot(&self, snapshot: &FileSnapshot) -> SnapshotResult> { - if snapshot.compressed_content.is_empty() { - return Err(SnapshotError::SnapshotNotFound( - "snapshot content is empty".to_string(), - )); + let _permit = CONTENT_JOBS + .acquire() + .await + .expect("snapshot semaphore stays open"); + let stored = match fs::File::open(&path) { + Ok(file) => read_bounded(file, CONTENT_LIMIT + 64 * 1024, &path)?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + // Legacy records may have the only remaining copy inline. + let metadata_path = self.get_metadata_path(snapshot_id); + let file = fs::File::open(&metadata_path)?; + let json_limit = CONTENT_LIMIT * 9 + 65536; + if file.metadata()?.len() > json_limit as u64 { + return Err(limit_error(&metadata_path, json_limit)); + } + let record: FileSnapshot = serde_json::from_reader(std::io::BufReader::new( + std::io::Read::take(file, json_limit as u64 + 1), + ))?; + if record.compressed_content.is_empty() { + return Err(SnapshotError::SnapshotNotFound(path.display().to_string())); + } + record.compressed_content + } + Err(error) => return Err(error.into()), + }; + // Old blobs carry no codec tag. Check the raw hash first so an original + // gzip file is restored byte-for-byte instead of being decoded twice. + if stored.len() as u64 == snapshot.metadata.size + && self.calculate_content_hash(&stored) == snapshot.content_hash + { + return Ok(stored); } - - match self.decompress_content(&snapshot.compressed_content) { - Ok(decompressed) => Ok(decompressed), - Err(_) => Ok(snapshot.compressed_content.clone()), + let decoded = read_bounded( + flate2::read::GzDecoder::new(stored.as_slice()), + snapshot.metadata.size as usize, + &path, + )?; + if decoded.len() as u64 != snapshot.metadata.size + || self.calculate_content_hash(&decoded) != snapshot.content_hash + { + return Err(SnapshotError::ConfigError(format!( + "Snapshot content failed verification: {}", + snapshot_id + ))); } + Ok(decoded) } /// Restores a file to the specified path (reads snapshot directly from disk). @@ -753,12 +779,14 @@ impl FileSnapshotSystem { let snapshot = self.load_snapshot_from_disk(snapshot_id).await?; let metadata = snapshot.metadata.clone(); - let content = self.restore_snapshot_content(snapshot_id).await?; - - // Provider write_file owns parent creation using its path semantics. - self.workspace_fs()? - .write_file(target_path.to_string_lossy().as_ref(), &content) - .await?; + if snapshot.metadata.size > CONTENT_LIMIT as u64 { + self.restore_large_blob(&snapshot, target_path).await?; + } else { + let content = self.restore_snapshot_content(snapshot_id).await?; + self.workspace_fs()? + .write_file(target_path.to_string_lossy().as_ref(), &content) + .await?; + } self.restore_file_metadata(target_path, &metadata).await?; @@ -769,6 +797,111 @@ impl FileSnapshotSystem { Ok(()) } + /// Large blobs, including historical backups above the capture limit, + /// Verify them while streaming to a sibling stage before replacing the target. + async fn restore_large_blob( + &self, + snapshot: &FileSnapshot, + target: &Path, + ) -> SnapshotResult<()> { + use std::io::Read; + use tokio::io::AsyncWriteExt; + let _permit = CONTENT_JOBS + .acquire() + .await + .expect("snapshot semaphore stays open"); + use std::io::Seek; + let expected = snapshot.metadata.size; + let _stage; + let mut blob = match fs::File::open(self.get_content_path(&snapshot.content_hash)) { + Ok(file) => file, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + let path = self.get_metadata_path(&snapshot.snapshot_id); + let directory = self.snapshot_by_hash_dir.clone(); + let (file, stage) = tokio::task::spawn_blocking(move || { + super::storage::extract_legacy_blob(&path, &directory, expected) + }) + .await + .map_err(|error| { + SnapshotError::ConfigError(format!( + "Legacy snapshot extraction failed: {error}" + )) + })??; + _stage = stage; + file + } + Err(err) => return Err(err.into()), + }; + let mut raw = blob.metadata()?.len() == expected; + if raw { + let mut magic = [0; 2]; + blob.read_exact(&mut magic)?; + blob.rewind()?; + if magic == [0x1f, 0x8b] { + // A raw gzip input and a gzip blob of coincidentally identical + // length share the same prefix. Old references have no codec tag. + let mut digest = md5::Context::new(); + std::io::copy(&mut blob, &mut digest)?; + raw = format!("{:x}", digest.compute()) == snapshot.content_hash; + blob.rewind()?; + } + } + let mut reader: Box = if raw { + Box::new(blob) + } else { + Box::new(flate2::read::GzDecoder::new(blob)) + }; + let workspace = self.workspace_fs()?; + let target = target.to_string_lossy(); + let parent = if self.remote_isolation.is_some() { + target + .rsplit_once('/') + .map(|(dir, _)| if dir.is_empty() { "/" } else { dir }) + } else { + Path::new(target.as_ref()).parent().and_then(Path::to_str) + } + .ok_or_else(|| { + SnapshotError::ConfigError("Snapshot restore target has no parent".into()) + })?; + workspace.create_dir_all(parent).await?; + let stage = workspace.join_path(parent, &[&format!(".snapshot-{}.tmp", Uuid::new_v4())]); + let writer = workspace.open_write_new(&stage).await?; + let result: SnapshotResult<()> = async { + let mut writer = writer; + let mut buffer = vec![0; 64 * 1024]; + let mut digest = md5::Context::new(); + let mut count = 0u64; + loop { + let n = reader.read(&mut buffer)?; + if n == 0 { + break; + } + count += n as u64; + if count > expected { + return Err(SnapshotError::ConfigError( + "Snapshot exceeds recorded size".into(), + )); + } + digest.consume(&buffer[..n]); + writer.write_all(&buffer[..n]).await?; + } + writer.shutdown().await?; + drop(writer); + if count != expected || format!("{:x}", digest.compute()) != snapshot.content_hash { + return Err(SnapshotError::ConfigError( + "Snapshot content failed verification".into(), + )); + } + workspace.atomic_replace(&stage, &target).await?; + Ok(()) + } + .await; + if result.is_err() { + let _ = workspace.remove_file(&stage).await; + } + result + } + /// Restores file metadata. async fn restore_file_metadata( &self, @@ -786,32 +919,55 @@ impl FileSnapshotSystem { Ok(()) } + // Baselines and legacy records outside the in-memory index may be the last + // owner of a blob. If any descriptor is unreadable, keep all candidate blobs. + fn persisted_hashes(&self) -> SnapshotResult> { + let mut hashes = HashSet::new(); + for dir in [ + &self.snapshot_metadata_dir, + &self.baseline_cache.baseline_dir, + ] { + for entry in fs::read_dir(dir)? { + let path = entry?.path(); + if path.extension().is_some_and(|ext| ext == "json") { + hashes.insert(descriptor(&path)?.content_hash); + } + } + } + Ok(hashes) + } + /// Deletes a snapshot. pub async fn delete_snapshot(&mut self, snapshot_id: &str) -> SnapshotResult<()> { info!("Deleting snapshot: snapshot_id={}", snapshot_id); + let metadata_path = self.get_metadata_path(snapshot_id); let snapshot = self .active_snapshots - .remove(snapshot_id) - .ok_or_else(|| SnapshotError::SnapshotNotFound(snapshot_id.to_string()))?; - - let content_still_used = self + .get(snapshot_id) + .ok_or_else(|| SnapshotError::SnapshotNotFound(snapshot_id.to_owned()))?; + let hash = snapshot.content_hash.clone(); + fs::remove_file(metadata_path)?; + self.active_snapshots.remove(snapshot_id); + if !self .active_snapshots .values() - .any(|s| s.content_hash == snapshot.content_hash); - - if !content_still_used { - let content_path = self.get_content_path(&snapshot.content_hash); - if content_path.exists() { - fs::remove_file(&content_path)?; + .any(|s| s.content_hash == hash) + { + match self.persisted_hashes() { + Ok(hashes) if !hashes.contains(&hash) => { + let path = self.get_content_path(&hash); + if path.exists() { + fs::remove_file(path)?; + } + self.hash_to_path.remove(&hash); + } + Err(error) => warn!( + "Retaining snapshot blob because references could not be verified: {}", + error + ), + _ => {} } - - self.hash_to_path.remove(&snapshot.content_hash); - } - - let metadata_path = self.get_metadata_path(snapshot_id); - if metadata_path.exists() { - fs::remove_file(&metadata_path)?; } debug!("Snapshot deleted successfully: snapshot_id={}", snapshot_id); @@ -885,16 +1041,12 @@ impl FileSnapshotSystem { } } + let referenced = self.persisted_hashes()?; for content_file in content_files { if let Some(file_stem) = content_file.file_stem().and_then(|s| s.to_str()) { let content_hash = file_stem; - let is_referenced = self - .active_snapshots - .values() - .any(|snapshot| snapshot.content_hash == content_hash); - - if !is_referenced { + if !referenced.contains(content_hash) { fs::remove_file(&content_file)?; self.hash_to_path.remove(content_hash); cleaned_count += 1; @@ -1075,4 +1227,162 @@ mod tests { fs::remove_dir_all(&context.runtime_root).expect("cleanup runtime root"); } + #[tokio::test] + async fn new_metadata_and_baselines_reference_one_blob_after_cleanup_and_restart() { + let context = test_runtime_context(); + create_runtime_dirs(&context); + let path = context.runtime_root.join("example"); + let bytes = vec![0x92; 10000]; + fs::write(&path, &bytes).unwrap(); + let mut system = FileSnapshotSystem::new(context.clone()); + let before = system.create_owned_snapshot(&path).await.unwrap(); + let baseline = system + .create_baseline_from_snapshot(&path, &before) + .await + .unwrap(); + for id in [&before, &baseline] { + let json = fs::read(system.get_metadata_path(id)).unwrap(); + // The old reader requires the content field even for a reference. + let legacy_reader: FileSnapshot = serde_json::from_slice(&json).unwrap(); + assert!(legacy_reader.compressed_content.is_empty()); + assert!(json.len() < 1024); + } + system.delete_snapshot(&before).await.unwrap(); + let mut cold = FileSnapshotSystem::new(context.clone()); + cold.initialize().await.unwrap(); + assert_eq!(cold.cleanup_orphaned_snapshots().await.unwrap(), 0); + assert_eq!( + cold.restore_snapshot_content(&baseline).await.unwrap(), + bytes + ); + fs::remove_dir_all(context.runtime_root).unwrap(); + } + + #[tokio::test] + async fn legacy_inline_only_payload_is_loaded_on_demand_and_round_trips() { + let context = test_runtime_context(); + create_runtime_dirs(&context); + let path = context.runtime_root.join("binary"); + let bytes = vec![173; 65536]; + let record = FileSnapshot::new( + path.clone(), + bytes.clone(), + FileMetadata { + size: bytes.len() as u64, + permissions: None, + last_modified: SystemTime::now(), + encoding: "binary".into(), + }, + SnapshotType::Before, + ); + let mut system = FileSnapshotSystem::new(context.clone()); + let json = serde_json::to_vec_pretty(&record).unwrap(); + fs::write(system.get_metadata_path(&record.snapshot_id), &json).unwrap(); + system.initialize().await.unwrap(); + assert!(system.list_snapshots()[0].compressed_content.is_empty()); + system + .restore_file(&record.snapshot_id, &path) + .await + .unwrap(); + assert_eq!(fs::read(path).unwrap(), bytes); + assert_eq!( + fs::read(system.get_metadata_path(&record.snapshot_id)).unwrap(), + json + ); + fs::remove_dir_all(context.runtime_root).unwrap(); + } + + #[tokio::test] + async fn streamed_legacy_restore_verifies_before_replacing_existing_target() { + let context = test_runtime_context(); + create_runtime_dirs(&context); + let path = context.runtime_root.join("target"); + fs::write(&path, b"keep").unwrap(); + let bytes = vec![127; CONTENT_LIMIT + 1]; + let mut record = FileSnapshot::new( + path.clone(), + bytes.clone(), + FileMetadata { + size: bytes.len() as u64, + permissions: None, + last_modified: SystemTime::now(), + encoding: "binary".into(), + }, + SnapshotType::Before, + ); + record.compressed_content.clear(); + let system = FileSnapshotSystem::new(context.clone()); + system.store_snapshot(&record).await.unwrap(); + let blob = system.get_content_path(&record.content_hash); + fs::write(&blob, system.compress_content(b"short").unwrap()).unwrap(); + assert!(system + .restore_file(&record.snapshot_id, &path) + .await + .is_err()); + assert_eq!(fs::read(&path).unwrap(), b"keep"); + // Legacy baseline with an inline gzip payload and a collected blob. + fs::remove_file(&blob).unwrap(); + record.compressed_content = system.compress_content(&bytes).unwrap(); + fs::write( + system.get_metadata_path(&record.snapshot_id), + serde_json::to_vec_pretty(&record).unwrap(), + ) + .unwrap(); + system + .restore_file(&record.snapshot_id, &path) + .await + .unwrap(); + assert_eq!(fs::read(path).unwrap(), bytes); + fs::remove_dir_all(context.runtime_root).unwrap(); + } + + #[tokio::test] + async fn oversized_source_is_rejected_before_a_snapshot_is_written() { + let context = test_runtime_context(); + create_runtime_dirs(&context); + let path = context.runtime_root.join("engine"); + fs::File::create(&path) + .unwrap() + .set_len(CONTENT_LIMIT as u64 + 1) + .unwrap(); + let mut system = FileSnapshotSystem::new(context.clone()); + system.set_capture_budget_mb(8); + assert!(system + .create_owned_snapshot(&path) + .await + .unwrap_err() + .to_string() + .contains("byte limit")); + assert_eq!( + fs::read_dir(&system.snapshot_by_hash_dir).unwrap().count(), + 0 + ); + assert_eq!( + fs::read_dir(&system.snapshot_metadata_dir).unwrap().count(), + 0 + ); + fs::remove_dir_all(context.runtime_root).unwrap(); + } + #[tokio::test] + async fn large_file_uses_a_streamed_blob_and_round_trips_after_restart() { + let context = test_runtime_context(); + create_runtime_dirs(&context); + let path = context.runtime_root.join("engine"); + let bytes = vec![42; CONTENT_LIMIT + 1]; + fs::write(&path, &bytes).unwrap(); + let mut system = FileSnapshotSystem::new(context.clone()); + let id = system.create_owned_snapshot(&path).await.unwrap(); + drop(system); + fs::remove_file(&path).unwrap(); + let mut cold = FileSnapshotSystem::new(context.clone()); + cold.initialize().await.unwrap(); + assert_eq!( + cold.get_snapshot_recorded_size_bytes(&id).await.unwrap(), + bytes.len() as u64 + ); + assert!(cold.get_snapshot_content(&id).await.is_err()); + cold.restore_file(&id, &path).await.unwrap(); + assert_eq!(fs::read(path).unwrap(), bytes); + fs::remove_dir_all(context.runtime_root).unwrap(); + } } diff --git a/src/crates/assembly/core/src/service/snapshot/storage.rs b/src/crates/assembly/core/src/service/snapshot/storage.rs new file mode 100644 index 0000000000..5c250c78f0 --- /dev/null +++ b/src/crates/assembly/core/src/service/snapshot/storage.rs @@ -0,0 +1,218 @@ +//! The legacy format embeds bytes between the identity and metadata fields. +//! Keep the descriptor readable by old releases, but store new bytes only by hash. +use super::types::{FileSnapshot, SnapshotError, SnapshotResult}; +use std::fs::{self, File}; +use std::io::{Read, Seek, SeekFrom}; +use std::path::Path; + +pub(crate) const CONTENT_LIMIT: usize = 8 * 1024 * 1024; +const HEADER_WINDOW: usize = 32 * 1024; +pub(super) static CONTENT_JOBS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2); + +pub(super) fn limit_error(path: &Path, limit: usize) -> SnapshotError { + SnapshotError::ConfigError(format!( + "Snapshot of {} exceeds the {} byte limit", + path.display(), + limit + )) +} + +pub(super) fn read_bounded( + reader: impl Read, + limit: usize, + path: &Path, +) -> SnapshotResult> { + let mut bytes = Vec::new(); + reader.take(limit as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > limit { + return Err(limit_error(path, limit)); + } + Ok(bytes) +} + +/// Read the small descriptor without traversing a historical byte array. +/// For large files only recognize the layout emitted by to_string_pretty. +/// Other oversized layouts remain on disk and report an explicit error. +pub(super) fn descriptor(path: &Path) -> SnapshotResult { + let mut file = File::open(path)?; + let len = file.metadata()?.len(); + let bytes = if len <= (2 * HEADER_WINDOW) as u64 { + read_bounded(file, 2 * HEADER_WINDOW, path)? + } else { + let mut head = vec![0; HEADER_WINDOW]; + let mut tail = vec![0; HEADER_WINDOW]; + file.read_exact(&mut head)?; + file.seek(SeekFrom::End(-(HEADER_WINDOW as i64)))?; + file.read_exact(&mut tail)?; + let start = b"\n \"compressed_content\": ["; + let end = b"],\n \"timestamp\":"; + let i = head + .windows(start.len()) + .position(|w| w == start) + .ok_or_else(|| limit_error(path, 2 * HEADER_WINDOW))?; + let j = tail + .windows(end.len()) + .rposition(|w| w == end) + .ok_or_else(|| limit_error(path, 2 * HEADER_WINDOW))?; + head.truncate(i + start.len()); + head.extend_from_slice(&tail[j..]); + head + }; + let mut record: FileSnapshot = serde_json::from_slice(&bytes)?; + record.compressed_content = Vec::new(); + if record.content_hash.len() != 32 + || !record.content_hash.bytes().all(|b| b.is_ascii_hexdigit()) + { + return Err(SnapshotError::ConfigError(format!( + "Invalid snapshot content hash in {}", + path.display() + ))); + } + Ok(record) +} + +pub(super) fn write_atomic(path: &Path, bytes: &[u8]) -> SnapshotResult<()> { + let tmp = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4())); + let result = fs::write(&tmp, bytes).and_then(|()| fs::rename(&tmp, path)); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + Ok(result?) +} + +/// A cancelled remote read must not leave its temporary compressed file behind. +pub(super) struct StagedBlob(std::path::PathBuf); +impl Drop for StagedBlob { + fn drop(&mut self) { + let _ = fs::remove_file(&self.0); + } +} + +pub(super) async fn stream_blob( + workspace: &dyn openbitfun_runtime_ports::WorkspaceFileSystem, + source: &Path, + directory: &Path, + limit: usize, +) -> SnapshotResult<(String, u64)> { + use std::io::{BufWriter, Write}; + use tokio::io::AsyncReadExt; + let mut reader = workspace + .open_read(source.to_string_lossy().as_ref()) + .await?; + let path = directory.join(format!("{}.tmp", uuid::Uuid::new_v4())); + let file = fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(&path)?; + let stage = StagedBlob(path); + let mut encoder = + flate2::write::GzEncoder::new(BufWriter::new(file), flate2::Compression::fast()); + let mut digest = md5::Context::new(); + let mut buffer = vec![0; 64 * 1024]; + let mut size = 0u64; + loop { + let n = reader.read(&mut buffer).await?; + if n == 0 { + break; + } + size += n as u64; + if size > limit as u64 { + return Err(limit_error(source, limit)); + } + digest.consume(&buffer[..n]); + encoder.write_all(&buffer[..n])?; + } + encoder.finish()?.flush()?; + let hash = format!("{:x}", digest.compute()); + let dest = directory.join(format!("{hash}.snap")); + if !dest.exists() { + fs::rename(&stage.0, dest)?; + } + Ok((hash, size)) +} + +/// Older cleanup could leave a baseline's embedded array as its only copy. +/// Extract it only for explicit restore. The encoded bytes are never added to +/// the shared store, since their integrity has not yet been verified. +pub(super) fn extract_legacy_blob( + metadata_path: &Path, + directory: &Path, + expected_size: u64, +) -> SnapshotResult<(File, StagedBlob)> { + use serde::de::{ + DeserializeSeed, Deserializer, Error, IgnoredAny, MapAccess, SeqAccess, Visitor, + }; + use std::fmt; + use std::io::{BufReader, BufWriter, Write}; + + struct Bytes<'a>(&'a mut BufWriter, u64); + impl<'de> DeserializeSeed<'de> for Bytes<'_> { + type Value = (); + fn deserialize>(self, d: D) -> Result<(), D::Error> { + d.deserialize_seq(self) + } + } + impl<'de> Visitor<'de> for Bytes<'_> { + type Value = (); + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a legacy snapshot byte array") + } + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + let mut remaining = self.1; + while let Some(byte) = seq.next_element::()? { + remaining = remaining + .checked_sub(1) + .ok_or_else(|| A::Error::custom("Legacy payload exceeds its recorded size"))?; + self.0.write_all(&[byte]).map_err(A::Error::custom)?; + } + Ok(()) + } + } + + struct Record<'a>(Bytes<'a>); + impl<'de> Visitor<'de> for Record<'_> { + type Value = (); + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a legacy snapshot") + } + fn visit_map>(self, mut map: M) -> Result<(), M::Error> { + let mut bytes = Some(self.0); + while let Some(field) = map.next_key::()? { + if field == "compressed_content" { + map.next_value_seed( + bytes + .take() + .ok_or_else(|| M::Error::duplicate_field("compressed_content"))?, + )?; + } else { + map.next_value::()?; + } + } + if bytes.is_some() { + return Err(M::Error::missing_field("compressed_content")); + } + Ok(()) + } + } + let source = File::open(metadata_path)?; + let max_json_bytes = expected_size.saturating_mul(9).saturating_add(65536); + if source.metadata()?.len() > max_json_bytes { + return Err(SnapshotError::ConfigError( + "Legacy snapshot exceeds its encoded size budget".into(), + )); + } + let path = directory.join(format!("{}.tmp", uuid::Uuid::new_v4())); + let file = fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(&path)?; + let stage = StagedBlob(path); + let mut output = BufWriter::new(file); + let mut de = serde_json::Deserializer::from_reader(BufReader::new(source.take(max_json_bytes))); + de.deserialize_map(Record(Bytes(&mut output, expected_size)))?; + de.end()?; + let mut file = output.into_inner().map_err(|e| e.into_error())?; + file.rewind()?; + Ok((file, stage)) +} diff --git a/src/crates/assembly/core/src/service/snapshot/types.rs b/src/crates/assembly/core/src/service/snapshot/types.rs index 1d3306e4b7..5f04793898 100644 --- a/src/crates/assembly/core/src/service/snapshot/types.rs +++ b/src/crates/assembly/core/src/service/snapshot/types.rs @@ -150,6 +150,13 @@ pub struct SnapshotConfig { pub max_session_retention_days: u64, pub compression_threshold_kb: usize, pub max_cache_size_mb: usize, + /// Maximum logical bytes per new before/after snapshot, in MiB. + #[serde(default = "default_max_snapshot_size_mb")] + pub max_snapshot_size_mb: usize, +} + +const fn default_max_snapshot_size_mb() -> usize { + 128 } impl Default for SnapshotConfig { @@ -160,6 +167,7 @@ impl Default for SnapshotConfig { max_session_retention_days: 30, compression_threshold_kb: 100, max_cache_size_mb: 500, + max_snapshot_size_mb: default_max_snapshot_size_mb(), } } } @@ -229,3 +237,25 @@ impl FileSnapshot { } } } + +#[cfg(test)] +mod budget_tests { + use super::*; + + #[test] + fn old_config_keeps_cache_policy_and_receives_the_default_capture_limit() { + let original = serde_json::json!({ + "auto_snapshot_enabled": true, "snapshot_interval_minutes": 30, + "max_session_retention_days": 7, "compression_threshold_kb": 100, + "max_cache_size_mb": 32 + }); + let config: SnapshotConfig = serde_json::from_value(original.clone()).unwrap(); + assert_eq!(config.max_snapshot_size_mb, 128); + let mut roundtrip = serde_json::to_value(config).unwrap(); + roundtrip + .as_object_mut() + .unwrap() + .remove("max_snapshot_size_mb"); + assert_eq!(roundtrip, original); + } +} diff --git a/src/crates/assembly/core/src/service/snapshot/workspace_io_tests.rs b/src/crates/assembly/core/src/service/snapshot/workspace_io_tests.rs index 2265886d9a..f6c27c453d 100644 --- a/src/crates/assembly/core/src/service/snapshot/workspace_io_tests.rs +++ b/src/crates/assembly/core/src/service/snapshot/workspace_io_tests.rs @@ -1081,3 +1081,62 @@ async fn legacy_operation_completion_round_trip_preserves_omission_and_recorded_ ("before\n".into(), "after\n".into(), Some(1)) ); } + +#[tokio::test] +async fn unrelated_remote_session_can_write_with_oversized_historical_metadata() { + use std::io::{Seek, SeekFrom, Write}; + let temp = tempfile::tempdir().unwrap(); + let root = "/remote/large-history"; + let context = runtime_context(root, temp.path(), true); + let fs = Arc::new(RemoteMemoryFs::new(root)); + // Only the descriptor ends are needed at cold start. Leave the middle + // sparse to exercise an interrupted legacy write without allocating GiBs. + let record = super::types::FileSnapshot::new( + PathBuf::from("/remote/large-history/full.engine"), + Vec::new(), + super::types::FileMetadata { + size: 41u64 << 30, + permissions: None, + last_modified: UNIX_EPOCH, + encoding: "binary".into(), + }, + super::types::SnapshotType::Before, + ); + let json = serde_json::to_string_pretty(&record).unwrap(); + let (head, tail) = json.split_once("\"compressed_content\": []").unwrap(); + let path = context + .snapshot_metadata_dir + .join(format!("{}.json", record.snapshot_id)); + let mut file = std::fs::File::create(&path).unwrap(); + write!(file, "{head}\"compressed_content\": [").unwrap(); + file.seek(SeekFrom::Current(128 << 20)).unwrap(); + write!(file, "]{tail}").unwrap(); + drop(file); + let old_len = std::fs::metadata(&path).unwrap().len(); + let mut core = open_core(&context, fs.clone()).await; + let script = "/remote/large-history/resolve_snapshot.py"; + let op = core + .start_file_operation( + "other-session", + 0, + script.into(), + OperationType::Create, + "Write".into(), + serde_json::json!({}), + None, + ) + .await + .unwrap(); + fs.write_file(script, b"print(42)").await.unwrap(); + core.complete_file_operation("other-session", &op, 1) + .await + .unwrap(); + assert_eq!(core.get_session_files("other-session").len(), 1); + assert_eq!(std::fs::metadata(&path).unwrap().len(), old_len); + assert!(core + .get_snapshot_content(&record.snapshot_id) + .await + .unwrap_err() + .to_string() + .contains("byte limit")); +} From 277b97d0d3d023df1b8cfed1cf5a10c410e5520a Mon Sep 17 00:00:00 2001 From: wsp Date: Mon, 23 Nov 2026 20:29:08 +0800 Subject: [PATCH 2/2] feat(snapshot): Add storage usage and cleanup Show snapshot usage by workspace and preview the space that cleanup can reclaim. Include snapshots of removed sessions in every time range and preserve shared files and rollback checkpoints. Record pending cleanup before deleting a session so reclamation can resume after a restart. --- docs/interactive-capabilities/README.md | 16 +- .../capabilities.json | 183 +++++- .../capabilities/setting.data.storage.md | 55 ++ .../technical/product-control-open-audit.json | 23 +- .../technical/tauri-command-map.json | 40 +- src/apps/desktop/src/api/snapshot_service.rs | 44 ++ src/apps/desktop/src/lib.rs | 2 + .../src/agentic/session/session_manager.rs | 34 +- .../session/session_manager/tests/deletion.rs | 69 +++ .../infrastructure/app_paths/path_manager.rs | 14 +- .../src/service/snapshot/maintenance/mod.rs | 462 +++++++++++++++ .../service/snapshot/maintenance/pending.rs | 233 ++++++++ .../src/service/snapshot/maintenance/plan.rs | 470 +++++++++++++++ .../src/service/snapshot/maintenance/tests.rs | 533 ++++++++++++++++++ .../snapshot/maintenance/writer_lease.rs | 105 ++++ .../core/src/service/snapshot/manager.rs | 58 +- .../assembly/core/src/service/snapshot/mod.rs | 1 + .../core/src/service/snapshot/service.rs | 14 +- .../src/service/snapshot/snapshot_core.rs | 8 +- .../src/service/snapshot/snapshot_system.rs | 7 + .../core/src/service/workspace/service.rs | 16 +- .../generated/product-control-catalog.json | 174 +++++- .../generated/remote-surface-registry.json | 26 +- .../src/remote_surface/table.rs | 2 + .../services-core/src/session/write_lock.rs | 47 +- .../tests/session_write_lock_contracts.rs | 14 + .../interactive-capabilities/catalog.json | 69 +++ .../generated/interactive-capabilities.json | 174 +++++- .../src/app/scenes/settings/appearance.ts | 1 + .../data/StorageSettingsPage.appearance.ts | 9 + .../data/StorageSettingsPage.module.scss | 172 ++++++ .../pages/data/StorageSettingsPage.test.tsx | 114 ++++ .../pages/data/StorageSettingsPage.tsx | 256 +++++++++ .../scenes/settings/settingsRegistry.test.ts | 4 +- .../app/scenes/settings/settingsRegistry.ts | 12 + .../src/app/scenes/settings/settingsTypes.ts | 1 + .../api/generated/productControl.ts | 6 +- .../api/generated/remoteSurface.ts | 4 +- .../api/service-api/SnapshotStorageAPI.ts | 43 ++ .../registry/defaultAppearanceRegistry.ts | 2 + .../locales/en-US/scenes/capabilities.json | 7 + src/web-ui/src/locales/en-US/settings.json | 35 ++ .../locales/zh-CN/scenes/capabilities.json | 7 + src/web-ui/src/locales/zh-CN/settings.json | 35 ++ .../locales/zh-TW/scenes/capabilities.json | 7 + src/web-ui/src/locales/zh-TW/settings.json | 35 ++ 46 files changed, 3589 insertions(+), 54 deletions(-) create mode 100644 docs/interactive-capabilities/capabilities/setting.data.storage.md create mode 100644 src/crates/assembly/core/src/service/snapshot/maintenance/mod.rs create mode 100644 src/crates/assembly/core/src/service/snapshot/maintenance/pending.rs create mode 100644 src/crates/assembly/core/src/service/snapshot/maintenance/plan.rs create mode 100644 src/crates/assembly/core/src/service/snapshot/maintenance/tests.rs create mode 100644 src/crates/assembly/core/src/service/snapshot/maintenance/writer_lease.rs create mode 100644 src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.appearance.ts create mode 100644 src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.module.scss create mode 100644 src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.test.tsx create mode 100644 src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.tsx create mode 100644 src/web-ui/src/infrastructure/api/service-api/SnapshotStorageAPI.ts diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index e86bbf3439..fbbd04fcd0 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -1,9 +1,9 @@ # OpenBitFun 功能与设置目录 / OpenBitFun Features & Settings -OpenBitFun Playbook 当前包含 **24 个功能**和 **23 个设置页**,共 **47 个**用户可理解的条目、**368 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 +OpenBitFun Playbook 当前包含 **24 个功能**和 **24 个设置页**,共 **48 个**用户可理解的条目、**369 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 -OpenBitFun Playbook currently contains **24 features**, **23 settings pages**, and **368** source-backed sub-capabilities across **47** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. +OpenBitFun Playbook currently contains **24 features**, **24 settings pages**, and **369** source-backed sub-capabilities across **48** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. ## 唯一事实源 / Single source of truth @@ -27,20 +27,20 @@ OpenBitFun Playbook currently contains **24 features**, **23 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 或可解析的源码标记;这些证据不会进入公开目录。当前 **701** 个 Tauri 命令只用于实现覆盖审计。产品 UI 交互源码会在生成和检查时扫描并校验,但不会保存成随普通 UI 改动频繁变化的版本化快照。 +说明书、网站、搜索和智能体只看“功能 + 设置 + 子能力”。每项子能力都必须引用已注册 Tauri Command 或可解析的源码标记;这些证据不会进入公开目录。当前 **703** 个 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 **701** 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 **703** 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 -- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **63**、委托 **74**、需交互 **231**、不支持 **0**。 +- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **63**、委托 **74**、需交互 **232**、不支持 **0**。 - 稳定行为声明为带 JSON 输入契约的 `operations` 或 `options`,并绑定原生产品控制 Provider;智能体不接触原始 Tauri Command。 -- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 368 项子能力都不会写入 system prompt。 +- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 369 项子能力都不会写入 system prompt。 - 目录发现与契约读取不依赖 React 或可见窗口。普通配置型 option 统一由 Product Assembly 的共享 ConfigService 执行器读、写并回读,因此 Desktop、CLI 与 Headless 表面走同一份实现;只有宿主原生 operation/provider option 和界面导航按表面注册适配器,缺失时必须明确返回不可用,禁止静默回退本机。只读智能体只能发现和读取目录。 -- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **63 direct**, **74 delegated**, **231 interactive**, and **0 unsupported**. +- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **63 direct**, **74 delegated**, **232 interactive**, and **0 unsupported**. - Stable behavior becomes a typed `operation` or `option` with a JSON input contract and a native product-control provider. Agents never receive raw Tauri commands. -- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 368 documented items enters the system prompt. +- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 369 documented items enters the system prompt. - Discovery and contract lookup do not depend on React or a visible window. Ordinary config-backed options are read, written, and read back by one Product Assembly ConfigService executor shared by Desktop, CLI, and headless surfaces. Only host-native operations/provider options and presentation routes install surface adapters; missing adapters return explicit unavailability without local fallback. Read-only agents may only discover and inspect entries. ## 防腐化门禁 / Anti-drift gates diff --git a/docs/interactive-capabilities/capabilities.json b/docs/interactive-capabilities/capabilities.json index 6da747dfe2..3d70f69f28 100644 --- a/docs/interactive-capabilities/capabilities.json +++ b/docs/interactive-capabilities/capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", + "digest": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -185,13 +185,13 @@ ], "counts": { "features": 24, - "settings": 23, - "userFacing": 47, - "documentedItems": 368, + "settings": 24, + "userFacing": 48, + "documentedItems": 369, "controlCoverage": { "direct": 63, "delegated": 74, - "interactive": 231, + "interactive": 232, "unsupported": 0 } }, @@ -21371,6 +21371,97 @@ "pageId": "data.usage" } }, + { + "id": "setting.data.storage:query", + "capabilityId": "setting.data.storage", + "itemIds": [ + "clean" + ], + "kind": "query", + "risk": "read", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "static" + }, + "presentationTarget": { + "kind": "settings", + "pageId": "data.storage" + } + }, + { + "id": "setting.data.storage:open:clean", + "capabilityId": "setting.data.storage", + "itemIds": [ + "clean" + ], + "kind": "open", + "risk": "ui", + "executionHost": "presentationSurface", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "product_control_presentation_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "openReason": "unstructuredInteraction", + "presentationTarget": { + "kind": "settings", + "pageId": "data.storage" + } + }, { "id": "setting.data.archived:query", "capabilityId": "setting.data.archived", @@ -37393,6 +37484,88 @@ ], "docsUrl": "https://playbook.openbitfun.com/capabilities/setting.data.usage/" }, + { + "id": "setting.data.storage", + "kind": "setting", + "categoryId": "data", + "directoryGroupId": "settings-data", + "order": 53, + "entryPathZh": "设置 → 数据与维护 → 存储空间", + "entryPathEn": "Settings → Data & Maintenance → Storage", + "titleZh": "存储空间", + "titleEn": "Storage", + "summaryZh": "按工作区查看本机文件快照占用,手动清理符合条件的会话。", + "summaryEn": "Inspect local file snapshot usage by workspace and clean up eligible session histories.", + "keywordsZh": [ + "存储空间", + "快照清理" + ], + "keywordsEn": [ + "storage", + "snapshot cleanup" + ], + "highlightsZh": [ + "查看每个工作区的快照占用及共享文件大小。" + ], + "highlightsEn": [ + "See snapshot usage and shared file sizes for each workspace." + ], + "items": [ + { + "id": "clean", + "titleZh": "预览并清理会话文件快照", + "titleEn": "Preview and clean up session file snapshots", + "descriptionZh": "选择工作区和未活跃时长,核对会话及预计释放空间后确认清理。", + "descriptionEn": "Choose workspaces and an inactivity period, review the affected sessions and estimated space, then confirm cleanup.", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“预览并清理会话文件快照”会永久移除所选会话的文件回退记录,请在存储空间页面核对并确认。", + "reasonEn": "“Preview and clean up session file snapshots” opens Storage so you can review the affected sessions before permanently removing their file rollback history." + } + } + ], + "stepsZh": [ + "打开存储空间,选择工作区和清理范围。", + "核对预览并确认删除文件快照。" + ], + "stepsEn": [ + "Open Storage and select the workspaces and inactivity period.", + "Review the preview and confirm deletion of file snapshots." + ], + "agentExamplesZh": [ + "打开快照存储设置" + ], + "agentExamplesEn": [ + "Open snapshot storage settings" + ], + "relatedIds": [ + "setting.data.archived" + ], + "destination": { + "kind": "settings", + "pageId": "data.storage" + }, + "operations": [], + "options": [], + "searchTerms": [ + "setting.data.storage", + "存储空间", + "Storage", + "数据与诊断", + "Data & diagnostics", + "快照清理", + "storage", + "snapshot cleanup", + "查看每个工作区的快照占用及共享文件大小。", + "See snapshot usage and shared file sizes for each workspace.", + "预览并清理会话文件快照", + "Preview and clean up session file snapshots", + "打开快照存储设置", + "Open snapshot storage settings" + ], + "docsUrl": "https://playbook.openbitfun.com/capabilities/setting.data.storage/" + }, { "id": "setting.data.archived", "kind": "setting", diff --git a/docs/interactive-capabilities/capabilities/setting.data.storage.md b/docs/interactive-capabilities/capabilities/setting.data.storage.md new file mode 100644 index 0000000000..208f7dd0d2 --- /dev/null +++ b/docs/interactive-capabilities/capabilities/setting.data.storage.md @@ -0,0 +1,55 @@ + +--- +id: setting.data.storage +kind: setting +category: data +title_zh: "存储空间" +title_en: "Storage" +--- + +# 存储空间 / Storage + +> 设置 / Setting + +按工作区查看本机文件快照占用,手动清理符合条件的会话。 + +Inspect local file snapshot usage by workspace and clean up eligible session histories. + +## 完整功能清单 / Everything included + +- **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 预览并清理会话文件快照 + - Preview and clean up session file snapshots + - 说明:选择工作区和未活跃时长,核对会话及预计释放空间后确认清理。 + - Why & how: Choose workspaces and an inactivity period, review the affected sessions and estimated space, then confirm cleanup. + +## 怎么用 / How to use it + +1. 打开存储空间,选择工作区和清理范围。 + Open Storage and select the workspaces and inactivity period. +2. 核对预览并确认删除文件快照。 + Review the preview and confirm deletion of file snapshots. + +入口 / Entry: 设置 → 数据与维护 → 存储空间 / Settings → Data & Maintenance → Storage + +## 智能体可替你做什么 / What an agent can do for you + +| 操作 / Action | 中文说明 | English description | +| --- | --- | --- | +| 打开对应界面 / Open the UI | 进入 OpenBitFun 中对应的功能界面。 | Open the matching feature in OpenBitFun. | + +## 可配置选项 / Configurable options + +| 选项 / Option | 可用值 / Values | 中文说明 | English description | +| --- | --- | --- | --- | +| 在界面中配置 / Configure in the UI | — | 此页面的设置在对应界面中完成。 | Configure this page in its matching UI. | + +## 可以直接对智能体说 / Try saying + +- “打开快照存储设置” + - “Open snapshot storage settings” + +关联条目 / Related: `setting.data.archived` + +智能体会先查找相关功能或设置,确认目标后再替你打开、执行或修改。完整能力目录不会预先塞进对话上下文。 + +The agent first finds the relevant feature or setting, confirms the target, and then opens, runs, or changes it for you. The full catalog is never embedded in the conversation context. diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index 97a6601ddb..802073f3cf 100644 --- a/docs/interactive-capabilities/technical/product-control-open-audit.json +++ b/docs/interactive-capabilities/technical/product-control-open-audit.json @@ -1,12 +1,12 @@ { "schemaVersion": 1, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", - "count": 231, + "catalogDigest": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", + "count": 232, "reasonCounts": { "externalAuth": 4, "secretEntry": 6, - "unstructuredInteraction": 194, + "unstructuredInteraction": 195, "visualSelection": 27 }, "entries": [ @@ -3984,6 +3984,23 @@ "source:src/web-ui/src/locales/zh-CN/settings/usage.json#trend.legend.cacheRead" ] }, + { + "capabilityId": "setting.data.storage", + "itemId": "clean", + "titleZh": "预览并清理会话文件快照", + "titleEn": "Preview and clean up session file snapshots", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“预览并清理会话文件快照”会永久移除所选会话的文件回退记录,请在存储空间页面核对并确认。", + "reasonEn": "“Preview and clean up session file snapshots” opens Storage so you can review the affected sessions before permanently removing their file rollback history.", + "presentationTarget": { + "kind": "settings", + "pageId": "data.storage" + }, + "evidence": [ + "command:inspect_snapshot_storage", + "command:clean_snapshot_storage" + ] + }, { "capabilityId": "setting.data.archived", "itemId": "browse", diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 787b826a6f..89a1d9c7f8 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,11 +1,11 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", - "commandCount": 701, + "catalogDigest": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", + "commandCount": 703, "coverage": { - "commandCount": 701, - "documentedCommandCount": 635, + "commandCount": 703, + "documentedCommandCount": 637, "implementationCommandCount": 66, "implementationDigest": "22a8353380694e1246a4b15ec83c4f5a10c781fd5dfb0a0fb9d2a135e53380b6" }, @@ -1074,6 +1074,22 @@ "signature": "fn choose_external_subagent_conflict_command( request: ChooseExternalSubagentConflictRequest, ) -> ExternalSourceOperationResult", "remoteWorkspacePolicy": "RemoteUnsupported" }, + { + "id": "clean_snapshot_storage", + "moduleId": "snapshot_service", + "capabilityId": "setting.data.storage", + "capabilityIds": [ + "setting.data.storage" + ], + "documentedItemIds": [ + "setting.data.storage:clean" + ], + "visibility": "documented", + "rustPath": "clean_snapshot_storage", + "sourceFile": "src/apps/desktop/src/api/snapshot_service.rs", + "signature": "fn clean_snapshot_storage( runtime: State<'_, DesktopRuntimeContext>, request: CleanSnapshotStorageRequest, ) -> Result", + "remoteWorkspacePolicy": "WorkspaceAgnostic" + }, { "id": "cleanup_invalid_workspaces", "moduleId": "commands", @@ -5124,6 +5140,22 @@ "signature": "fn initialize_workspace_startup_state( state: State<'_, AppState>, app: tauri::AppHandle, startup_trace: State<'_, DesktopStartupTrace>, ) -> Result", "remoteWorkspacePolicy": "RemoteRouted" }, + { + "id": "inspect_snapshot_storage", + "moduleId": "snapshot_service", + "capabilityId": "setting.data.storage", + "capabilityIds": [ + "setting.data.storage" + ], + "documentedItemIds": [ + "setting.data.storage:clean" + ], + "visibility": "documented", + "rustPath": "inspect_snapshot_storage", + "sourceFile": "src/apps/desktop/src/api/snapshot_service.rs", + "signature": "fn inspect_snapshot_storage( request: InspectSnapshotStorageRequest, ) -> Result", + "remoteWorkspacePolicy": "WorkspaceAgnostic" + }, { "id": "install_acp_client_cli", "moduleId": "acp_client", diff --git a/src/apps/desktop/src/api/snapshot_service.rs b/src/apps/desktop/src/api/snapshot_service.rs index a6c5a891fe..03d24cc337 100644 --- a/src/apps/desktop/src/api/snapshot_service.rs +++ b/src/apps/desktop/src/api/snapshot_service.rs @@ -19,6 +19,50 @@ use tauri::{AppHandle, Emitter, State}; use crate::runtime::{DesktopRuntimeContext, DesktopSessionScopeRequest}; +use openbitfun_core::service::snapshot::maintenance::{ + self, Candidate, CleanupResult, Period, StorageOverview, +}; + +#[derive(Deserialize)] +pub struct InspectSnapshotStorageRequest { + period: Period, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CleanSnapshotStorageRequest { + workspace_id: String, + period: Period, + candidates: Vec, +} + +#[tauri::command] +pub async fn inspect_snapshot_storage( + request: InspectSnapshotStorageRequest, +) -> Result { + maintenance::inspect(request.period) + .await + .map_err(|e| e.to_string()) +} + +#[tauri::command] +pub async fn clean_snapshot_storage( + runtime: State<'_, DesktopRuntimeContext>, + request: CleanSnapshotStorageRequest, +) -> Result { + ensure_local_runtime_ownership( + runtime.inner(), + &SnapshotRemoteScope { + workspace_id: Some(request.workspace_id.clone()), + ..Default::default() + }, + ) + .await?; + maintenance::clean(&request.workspace_id, request.period, request.candidates) + .await + .map_err(|e| e.to_string()) +} + #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct SnapshotRemoteScope { #[serde(default, alias = "workspaceId")] diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index 942f0cdc49..829118b33f 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -1718,6 +1718,8 @@ pub async fn run() { get_snapshot_sessions, check_git_isolation, get_file_change_history, + inspect_snapshot_storage, + clean_snapshot_storage, get_all_modified_files, get_baseline_snapshot_diff, // Session persistence API diff --git a/src/crates/assembly/core/src/agentic/session/session_manager.rs b/src/crates/assembly/core/src/agentic/session/session_manager.rs index d669ee1130..8e26b01025 100644 --- a/src/crates/assembly/core/src/agentic/session/session_manager.rs +++ b/src/crates/assembly/core/src/agentic/session/session_manager.rs @@ -5510,7 +5510,18 @@ impl SessionManager { { let snapshot_service = snapshot_manager.get_snapshot_service(); let snapshot_service = snapshot_service.read().await; - if let Err(error) = snapshot_service.accept_session(session_id).await { + let result = if policy == SessionResourceCleanupPolicy::BestEffort + && self.config.enable_persistence + && !self.is_transient_session(session_id) + { + // Persisted deletion reclaims references after releasing the session writer lock. + snapshot_service + .release_session_file_locks(session_id) + .await + } else { + snapshot_service.accept_session(session_id).await + }; + if let Err(error) = result { record_error("snapshot", error.to_string()); } } @@ -5570,7 +5581,7 @@ impl SessionManager { .resolve_session_workspace_binding(session_id) .await .and_then(|binding| binding.workspace_id); - let _temporary_write_lock = if self.config.enable_persistence + let temporary_write_lock = if self.config.enable_persistence && !self.is_transient_session(session_id) && !self.session_write_locks.contains_key(session_id) { @@ -5586,9 +5597,7 @@ impl SessionManager { self.config.enable_persistence ); - // Persisted deletion is the only fallible required stage. Complete it - // before mutating loaded runtime state so a storage failure leaves the - // active session usable and retryable. + let mut pending_snapshot_deletion = None; if self.config.enable_persistence { let revert_state = self .persistence_manager @@ -5602,6 +5611,15 @@ impl SessionManager { "Session deletion cannot discard an unfinished revert transition: session_id={session_id}" ))); } + pending_snapshot_deletion = + crate::service::snapshot::maintenance::prepare_session_deletion( + self.persistence_manager.path_manager(), + cleanup_workspace_id.as_deref(), + session_storage_path, + session_id, + ) + .await + .map_err(|e| OpenBitFunError::Session(e.to_string()))?; let persistence_stage_started_at = Instant::now(); debug!( "Session deletion stage starting: session_id={}, stage=persistence_delete", @@ -5664,6 +5682,12 @@ impl SessionManager { ); self.session_storage_path_index.remove(session_id); self.release_session_write_lock(session_id); + drop(temporary_write_lock); + if let Some(intent) = pending_snapshot_deletion { + if let Err(e) = intent.finish(self.persistence_manager.path_manager()).await { + warn!("Snapshot cleanup deferred after session deletion: session_id={session_id}, error={e}"); + } + } info!( "Session deletion completed: session_id={}, cleanup_workspace_path={}, session_storage_path={}, duration_ms={}", diff --git a/src/crates/assembly/core/src/agentic/session/session_manager/tests/deletion.rs b/src/crates/assembly/core/src/agentic/session/session_manager/tests/deletion.rs index 65af3c48b5..f712e45187 100644 --- a/src/crates/assembly/core/src/agentic/session/session_manager/tests/deletion.rs +++ b/src/crates/assembly/core/src/agentic/session/session_manager/tests/deletion.rs @@ -248,3 +248,72 @@ async fn direct_delete_rejects_an_unfinished_revert_transition() { Some(state) ); } + +#[tokio::test] +async fn cold_session_deletion_reclaims_persisted_file_snapshots() { + let workspace = TestWorkspace::new(); + let paths = workspace.path_manager(); + let persistence = Arc::new(PersistenceManager::new(paths.clone()).unwrap()); + let manager = test_manager(persistence); + for simulate_busy_writer in [false, true] { + let session = manager + .create_session( + "Cold".into(), + "agent".into(), + SessionConfig { + workspace_path: Some(workspace.path().to_string_lossy().into_owned()), + ..Default::default() + }, + ) + .await + .unwrap(); + let id = &session.session_id; + let snapshots = paths.project_snapshots_dir(workspace.path()); + let ops = snapshots.join("operations"); + std::fs::create_dir_all(&ops).unwrap(); + let history = ops.join(format!("{id}.json")); + std::fs::write( + &history, + serde_json::json!({ + "session_id": id, "last_updated": std::time::SystemTime::now(), "turns": {} + }) + .to_string(), + ) + .unwrap(); + manager.evict_loaded_session_for_test(id); + assert!( + crate::service::snapshot::get_snapshot_manager_for_workspace(workspace.workspace_id()) + .is_none() + ); + let gate = if simulate_busy_writer { + let dir = paths + .project_runtime_root(workspace.path()) + .join("locks/snapshot-writers"); + std::fs::create_dir_all(&dir).unwrap(); + let gate = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(dir.join("maintenance.lock")) + .unwrap(); + gate.try_lock().unwrap(); + Some(gate) + } else { + None + }; + manager.delete_session(workspace.path(), id).await.unwrap(); + if let Some(gate) = gate { + assert!(history.is_file()); + drop(gate); + crate::service::snapshot::maintenance::retry_pending_deletions(&paths) + .await + .unwrap(); + } + assert!(!history.exists()); + assert!(!paths + .project_sessions_dir(workspace.path()) + .join(id) + .exists()); + } +} diff --git a/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs b/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs index 0f5d5d7e33..d887b54f2c 100644 --- a/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs +++ b/src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs @@ -388,10 +388,16 @@ impl PathManager { /// Get the runtime root for a workspace: ~/.openbitfun/projects/<24-hex-key>/ pub fn project_runtime_root(&self, workspace_path: &Path) -> PathBuf { - let runtime_root = self - .projects_root() - .join(self.project_runtime_key(workspace_path)); - self.migrate_legacy_project_runtime(workspace_path, &runtime_root) + self.migrate_legacy_project_runtime( + workspace_path, + &self.project_runtime_location(workspace_path), + ) + } + + /// Compute the current layout location without migrating any persisted data. + pub(crate) fn project_runtime_location(&self, workspace_path: &Path) -> PathBuf { + self.projects_root() + .join(self.project_runtime_key(workspace_path)) } /// Get the legacy runtime root for a local workspace. diff --git a/src/crates/assembly/core/src/service/snapshot/maintenance/mod.rs b/src/crates/assembly/core/src/service/snapshot/maintenance/mod.rs new file mode 100644 index 0000000000..90bac8f1e8 --- /dev/null +++ b/src/crates/assembly/core/src/service/snapshot/maintenance/mod.rs @@ -0,0 +1,462 @@ +//! Controller-local file snapshot accounting. All deletion paths originate in +//! a directory enumeration of the app store, never in a request or descriptor. +mod pending; +mod plan; +pub(crate) use pending::{prepare_session_deletion, retry_pending_deletions}; +mod writer_lease; +pub(super) use writer_lease::{ViewStamp, WriterLease}; + +use super::manager::{bound_snapshot_context, maintenance_manager}; +use super::types::{SnapshotError, SnapshotResult}; +use crate::agentic::WorkspaceBinding; +use crate::infrastructure::PathManager; +use crate::service::workspace_runtime::{WorkspaceRuntimeContext, WorkspaceRuntimeTarget}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashSet}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Period { + SevenDays, + ThirtyDays, + All, +} + +impl Period { + fn includes(self, active: u64, now: u64) -> bool { + let days = match self { + Self::SevenDays => 7, + Self::ThirtyDays => 30, + Self::All => return true, + }; + active < now.saturating_sub(days * 86_400_000) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct Candidate { + pub session_id: String, + pub name: String, + pub active_at: u64, + pub revision: String, + #[serde(default)] + pub removed: bool, +} + +#[derive(Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceUsage { + workspace_id: String, + name: String, + location: String, + bytes: u64, + shared_bytes: u64, + estimated_bytes: u64, + removed_estimated_bytes: u64, + skipped_sessions: usize, + candidates: Vec, + warning: Option, + unverified_references: bool, +} + +#[derive(Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StorageOverview { + total_bytes: u64, + unidentified_bytes: u64, + workspaces: Vec, + scan_errors: Vec, +} + +#[derive(Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CleanupResult { + removed_sessions: usize, + skipped_sessions: usize, + freed_bytes: u64, + errors: Vec, +} + +#[derive(Default)] +pub(super) struct Removed { + pub sessions: HashSet, + pub handles: HashSet, + pub blobs: HashSet, +} + +struct Scope { + id: String, + name: String, + location: String, + remote: bool, + context: WorkspaceRuntimeContext, + sessions: PathBuf, +} + +fn invalid(message: impl ToString) -> SnapshotError { + SnapshotError::ConfigError(message.to_string()) +} + +fn millis(time: SystemTime) -> Option { + time.duration_since(UNIX_EPOCH) + .ok()? + .as_millis() + .try_into() + .ok() +} + +async fn known_scopes(paths: &PathManager) -> SnapshotResult>> { + let service = crate::service::workspace::get_global_workspace_service() + .ok_or_else(|| invalid("Workspace service unavailable"))?; + let mut scopes = BTreeMap::new(); + for record in service.list_workspace_infos().await { + let Ok(binding) = WorkspaceBinding::resolve(&record.id).await else { + continue; + }; + let identity = &binding.session_identity; + let remote = identity.is_remote(); + // Opening Storage must not run the normal on-demand runtime migration. + let context = if remote { + use openbitfun_services_core::workspace_identity::{ + normalize_remote_workspace_path, remote_workspace_runtime_key, + remote_workspace_runtime_root, + }; + let host = identity.identity_host(); + let remote_root = normalize_remote_workspace_path(&identity.logical_workspace_path); + let legacy = remote_workspace_runtime_root( + paths.remote_ssh_mirror_root_dir(), + &host, + &remote_root, + ); + if legacy.join("snapshots").exists() || legacy.join("sessions").exists() { + continue; + } + let root = paths + .projects_root() + .join(remote_workspace_runtime_key(&host, &remote_root)); + WorkspaceRuntimeContext::new( + WorkspaceRuntimeTarget::RemoteWorkspaceMirror { + ssh_host: host, + remote_root, + }, + root, + ) + } else { + WorkspaceRuntimeContext::new( + WorkspaceRuntimeTarget::LocalWorkspace { + workspace_root: binding.root_path.clone(), + }, + paths.project_runtime_location(&binding.root_path), + ) + }; + let Ok(context) = bound_snapshot_context(identity, context) else { + continue; + }; + let sessions = if !remote && binding.project_root_path != binding.root_path { + paths + .project_runtime_location(&binding.project_root_path) + .join("sessions") + } else { + context.sessions_dir.clone() + }; + let location = if remote { + format!( + "{} · {} · {}", + identity.hostname, + identity.logical_workspace_path, + identity.remote_connection_id.as_deref().unwrap_or_default() + ) + } else { + identity.logical_workspace_path.clone() + }; + let key = context.snapshots_dir.clone(); + let scope = Scope { + id: record.id, + name: record.name, + remote, + context, + sessions, + location, + }; + scopes + .entry(key) + .and_modify(|v| *v = None) + .or_insert(Some(scope)); + } + Ok(scopes) +} + +// Ignore symbolic links, including directory links. An unreadable directory +// is an error, not evidence that a blob has no owners. +fn entries(dir: &Path) -> SnapshotResult> { + match fs::symlink_metadata(dir) { + Ok(m) if m.is_dir() => Ok(fs::read_dir(dir)?.collect::>()?), + Ok(_) => Err(invalid(format!( + "Expected a storage directory: {}", + dir.display() + ))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(e) => Err(e.into()), + } +} + +fn checked_path(root: &Path, path: &Path) -> SnapshotResult<()> { + let mut current = root.to_owned(); + for part in path.strip_prefix(root).map_err(invalid)?.components() { + let std::path::Component::Normal(part) = part else { + return Err(invalid("Invalid storage path")); + }; + current.push(part); + match fs::symlink_metadata(¤t) { + Ok(m) if m.is_symlink() => { + return Err(invalid(format!( + "Linked storage path: {}", + current.display() + ))) + } + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()), + _ => {} + } + } + Ok(()) +} + +fn tree_bytes(root: &Path, omit_scopes: bool) -> SnapshotResult { + let mut pending = vec![root.to_owned()]; + let mut bytes = 0; + while let Some(dir) = pending.pop() { + for entry in entries(&dir)? { + let kind = entry.file_type()?; + if kind.is_file() { + bytes += entry.metadata()?.len(); + } + if kind.is_dir() + && !(omit_scopes && dir == root && entry.file_name() == "workspace-identities") + { + pending.push(entry.path()); + } + } + } + Ok(bytes) +} + +pub async fn inspect(period: Period) -> SnapshotResult { + let paths = crate::infrastructure::try_get_path_manager_arc()?; + let known = known_scopes(&paths).await?; + tokio::task::spawn_blocking(move || { + let mut result = inspect_roots(&paths.projects_root(), known, period)?; + inspect_legacy_mirrors(&paths.remote_ssh_mirror_root_dir(), &mut result); + Ok(result) + }) + .await + .map_err(invalid)? +} + +// Legacy remote runtimes mirror the host and POSIX workspace path at arbitrary +// depth. Recognize the file snapshot layout before counting a directory. +fn inspect_legacy_mirrors(root: &Path, result: &mut StorageOverview) { + let mut pending = vec![root.to_owned()]; + while let Some(dir) = pending.pop() { + let children = match entries(&dir) { + Ok(children) => children, + Err(e) => { + result.scan_errors.push(e.to_string()); + continue; + } + }; + for child in children { + let path = child.path(); + match child.file_type() { + Ok(kind) if kind.is_dir() => {} + Err(e) => { + result.scan_errors.push(e.to_string()); + continue; + } + _ => continue, + } + if child.file_name() == "snapshots" + && [ + "metadata", + "baselines", + "operations", + "by_hash", + "workspace-identities", + ] + .iter() + .any(|s| path.join(s).is_dir()) + { + match tree_bytes(&path, false) { + Ok(bytes) => { + result.total_bytes += bytes; + result.unidentified_bytes += bytes; + } + Err(e) => result + .scan_errors + .push(format!("{}: {}", path.display(), e)), + } + } else { + pending.push(path); + } + } + } +} + +fn inspect_roots( + root: &Path, + mut known: BTreeMap>, + period: Period, +) -> SnapshotResult { + let mut overview = StorageOverview::default(); + for project in entries(root)? { + if !project.file_type()?.is_dir() { + continue; + } + let base = project.path().join("snapshots"); + if let Err(e) = checked_path(root, &base) { + overview.scan_errors.push(e.to_string()); + continue; + } + let mut dirs = vec![base.clone()]; + match entries(&base.join("workspace-identities")) { + Ok(children) => { + for child in children { + match child.file_type() { + Ok(kind) if kind.is_dir() => dirs.push(child.path()), + Ok(kind) if kind.is_file() => match child.metadata() { + Ok(meta) => { + overview.unidentified_bytes += meta.len(); + overview.total_bytes += meta.len(); + } + Err(e) => overview.scan_errors.push(e.to_string()), + }, + Ok(_) => {} + Err(e) => overview.scan_errors.push(e.to_string()), + } + } + } + Err(e) => overview.scan_errors.push(e.to_string()), + } + for dir in dirs { + let bytes = match tree_bytes(&dir, dir == base) { + Ok(bytes) => bytes, + Err(e) => { + overview + .scan_errors + .push(format!("{}: {}", dir.display(), e)); + continue; + } + }; + overview.total_bytes += bytes; + let Some(Some(scope)) = known.remove(&dir) else { + overview.unidentified_bytes += bytes; + continue; + }; + let mut row = WorkspaceUsage { + bytes, + workspace_id: scope.id.clone(), + name: scope.name.clone(), + location: scope.location.clone(), + ..Default::default() + }; + match checked_path(root, &scope.sessions) + .and_then(|_| plan::Plan::load(&scope, period, None)) + { + Ok(plan) => { + row.shared_bytes = bytes.saturating_sub(plan.single_session_bytes); + row.estimated_bytes = plan.estimate(); + row.removed_estimated_bytes = plan.removed_estimated_bytes; + row.skipped_sessions = plan.skipped; + row.unverified_references = plan.unverified_references; + row.candidates = plan.candidates.into_values().collect(); + } + Err(e) => row.warning = Some(e.to_string()), + } + overview.workspaces.push(row); + } + } + overview + .workspaces + .sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.name.cmp(&b.name))); + Ok(overview) +} + +pub async fn clean( + workspace_id: &str, + period: Period, + confirmed: Vec, +) -> SnapshotResult { + let paths = crate::infrastructure::try_get_path_manager_arc()?; + let scope = registered_scope(&paths, workspace_id).await?; + clean_scope( + scope, + Cleanup::Confirmed(period, confirmed), + paths.projects_root(), + ) + .await +} + +enum Cleanup { + Confirmed(Period, Vec), + Pending(Vec), +} + +async fn registered_scope(paths: &PathManager, workspace_id: &str) -> SnapshotResult { + known_scopes(paths) + .await? + .into_values() + .flatten() + .find(|s| s.id == workspace_id) + .ok_or_else(|| invalid("Snapshot store has no unique registered workspace owner")) +} + +async fn clean_scope( + scope: Scope, + cleanup: Cleanup, + root: PathBuf, +) -> SnapshotResult { + let (registration, manager) = maintenance_manager(&scope.id, scope.remote).await; + tokio::task::spawn_blocking(move || { + let _registration = registration; + checked_path(&root, &scope.context.snapshots_dir)?; + checked_path(&root, &scope.sessions)?; + checked_path(&root, &scope.context.locks_dir)?; + let service = manager.map(|m| m.get_snapshot_service()); + let service = service.as_ref().map(|s| s.blocking_write()); + let own = service.as_ref().and_then(|s| s.writer_lease.as_ref()); + let _exclusive = writer_lease::exclusive(&scope.context.locks_dir, own)?; + let mut core = service.as_ref().map(|s| s.snapshot_core.blocking_write()); + let (mut plan, requested, deleted_ids): (_, _, Vec<&str>) = match &cleanup { + Cleanup::Confirmed(period, candidates) => ( + plan::Plan::load(&scope, *period, Some(candidates))?, + candidates.len(), + candidates + .iter() + .filter(|c| c.removed) + .map(|c| c.session_id.as_str()) + .collect(), + ), + Cleanup::Pending(ids) => ( + plan::Plan::for_deleted_sessions(&scope, ids)?, + ids.len(), + ids.iter().map(String::as_str).collect(), + ), + }; + let (mut result, removed) = plan.remove(requested); + if let Some(core) = &mut core { + core.forget_cleaned_history(&removed); + } + if let Err(e) = pending::acknowledge(&root, &scope, deleted_ids.into_iter()) { + result.errors.push(e.to_string()); + } + Ok(result) + }) + .await + .map_err(invalid)? +} + +#[cfg(test)] +mod tests; diff --git a/src/crates/assembly/core/src/service/snapshot/maintenance/pending.rs b/src/crates/assembly/core/src/service/snapshot/maintenance/pending.rs new file mode 100644 index 0000000000..4737886149 --- /dev/null +++ b/src/crates/assembly/core/src/service/snapshot/maintenance/pending.rs @@ -0,0 +1,233 @@ +//! Deletion intents live outside both the chat and its snapshot history. +//! Replay uses the same disk reference scan and writer locks as manual cleanup. +use super::*; +use crate::service::snapshot::{snapshot_core::sanitize_id, storage::write_atomic}; +use sha2::{Digest, Sha256}; + +#[derive(Deserialize, Serialize)] +pub(crate) struct PendingDeletion { + workspace_id: String, + store_key: String, + session_id: String, +} + +// Bind the intent to both stores. A reconfigured worktree or SSH connection +// can keep its workspace ID while resolving to different on-disk data. +fn store_key(projects: &Path, scope: &Scope) -> SnapshotResult { + let identity = ( + &scope.id, + scope + .context + .snapshots_dir + .strip_prefix(projects) + .map_err(invalid)?, + scope.sessions.strip_prefix(projects).map_err(invalid)?, + ); + Ok(format!( + "{:x}", + Sha256::digest(serde_json::to_vec(&identity)?) + )) +} + +impl PendingDeletion { + fn new(projects: &Path, scope: &Scope, id: &str) -> SnapshotResult { + Ok(Self { + workspace_id: scope.id.clone(), + store_key: store_key(projects, scope)?, + session_id: id.to_owned(), + }) + } + + fn directory(projects: &Path) -> PathBuf { + projects.with_file_name("pending-snapshot-deletions") + } + + fn path(&self, projects: &Path) -> SnapshotResult { + let digest = Sha256::digest(serde_json::to_vec(self)?); + Ok(Self::directory(projects).join(format!("{digest:x}.json"))) + } + + pub(super) fn prepare( + projects: &Path, + scope: &Scope, + session_id: &str, + ) -> SnapshotResult> { + let history = history_path(scope, session_id); + checked_path(&scope.context.snapshots_dir, &history)?; + if missing(&history)? { + return Ok(None); + } + let intent = Self::new(projects, scope, session_id)?; + let path = intent.path(projects)?; + validate_journal_path(projects, &path)?; + fs::create_dir_all(Self::directory(projects))?; + write_atomic(&path, &serde_json::to_vec(&intent)?)?; + Ok(Some(intent)) + } + + pub(crate) async fn finish(self, paths: &PathManager) -> SnapshotResult<()> { + let scope = registered_scope(paths, &self.workspace_id).await?; + let projects = paths.projects_root(); + if store_key(&projects, &scope)? != self.store_key { + return Err(invalid( + "Snapshot store identity changed after session deletion", + )); + } + let result = clean_scope(scope, Cleanup::Pending(vec![self.session_id]), projects).await?; + if result.errors.is_empty() && result.skipped_sessions == 0 { + Ok(()) + } else { + Err(invalid(format!( + "Snapshot cleanup deferred: {} skipped, {:?}", + result.skipped_sessions, result.errors + ))) + } + } +} + +fn history_path(scope: &Scope, session_id: &str) -> PathBuf { + scope + .context + .snapshot_operations_dir + .join(format!("{}.json", sanitize_id(session_id))) +} + +fn missing(path: &Path) -> SnapshotResult { + match fs::symlink_metadata(path) { + Ok(_) => Ok(false), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true), + Err(e) => Err(e.into()), + } +} + +pub(crate) async fn prepare_session_deletion( + paths: &PathManager, + workspace_id: Option<&str>, + sessions: &Path, + session_id: &str, +) -> SnapshotResult> { + openbitfun_core_types::validate_session_id(session_id).map_err(invalid)?; + if crate::service::workspace::get_global_workspace_service().is_none() { + return Ok(None); + } + let scopes = known_scopes(paths).await?; + let actual = dunce::canonicalize(sessions)?; + let mut matches = scopes.into_values().flatten().filter(|s| { + workspace_id.is_none_or(|id| s.id == id) + && dunce::canonicalize(&s.sessions).is_ok_and(|p| p == actual) + }); + let Some(scope) = matches.next() else { + return Ok(None); + }; + if matches.next().is_some() { + return Ok(None); + } + let root = paths.projects_root(); + let id = session_id.to_owned(); + tokio::task::spawn_blocking(move || { + checked_path(&root, &scope.context.snapshots_dir)?; + checked_path(&root, &scope.context.locks_dir)?; + checked_path(&root, &scope.sessions)?; + PendingDeletion::prepare(&root, &scope, &id) + }) + .await + .map_err(invalid)? +} + +// A crash after unlinking the history but before acknowledging the intent is +// harmless. An intent for a surviving session can also be retired under its lock. +pub(super) fn acknowledge<'a>( + projects: &Path, + scope: &Scope, + ids: impl Iterator, +) -> SnapshotResult<()> { + for id in ids { + openbitfun_core_types::validate_session_id(id).map_err(invalid)?; + let intent = PendingDeletion::new(projects, scope, id)?; + let path = intent.path(projects)?; + validate_journal_path(projects, &path)?; + if missing(&path)? { + continue; + } + if !missing(&history_path(scope, id))? { + // An interrupted or failed deletion can leave both the chat and the intent. + // Retire that intent only after the original deleting writer has gone away. + if !fs::symlink_metadata(&scope.sessions).is_ok_and(|m| m.is_dir()) { + continue; + } + let Ok(_guard) = + openbitfun_services_core::session::SessionWriteLock::try_acquire_for_maintenance( + &scope.sessions, + id, + ) + else { + continue; + }; + if !fs::symlink_metadata(scope.sessions.join(id)).is_ok_and(|m| m.is_dir()) { + continue; + } + fs::remove_file(path)?; + } else { + fs::remove_file(path)?; + } + } + Ok(()) +} + +fn validate_journal_path(projects: &Path, path: &Path) -> SnapshotResult<()> { + checked_path( + projects + .parent() + .ok_or_else(|| invalid("Invalid project storage root"))?, + path, + ) +} + +pub(super) fn pending_by_store(projects: &Path) -> SnapshotResult>> { + let mut pending = BTreeMap::>::new(); + for entry in entries(&PendingDeletion::directory(projects))? { + let path = entry.path(); + if !entry.file_type()?.is_file() || path.extension().is_none_or(|e| e != "json") { + continue; + } + match plan::json::(&path) { + Ok(intent) + if intent.path(projects)? == path + && openbitfun_core_types::validate_session_id(&intent.session_id).is_ok() => + { + pending + .entry(intent.store_key) + .or_default() + .push(intent.session_id); + } + _ => log::warn!( + "Leaving unrecognized snapshot deletion intent in {}", + path.display() + ), + } + } + Ok(pending) +} + +pub(crate) async fn retry_pending_deletions(paths: &PathManager) -> SnapshotResult<()> { + let projects = paths.projects_root(); + let root = projects.clone(); + let mut pending = tokio::task::spawn_blocking(move || pending_by_store(&root)) + .await + .map_err(invalid)??; + if pending.is_empty() { + return Ok(()); + } + for scope in known_scopes(paths).await?.into_values().flatten() { + let id = scope.id.clone(); + let Some(session_ids) = pending.remove(&store_key(&projects, &scope)?) else { + continue; + }; + match clean_scope(scope, Cleanup::Pending(session_ids), projects.clone()).await { + Ok(result) if result.errors.is_empty() => {} + Ok(result) => log::warn!("Pending snapshot cleanup for {id}: {:?}", result.errors), + Err(e) => log::warn!("Pending snapshot cleanup for {id} deferred: {e}"), + } + } + Ok(()) +} diff --git a/src/crates/assembly/core/src/service/snapshot/maintenance/plan.rs b/src/crates/assembly/core/src/service/snapshot/maintenance/plan.rs new file mode 100644 index 0000000000..cbf8159979 --- /dev/null +++ b/src/crates/assembly/core/src/service/snapshot/maintenance/plan.rs @@ -0,0 +1,470 @@ +use super::*; +use crate::service::snapshot::{ + snapshot_core::sanitize_id, + storage::{descriptor, read_bounded, CONTENT_LIMIT}, +}; +use openbitfun_services_core::session::{ + SessionLastTurn, SessionWriteLock, TurnStatus, SESSION_STORAGE_SCHEMA_VERSION, +}; +use serde::de::DeserializeOwned; +use std::collections::HashMap; +use std::fs::File; + +#[derive(Deserialize)] +struct History { + session_id: String, + last_updated: SystemTime, + turns: BTreeMap, +} +#[derive(Deserialize)] +struct Turn { + operations: Vec, +} +#[derive(Deserialize)] +struct Operation { + before_snapshot_id: Option, + after_snapshot_id: Option, + completed: Option, +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Activity { + #[serde(default, alias = "schema_version")] + schema_version: u32, + #[serde(alias = "session_id")] + session_id: String, + #[serde(alias = "last_active_at")] + last_active_at: u64, + #[serde(alias = "session_name")] + session_name: String, + #[serde(alias = "last_turn")] + last_turn: Option, + #[serde(alias = "needs_user_attention")] + needs_user_attention: Option, +} + +#[derive(Clone, Copy)] +enum Admission<'a> { + Preview, + Confirmed(&'a Candidate), + RemovedSession, +} + +impl History { + fn candidate( + &self, + sessions: &Path, + period: Period, + unfinished: bool, + now: u64, + admission: Admission, + ) -> Option<(Candidate, Option)> { + let id = &self.session_id; + let dir = sessions.join(id); + checked_path(sessions, &dir).ok()?; + // A missing sessions root, inaccessible directory or link cannot prove deletion. + if !fs::symlink_metadata(sessions).ok()?.is_dir() { + return None; + } + let lock = if !matches!(admission, Admission::Preview) { + Some(SessionWriteLock::try_acquire_for_maintenance(sessions, id).ok()?) + } else { + if SessionWriteLock::is_in_use(sessions, id).ok()? { + return None; + } + None + }; + let candidate = match fs::symlink_metadata(&dir) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + removed_candidate(id, self.last_updated)? + } + Ok(metadata) + if metadata.is_dir() + && !unfinished + && !matches!(admission, Admission::RemovedSession) => + { + self.live_candidate(&dir, period, now)? + } + _ => return None, + }; + if matches!(admission, Admission::Confirmed(expected) if expected != &candidate) { + return None; + } + Some((candidate, lock)) + } + + fn live_candidate(&self, dir: &Path, period: Period, now: u64) -> Option { + if !matches!(fs::symlink_metadata(dir.join("session-revert.json")), Err(e) if e.kind() == std::io::ErrorKind::NotFound) + { + return None; + } + let activity: Activity = json(&dir.join("metadata.json")).ok()?; + if activity.schema_version > SESSION_STORAGE_SCHEMA_VERSION + || activity.session_id != self.session_id + || activity.last_active_at == 0 + || activity.needs_user_attention.is_some() + || activity.last_turn.as_ref().is_some_and(|t| { + t.status == TurnStatus::InProgress || t.recovery_pending == Some(true) + }) + { + return None; + } + let updated = self.last_updated.duration_since(UNIX_EPOCH).ok()?; + let active_at = activity.last_active_at.max(millis(self.last_updated)?); + if !period.includes(active_at, now) { + return None; + } + Some(Candidate { + removed: false, + session_id: self.session_id.clone(), + name: activity.session_name, + active_at, + revision: format!("{}:{}", activity.last_active_at, updated.as_nanos()), + }) + } +} + +fn removed_candidate(id: &str, updated: SystemTime) -> Option { + Some(Candidate { + session_id: id.to_owned(), + name: String::new(), + active_at: millis(updated)?, + revision: format!( + "removed:{}", + updated.duration_since(UNIX_EPOCH).ok()?.as_nanos() + ), + removed: true, + }) +} + +pub(super) fn json(path: &Path) -> SnapshotResult { + let metadata = fs::symlink_metadata(path)?; + if !metadata.is_file() || metadata.len() > CONTENT_LIMIT as u64 { + return Err(invalid("Invalid storage record")); + } + let bytes = read_bounded(File::open(path)?, CONTENT_LIMIT, path)?; + Ok(serde_json::from_slice(&bytes)?) +} + +struct StoredFile { + path: PathBuf, + bytes: u64, +} +impl StoredFile { + fn new(entry: &fs::DirEntry) -> SnapshotResult { + Ok(Self { + path: entry.path(), + bytes: entry.metadata()?.len(), + }) + } +} + +#[derive(Default)] +pub(super) struct Plan { + pub(super) candidates: BTreeMap, + pub(super) single_session_bytes: u64, + pub(super) removed_estimated_bytes: u64, + removed_histories: BTreeMap, + pub(super) skipped: usize, + pub(super) unverified_references: bool, + histories: BTreeMap, + handles: BTreeMap, + blobs: BTreeMap, + // Held across the final revalidation, unlink and in-memory invalidation. + locks: Vec, +} + +impl Plan { + pub(super) fn load( + scope: &Scope, + period: Period, + confirmed: Option<&[Candidate]>, + ) -> SnapshotResult { + let selected = confirmed.map(|items| { + items + .iter() + .map(|c| (c.session_id.as_str(), Admission::Confirmed(c))) + .collect() + }); + Self::load_selected(scope, period, selected) + } + + pub(super) fn for_deleted_sessions(scope: &Scope, ids: &[String]) -> SnapshotResult { + let selected = ids + .iter() + .map(|id| (id.as_str(), Admission::RemovedSession)) + .collect(); + Self::load_selected(scope, Period::All, Some(selected)) + } + + fn load_selected( + scope: &Scope, + period: Period, + selected: Option>, + ) -> SnapshotResult { + let context = &scope.context; + let now = millis(SystemTime::now()).ok_or_else(|| invalid("Invalid system clock"))?; + let mut plan = Self::default(); + let mut owners: HashMap> = HashMap::new(); + let mut unknown_owners = false; + for entry in entries(&context.snapshot_operations_dir)? { + let path = entry.path(); + if path.extension().is_none_or(|ext| ext != "json") { + continue; + } + let history: History = match json::(&path) { + Ok(h) + if openbitfun_core_types::validate_session_id(&h.session_id).is_ok() + && path.file_stem().and_then(|s| s.to_str()) + == Some(&sanitize_id(&h.session_id)) => + { + h + } + _ => { + unknown_owners = true; + plan.skipped += 1; + continue; + } + }; + let history_file = StoredFile::new(&entry)?; + plan.single_session_bytes += history_file.bytes; + let mut unfinished = false; + for op in history.turns.values().flat_map(|t| &t.operations) { + unfinished |= op.completed == Some(false); + for id in [ + op.before_snapshot_id.as_ref(), + op.after_snapshot_id.as_ref(), + ] + .into_iter() + .flatten() + { + owners + .entry(id.clone()) + .or_default() + .insert(history.session_id.clone()); + } + } + // Acquire a fresh lock before reading activity. Loaded writers (including + // this process), stale pending operations and outstanding reverts are retained. + let id = &history.session_id; + let admission = match &selected { + Some(items) => items.get(id.as_str()).copied(), + None => Some(Admission::Preview), + }; + let candidate = admission + .and_then(|a| history.candidate(&scope.sessions, period, unfinished, now, a)); + if let Some((candidate, lock)) = candidate { + if let Some(lock) = lock { + plan.locks.push(lock); + } + if candidate.removed { + plan.removed_estimated_bytes += history_file.bytes; + plan.removed_histories.insert(id.clone(), history_file); + } else { + plan.histories.insert(id.clone(), history_file); + } + plan.candidates.insert(id.clone(), candidate); + } else { + plan.skipped += 1; + } + } + + // Older reverts could borrow operation handles, even from another + // session. Include markers belonging to sessions without an operation file. + let mut checkpoints = HashSet::new(); + for entry in entries(&scope.sessions)? { + if entry.file_type()?.is_symlink() { + unknown_owners = true; + continue; + } + if !entry.file_type()?.is_dir() { + continue; + } + let path = entry.path().join("session-revert.json"); + if matches!(fs::symlink_metadata(&path), Err(e) if e.kind() == std::io::ErrorKind::NotFound) + { + continue; + } + match json::(&path) { + Ok(state) + if state.schema_version + == crate::agentic::session::revert::SESSION_REVERT_SCHEMA_VERSION => + { + checkpoints.extend( + state + .workspace_checkpoint + .into_iter() + .filter_map(|c| c.snapshot_id), + ); + } + _ => unknown_owners = true, + } + } + + plan.collect_files(context, &owners, &checkpoints, unknown_owners)?; + Ok(plan) + } + + fn collect_files( + &mut self, + context: &WorkspaceRuntimeContext, + owners: &HashMap>, + checkpoints: &HashSet, + unknown_owners: bool, + ) -> SnapshotResult<()> { + let mut kept_hashes = HashSet::new(); + let mut owned_hashes = HashSet::new(); + let mut hash_owners: HashMap> = HashMap::new(); + let mut shared_hashes = HashSet::new(); + let mut unknown_hash = false; + for (dir, baseline) in [ + (&context.snapshot_baselines_dir, true), + (&context.snapshot_metadata_dir, false), + ] { + for entry in entries(dir)? { + let path = entry.path(); + if path.extension().is_none_or(|ext| ext != "json") { + continue; + } + if !entry.file_type()?.is_file() { + unknown_hash = true; + continue; + } + let stored = StoredFile::new(&entry)?; + let snapshot = match descriptor(&path) { + Ok(s) if path.file_stem().and_then(|v| v.to_str()) == Some(&s.snapshot_id) => s, + _ => { + unknown_hash = true; + continue; + } + }; + let id = snapshot.snapshot_id; + let hash = snapshot.content_hash; + let refs = owners.get(&id); + let protected = baseline + || snapshot.snapshot_type == super::super::SnapshotType::Baseline + || id.starts_with("baseline_") + || checkpoints.contains(&id) + || refs.is_none(); + if !unknown_owners && !protected && refs.is_some_and(|r| r.len() == 1) { + self.single_session_bytes += stored.bytes; + } + if protected { + shared_hashes.insert(hash.clone()); + } + if let Some(refs) = refs { + hash_owners + .entry(hash.clone()) + .or_default() + .extend(refs.iter().cloned()); + } + if !unknown_owners + && !protected + && refs.is_some_and(|r| r.iter().all(|s| self.candidates.contains_key(s))) + { + owned_hashes.insert(hash); + if refs + .is_some_and(|r| r.iter().all(|s| self.removed_histories.contains_key(s))) + { + self.removed_estimated_bytes += stored.bytes; + } + self.handles.insert(id, stored); + } else { + kept_hashes.insert(hash); + } + } + } + for entry in entries(&context.snapshot_by_hash_dir)? { + if !entry.file_type()?.is_file() { + continue; + } + let path = entry.path(); + let Some(hash) = path + .file_stem() + .and_then(|s| s.to_str()) + .filter(|_| path.extension().is_some_and(|e| e == "snap")) + else { + continue; + }; + let stored = StoredFile::new(&entry)?; + if !unknown_hash + && !unknown_owners + && !shared_hashes.contains(hash) + && hash_owners.get(hash).is_some_and(|r| r.len() == 1) + { + self.single_session_bytes += stored.bytes; + } + if !unknown_hash && owned_hashes.contains(hash) && !kept_hashes.contains(hash) { + if hash_owners + .get(hash) + .is_some_and(|r| r.iter().all(|s| self.removed_histories.contains_key(s))) + { + self.removed_estimated_bytes += stored.bytes; + } + self.blobs.insert(hash.to_owned(), stored); + } + } + self.unverified_references = unknown_owners || unknown_hash; + if self.unverified_references && !self.removed_histories.is_empty() { + // Keep the ownership chain intact until every reference can be checked. + self.skipped += self.removed_histories.len(); + self.candidates.retain(|_, candidate| !candidate.removed); + self.removed_histories.clear(); + self.removed_estimated_bytes = 0; + self.handles + .retain(|id, _| owners[id].iter().all(|s| self.candidates.contains_key(s))); + } + Ok(()) + } + + pub(super) fn estimate(&self) -> u64 { + self.histories + .values() + .chain(self.removed_histories.values()) + .chain(self.handles.values()) + .chain(self.blobs.values()) + .map(|f| f.bytes) + .sum() + } + + pub(super) fn remove(&mut self, requested: usize) -> (CleanupResult, Removed) { + let mut result = CleanupResult::default(); + let mut removed = Removed::default(); + // Detach live undo history first. For removed sessions the history is the + // retry manifest: retain it and its descriptors until exclusive blobs are gone. + // After a crash the next scan can reconstruct the remaining work from disk. + unlink(&self.histories, &mut removed.sessions, &mut result); + if self.removed_histories.is_empty() { + unlink(&self.handles, &mut removed.handles, &mut result); + unlink(&self.blobs, &mut removed.blobs, &mut result); + } else { + unlink(&self.blobs, &mut removed.blobs, &mut result); + unlink(&self.handles, &mut removed.handles, &mut result); + unlink(&self.removed_histories, &mut removed.sessions, &mut result); + } + result.removed_sessions = removed.sessions.len(); + result.skipped_sessions = requested.saturating_sub(result.removed_sessions); + (result, removed) + } +} + +fn unlink( + files: &BTreeMap, + ids: &mut HashSet, + result: &mut CleanupResult, +) { + if !result.errors.is_empty() { + return; + } + for (id, file) in files { + match fs::remove_file(&file.path) { + Ok(()) => { + ids.insert(id.clone()); + result.freed_bytes += file.bytes; + } + Err(e) => result + .errors + .push(format!("{}: {}", file.path.display(), e)), + } + } +} diff --git a/src/crates/assembly/core/src/service/snapshot/maintenance/tests.rs b/src/crates/assembly/core/src/service/snapshot/maintenance/tests.rs new file mode 100644 index 0000000000..e4a3fe2e89 --- /dev/null +++ b/src/crates/assembly/core/src/service/snapshot/maintenance/tests.rs @@ -0,0 +1,533 @@ +use super::*; +use crate::service::workspace_runtime::WorkspaceRuntimeTarget; +use openbitfun_services_core::session::SessionWriteLock; +use serde_json::json; +use std::time::Duration; + +fn scope(root: &Path) -> Scope { + let context = WorkspaceRuntimeContext::new( + WorkspaceRuntimeTarget::LocalWorkspace { + workspace_root: root.join("worktree"), + }, + root.join("project"), + ); + for dir in context.required_directories() { + fs::create_dir_all(dir).unwrap(); + } + Scope { + id: "project".into(), + name: "Project".into(), + location: "local".into(), + remote: false, + sessions: context.sessions_dir.clone(), + context, + } +} + +fn history(scope: &Scope, id: &str, days: u64, snapshots: &[&str]) { + let time = SystemTime::now() - Duration::from_secs(86_400 * days); + let dir = scope.sessions.join(id); + fs::create_dir_all(&dir).unwrap(); + // Legacy snake-case metadata and operations without an explicit completed flag. + fs::write( + dir.join("metadata.json"), + json!({ + "session_id": id, "session_name": id, "last_active_at": millis(time) + }) + .to_string(), + ) + .unwrap(); + let operations = snapshots + .iter() + .map(|s| json!({"before_snapshot_id":s})) + .collect::>(); + fs::write( + scope + .context + .snapshot_operations_dir + .join(format!("{id}.json")), + json!({"session_id":id,"last_updated":time,"turns":{"0":{"operations":operations}}}) + .to_string(), + ) + .unwrap(); +} + +fn handle(scope: &Scope, id: &str, hash: &str, baseline: bool) -> PathBuf { + let dir = if baseline { + &scope.context.snapshot_baselines_dir + } else { + &scope.context.snapshot_metadata_dir + }; + let path = dir.join(format!("{id}.json")); + fs::write(&path,json!({"snapshot_id":id,"file_path":"a","content_hash":hash, + "snapshot_type":if baseline {"Baseline"} else {"Before"}, "compressed_content":[1,2,3], + "timestamp":UNIX_EPOCH,"metadata":{"size":3,"permissions":null,"last_modified":UNIX_EPOCH,"encoding":"binary"}}).to_string()).unwrap(); + path +} + +#[test] +fn cleanup_preserves_shared_content_checkpoints_and_session_records() { + let tmp = tempfile::tempdir().unwrap(); + let scope = scope(tmp.path()); + let hash_a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let hash_b = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let hash_c = "cccccccccccccccccccccccccccccccc"; + history( + &scope, + "old", + 40, + &["own", "with-base", "shared-id", "revert-id"], + ); + history(&scope, "recent", 1, &["shared-id"]); + let own = handle(&scope, "own", hash_a, false); + let with_base = handle(&scope, "with-base", hash_b, false); + let baseline = handle(&scope, "baseline_x", hash_b, true); + let shared = handle(&scope, "shared-id", hash_c, false); + let borrowed = handle(&scope, "revert-id", hash_c, false); + let marker = scope.sessions.join("undo"); + fs::create_dir_all(&marker).unwrap(); + fs::write( + marker.join("session-revert.json"), + json!({"schemaVersion":1,"boundaryTurn":0,"originalTurnEnd":1, + "phase":"staged","workspaceCheckpoint":[{"path":"a","snapshotId":"revert-id"}]}) + .to_string(), + ) + .unwrap(); + for hash in [hash_a, hash_b, hash_c] { + fs::write( + scope + .context + .snapshot_by_hash_dir + .join(format!("{hash}.snap")), + b"data", + ) + .unwrap(); + } + let large = scope + .context + .snapshot_by_hash_dir + .join(format!("{hash_a}.snap")); + // A sparse 41 GiB payload must be counted and deleted without reading it. + #[cfg(unix)] + fs::OpenOptions::new() + .write(true) + .open(&large) + .unwrap() + .set_len(41 << 30) + .unwrap(); + let preview = plan::Plan::load(&scope, Period::ThirtyDays, None).unwrap(); + assert_eq!(preview.candidates.len(), 1); + let confirmed = vec![preview.candidates["old"].clone()]; + let before = tree_bytes(&scope.context.snapshots_dir, false).unwrap(); + let mut cleanup = plan::Plan::load(&scope, Period::ThirtyDays, Some(&confirmed)).unwrap(); + assert!(SessionWriteLock::try_acquire_for_operation(&scope.sessions, "old").is_err()); + let (result, _) = cleanup.remove(1); + assert_eq!(result.removed_sessions, 1); + assert_eq!(result.freed_bytes, preview.estimate()); + assert_eq!( + before - tree_bytes(&scope.context.snapshots_dir, false).unwrap(), + result.freed_bytes + ); + assert!(!own.exists() && !with_base.exists() && !large.exists()); + assert!(baseline.exists() && shared.exists() && borrowed.exists()); + for hash in [hash_b, hash_c] { + assert!(scope + .context + .snapshot_by_hash_dir + .join(format!("{hash}.snap")) + .is_file()); + } + assert!(scope.sessions.join("old/metadata.json").exists()); + assert!(scope + .context + .snapshot_operations_dir + .join("recent.json") + .exists()); + drop(cleanup); + let (retry, _) = plan::Plan::load(&scope, Period::ThirtyDays, Some(&confirmed)) + .unwrap() + .remove(1); + assert_eq!((retry.skipped_sessions, retry.freed_bytes), (1, 0)); +} + +#[test] +fn rechecks_both_activity_clocks_locks_approval_and_undo_even_for_all() { + let tmp = tempfile::tempdir().unwrap(); + let scope = scope(tmp.path()); + for id in [ + "new-snapshot", + "new-chat", + "locked", + "approval", + "undo", + "lost", + "warm", + "unchanged", + ] { + history(&scope, id, 40, &[]); + } + let initial = plan::Plan::load(&scope, Period::All, None) + .unwrap() + .candidates + .into_values() + .collect::>(); + let _writer = SessionWriteLock::try_acquire(&scope.sessions, "locked").unwrap(); + let now = SystemTime::now(); + let update = |path: PathBuf, key: &str, value: serde_json::Value| { + let mut record: serde_json::Value = + serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + record[key] = value; + fs::write(path, record.to_string()).unwrap(); + }; + update( + scope + .context + .snapshot_operations_dir + .join("new-snapshot.json"), + "last_updated", + json!(now), + ); + update( + scope.sessions.join("new-chat/metadata.json"), + "last_active_at", + json!(millis(now)), + ); + update( + scope.sessions.join("approval/metadata.json"), + "needsUserAttention", + json!("tool_confirm"), + ); + fs::write(scope.sessions.join("undo/session-revert.json"), b"{").unwrap(); + fs::remove_file(scope.sessions.join("lost/metadata.json")).unwrap(); + history(&scope, "warm", 15, &[]); + let seven = plan::Plan::load(&scope, Period::SevenDays, None).unwrap(); + assert_eq!(seven.candidates.len(), 2); + let month = plan::Plan::load(&scope, Period::ThirtyDays, None).unwrap(); + assert_eq!(month.candidates.len(), 1); + let mut final_plan = plan::Plan::load(&scope, Period::All, Some(&initial)).unwrap(); + assert_eq!( + final_plan.candidates.keys().collect::>(), + vec!["unchanged"] + ); + assert_eq!(final_plan.remove(initial.len()).0.skipped_sessions, 7); +} + +#[test] +fn inventory_counts_unregistered_and_connection_scoped_stores_once() { + let tmp = tempfile::tempdir().unwrap(); + let mut scope = scope(tmp.path()); + let base = scope.context.snapshots_dir.clone(); + fs::write(base.join("legacy"), b"12345").unwrap(); + let scoped = base.join("workspace-identities/profile-a"); + fs::create_dir_all(&scoped).unwrap(); + fs::write(scoped.join("data"), b"abc").unwrap(); + let other = base.join("workspace-identities/profile-b"); + fs::create_dir_all(&other).unwrap(); + fs::write(other.join("data"), b"1234").unwrap(); + scope.context.snapshots_dir = scoped.clone(); + let overview = inspect_roots( + tmp.path(), + BTreeMap::from([(scoped, Some(scope))]), + Period::All, + ) + .unwrap(); + assert_eq!((overview.total_bytes, overview.unidentified_bytes), (12, 9)); + assert_eq!(overview.workspaces[0].bytes, 3); +} + +#[test] +fn another_writer_prevents_reclamation_until_it_releases_its_index() { + let tmp = tempfile::tempdir().unwrap(); + let cached = ViewStamp::capture(tmp.path()); + assert!(cached.current()); + let own = WriterLease::register(tmp.path()).unwrap(); + let other = WriterLease::register(tmp.path()).unwrap(); + assert!(writer_lease::exclusive(tmp.path(), Some(&own)).is_err()); + drop(other); + let exclusive = writer_lease::exclusive(tmp.path(), Some(&own)).unwrap(); + assert!(writer_lease::exclusive(tmp.path(), Some(&own)).is_err()); + let during = ViewStamp::capture(tmp.path()); + assert!(!cached.current()); + drop(exclusive); + assert!(!during.current() && !cached.current()); + assert!(ViewStamp::capture(tmp.path()).current()); + assert!(writer_lease::exclusive(tmp.path(), None).is_err()); +} + +#[cfg(unix)] +#[test] +fn a_linked_store_cannot_escape_or_disable_another_workspace() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let external = tempfile::tempdir().unwrap(); + fs::write(external.path().join("keep"), b"unused").unwrap(); + let scope = scope(tmp.path()); + let linked = tmp.path().join("other/snapshots"); + fs::create_dir_all(linked.parent().unwrap()).unwrap(); + symlink(external.path(), &linked).unwrap(); + history(&scope, "valid", 40, &[]); + let overview = inspect_roots( + tmp.path(), + BTreeMap::from([(scope.context.snapshots_dir.clone(), Some(scope))]), + Period::All, + ) + .unwrap(); + assert_eq!(overview.scan_errors.len(), 1); + assert_eq!(overview.workspaces[0].candidates.len(), 1); + assert_eq!(overview.unidentified_bytes, 0); +} + +#[test] +fn legacy_mirrors_are_counted_read_only_without_counting_transcripts() { + let tmp = tempfile::tempdir().unwrap(); + let project = tmp.path().join("ssh-server/nested/project"); + let history = project.join("snapshots/operations/old.json"); + fs::create_dir_all(history.parent().unwrap()).unwrap(); + fs::write(&history, b"history").unwrap(); + let chat = project.join("sessions/s/snapshots/dialog.json"); + fs::create_dir_all(chat.parent().unwrap()).unwrap(); + fs::write(&chat, b"session record").unwrap(); + let mut overview = StorageOverview::default(); + inspect_legacy_mirrors(tmp.path(), &mut overview); + assert_eq!((overview.total_bytes, overview.unidentified_bytes), (7, 7)); + assert!(overview.workspaces.is_empty() && history.is_file() && chat.is_file()); +} + +#[test] +fn orphan_preview_requires_positive_workspace_ownership_and_rechecks_the_session_under_lock() { + let tmp = tempfile::tempdir().unwrap(); + let scope = scope(tmp.path()); + history(&scope, "gone", 1, &["own", "borrowed"]); + history(&scope, "retained", 1, &["borrowed"]); + let own = handle(&scope, "own", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false); + let borrowed = handle( + &scope, + "borrowed", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + false, + ); + let dir = scope.sessions.join("gone"); + fs::remove_dir_all(&dir).unwrap(); + let preview = plan::Plan::load(&scope, Period::All, None).unwrap(); + let confirmed = vec![preview.candidates["gone"].clone()]; + assert!(confirmed[0].removed); + assert!(preview.candidates.contains_key("retained")); + let history_bytes = fs::metadata(scope.context.snapshot_operations_dir.join("gone.json")) + .unwrap() + .len(); + let reclaimable = history_bytes + own.metadata().unwrap().len(); + for period in [Period::SevenDays, Period::ThirtyDays] { + let preview = plan::Plan::load(&scope, period, None).unwrap(); + assert_eq!( + preview.candidates.into_values().collect::>(), + confirmed + ); + assert_eq!(preview.removed_estimated_bytes, reclaimable); + let rechecked = plan::Plan::load(&scope, period, Some(&confirmed)).unwrap(); + assert_eq!(rechecked.estimate(), reclaimable); + } + let locked = SessionWriteLock::try_acquire(&scope.sessions, "gone").unwrap(); + assert!(plan::Plan::load(&scope, Period::All, Some(&confirmed)) + .unwrap() + .candidates + .is_empty()); + drop(locked); + // An incomplete restore is not proof of deletion, even if its metadata is missing. + fs::create_dir(&dir).unwrap(); + assert!(plan::Plan::load(&scope, Period::All, Some(&confirmed)) + .unwrap() + .candidates + .is_empty()); + history(&scope, "gone", 40, &["own", "borrowed"]); + assert!(plan::Plan::load(&scope, Period::All, Some(&confirmed)) + .unwrap() + .candidates + .is_empty()); + assert!(own.exists() && borrowed.exists()); + let legacy: Candidate = serde_json::from_value(json!({ + "sessionId":"active","name":"Active","activeAt":42,"revision":"42:1" + })) + .unwrap(); + assert!(!legacy.removed); + assert_eq!( + serde_json::from_value::(serde_json::to_value(&legacy).unwrap()).unwrap(), + legacy + ); +} + +#[tokio::test] +async fn pending_deletion_survives_restart_and_another_writer_then_reclaims_only_exclusive_files() { + let tmp = tempfile::tempdir().unwrap(); + let projects = tmp.path().join("projects"); + let workspace = scope(&projects); + let hash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + history(&workspace, "gone", 1, &["own", "shared", "with-base"]); + history(&workspace, "other", 1, &["shared"]); + let own = handle(&workspace, "own", hash, false); + let blob = workspace + .context + .snapshot_by_hash_dir + .join(format!("{hash}.snap")); + fs::write(&blob, b"old").unwrap(); + let base_hash = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let base = handle(&workspace, "baseline_file", base_hash, true); + let with_base = handle(&workspace, "with-base", base_hash, false); + let shared = handle(&workspace, "shared", base_hash, false); + let shared_blob = workspace + .context + .snapshot_by_hash_dir + .join(format!("{base_hash}.snap")); + fs::write(&shared_blob, b"kept").unwrap(); + + let deleting = SessionWriteLock::try_acquire(&workspace.sessions, "gone").unwrap(); + pending::PendingDeletion::prepare(&projects, &workspace, "gone") + .unwrap() + .unwrap(); + let replay = || { + pending::pending_by_store(&projects) + .unwrap() + .into_values() + .next() + .unwrap() + }; + // A second process replaying the intent before deletion commits cannot remove it. + let early = clean_scope( + scope(&projects), + Cleanup::Pending(replay()), + projects.clone(), + ) + .await + .unwrap(); + assert_eq!((early.removed_sessions, early.freed_bytes), (0, 0)); + assert!(own.exists()); + fs::remove_dir_all(workspace.sessions.join("gone")).unwrap(); + drop(deleting); + let writer = WriterLease::register(&workspace.context.locks_dir).unwrap(); + assert!(clean_scope( + scope(&projects), + Cleanup::Pending(replay()), + projects.clone() + ) + .await + .is_err()); + drop(writer); + let expected = plan::Plan::load(&workspace, Period::All, None) + .unwrap() + .removed_estimated_bytes; + let result = clean_scope( + scope(&projects), + Cleanup::Pending(replay()), + projects.clone(), + ) + .await + .unwrap(); + assert!(result.errors.is_empty()); + assert_eq!((result.removed_sessions, result.freed_bytes), (1, expected)); + assert!(pending::pending_by_store(&projects).unwrap().is_empty()); + assert!(!own.exists() && !with_base.exists() && !blob.exists()); + assert!(base.exists() && shared.exists() && shared_blob.exists()); +} + +#[test] +fn orphan_removal_keeps_ownership_until_payload_and_descriptor_removal_complete() { + let tmp = tempfile::tempdir().unwrap(); + let scope = scope(tmp.path()); + let hash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + history(&scope, "gone", 1, &["own"]); + fs::remove_dir_all(scope.sessions.join("gone")).unwrap(); + let own = handle(&scope, "own", hash, false); + let blob = scope + .context + .snapshot_by_hash_dir + .join(format!("{hash}.snap")); + fs::write(&blob, b"payload").unwrap(); + let preview = plan::Plan::load(&scope, Period::ThirtyDays, None).unwrap(); + let confirmed = vec![preview.candidates["gone"].clone()]; + let mut plan = plan::Plan::load(&scope, Period::ThirtyDays, Some(&confirmed)).unwrap(); + let parked = tmp.path().join("parked"); + fs::rename(&own, &parked).unwrap(); // inject failure between unlink stages + let (partial, _) = plan.remove(1); + assert_eq!((partial.removed_sessions, partial.freed_bytes), (0, 7)); + assert!(!partial.errors.is_empty()); + drop(plan); + fs::rename(&parked, &own).unwrap(); + let retry = plan::Plan::load(&scope, Period::ThirtyDays, Some(&confirmed)) + .unwrap() + .remove(1) + .0; + assert_eq!(retry.removed_sessions, 1); + assert!(retry.errors.is_empty()); + assert_eq!(partial.freed_bytes + retry.freed_bytes, preview.estimate()); +} + +#[test] +fn unverifiable_checkpoint_keeps_orphan_history_for_a_future_retry() { + let tmp = tempfile::tempdir().unwrap(); + let scope = scope(tmp.path()); + history(&scope, "gone", 1, &["own"]); + let own = handle(&scope, "own", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false); + fs::remove_dir_all(scope.sessions.join("gone")).unwrap(); + let confirmed = plan::Plan::load(&scope, Period::All, None) + .unwrap() + .candidates + .into_values() + .collect::>(); + fs::create_dir(scope.sessions.join("undo")).unwrap(); + fs::write(scope.sessions.join("undo/session-revert.json"), b"{").unwrap(); + let plan = plan::Plan::load(&scope, Period::All, Some(&confirmed)).unwrap(); + assert!(plan.unverified_references && plan.candidates.is_empty()); + assert_eq!((plan.estimate(), plan.removed_estimated_bytes), (0, 0)); + assert!( + own.exists() + && scope + .context + .snapshot_operations_dir + .join("gone.json") + .exists() + ); +} + +#[test] +fn deletion_intents_stay_with_their_ssh_profile_after_a_workspace_rebind() { + use openbitfun_services_core::workspace_identity::WorkspaceSessionIdentity; + let tmp = tempfile::tempdir().unwrap(); + let projects = tmp.path().join("projects"); + let profile = |connection: &str| { + let mut workspace = scope(&projects); + let identity = WorkspaceSessionIdentity { + workspace_kind: openbitfun_core_types::WorkspaceKind::Remote, + hostname: "server".into(), + logical_workspace_path: "/work".into(), + remote_connection_id: Some(connection.into()), + }; + let runtime = WorkspaceRuntimeContext::new( + WorkspaceRuntimeTarget::RemoteWorkspaceMirror { + ssh_host: identity.identity_host(), + remote_root: "/work".into(), + }, + projects.join("mirror"), + ); + workspace.context = bound_snapshot_context(&identity, runtime).unwrap(); + workspace.remote = true; + workspace.sessions = workspace.context.sessions_dir.clone(); + for dir in workspace.context.required_directories() { + fs::create_dir_all(dir).unwrap(); + } + history(&workspace, "same-id", 1, &[]); + pending::PendingDeletion::prepare(&projects, &workspace, "same-id") + .unwrap() + .unwrap(); + workspace + }; + let first = profile("profile-a"); + let second = profile("profile-b"); + assert_eq!(pending::pending_by_store(&projects).unwrap().len(), 2); + fs::remove_file(first.context.snapshot_operations_dir.join("same-id.json")).unwrap(); + pending::acknowledge(&projects, &first, std::iter::once("same-id")).unwrap(); + assert_eq!(pending::pending_by_store(&projects).unwrap().len(), 1); + assert!(second + .context + .snapshot_operations_dir + .join("same-id.json") + .is_file()); +} diff --git a/src/crates/assembly/core/src/service/snapshot/maintenance/writer_lease.rs b/src/crates/assembly/core/src/service/snapshot/maintenance/writer_lease.rs new file mode 100644 index 0000000000..a1fb3c74b9 --- /dev/null +++ b/src/crates/assembly/core/src/service/snapshot/maintenance/writer_lease.rs @@ -0,0 +1,105 @@ +//! Writers cache the reference index. Cleanup can update the local writer +//! under its service lock, but must wait until any other writer has closed. +use super::{entries, invalid, SnapshotResult}; +use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + path::{Path, PathBuf}, +}; + +/// A view in another process may outlive a cleanup. Capture the version +/// before loading its index. Views opened during removal are never cached. +pub(in crate::service::snapshot) struct ViewStamp { + path: PathBuf, + version: Option<[u8; 16]>, +} + +impl ViewStamp { + pub(in crate::service::snapshot) fn capture(locks: &Path) -> Self { + let path = locks.join("snapshot-writers/maintenance.lock"); + let version = Self::read(&path); + Self { path, version } + } + + pub(in crate::service::snapshot) fn current(&self) -> bool { + self.version.is_some() && self.version == Self::read(&self.path) + } + + fn read(path: &Path) -> Option<[u8; 16]> { + let mut file = match File::open(path) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some([0; 16]), + Err(_) => return None, + }; + file.try_lock_shared().ok()?; + let mut version = [0; 16]; + if file.metadata().ok()?.len() > 0 { + file.read_exact(&mut version).ok()?; + } + Some(version) + } +} + +fn gate(locks: &Path) -> SnapshotResult<(File, PathBuf)> { + let dir = locks.join("snapshot-writers"); + fs::create_dir_all(&dir)?; + super::checked_path(locks, &dir.join("maintenance.lock"))?; + let gate = OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(dir.join("maintenance.lock"))?; + Ok((gate, dir)) +} + +pub(crate) struct WriterLease { + _file: File, + path: PathBuf, +} + +impl WriterLease { + pub(in crate::service::snapshot) fn register(locks: &Path) -> SnapshotResult { + let (gate, dir) = gate(locks)?; + gate.lock_shared()?; + let path = dir.join(format!("{}.writer", uuid::Uuid::new_v4())); + let file = OpenOptions::new() + .create_new(true) + .read(true) + .write(true) + .open(&path)?; + file.try_lock().map_err(invalid)?; + Ok(Self { _file: file, path }) + } +} + +impl Drop for WriterLease { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +pub(super) fn exclusive(locks: &Path, own: Option<&WriterLease>) -> SnapshotResult { + let (mut gate, dir) = gate(locks)?; + gate.try_lock().map_err(invalid)?; + for entry in entries(&dir)? { + let path = entry.path(); + if path.extension().is_none_or(|e| e != "writer") || own.is_some_and(|w| w.path == path) { + continue; + } + if !entry.file_type()?.is_file() { + return Err(invalid("Invalid snapshot writer lease")); + } + let file = match OpenOptions::new().read(true).write(true).open(&path) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => return Err(e.into()), + }; + file.try_lock() + .map_err(|_| invalid("Snapshot store is in use by another writer"))?; + drop(file); + fs::remove_file(path)?; + } + gate.write_all(uuid::Uuid::new_v4().as_bytes())?; + Ok(gate) +} diff --git a/src/crates/assembly/core/src/service/snapshot/manager.rs b/src/crates/assembly/core/src/service/snapshot/manager.rs index 1c57c550df..8d8606abba 100644 --- a/src/crates/assembly/core/src/service/snapshot/manager.rs +++ b/src/crates/assembly/core/src/service/snapshot/manager.rs @@ -31,6 +31,7 @@ use std::time::Duration; /// /// Manages all components of the snapshot system. pub struct SnapshotManager { + view_stamp: Option, snapshot_service: Arc>, } @@ -55,7 +56,10 @@ impl SnapshotManager { let mut snapshot_service = SnapshotService::new(workspace_dir, runtime_context, config); snapshot_service.initialize().await?; let snapshot_service = Arc::new(RwLock::new(snapshot_service)); - Ok(Self { snapshot_service }) + Ok(Self { + snapshot_service, + view_stamp: None, + }) } /// Records a file change. @@ -510,6 +514,44 @@ async fn snapshot_manager_init_lock(workspace_id: &str) -> Arc> { .clone() } +/// Hold the same initialization lock used by view/writer registration until disk and +/// in-memory indexes agree. A cold cleanup never constructs a snapshot manager. +pub(super) async fn maintenance_manager( + workspace_id: &str, + remote: bool, +) -> ( + tokio::sync::OwnedMutexGuard<()>, + Option>, +) { + if remote { + let key = BoundSnapshotKey { + workspace_id: workspace_id.to_owned(), + }; + let lock = bound_snapshot_init_locks() + .lock() + .await + .entry(key.clone()) + .or_default() + .clone(); + let guard = lock.lock_owned().await; + let managers = bound_snapshot_managers().lock().await; + let manager = managers + .writers + .get(&key) + .cloned() + .or_else(|| managers.views.get(&key).map(|v| v.0.clone())); + (guard, manager) + } else { + let guard = snapshot_manager_init_lock(workspace_id) + .await + .lock_owned() + .await; + let manager = get_snapshot_manager_for_workspace(workspace_id) + .or_else(|| get_snapshot_view_manager_for_workspace(workspace_id)); + (guard, manager) + } +} + fn canonical_snapshot_io_path(workspace_dir: &Path) -> PathBuf { dunce::canonicalize(workspace_dir).unwrap_or_else(|_| workspace_dir.to_path_buf()) } @@ -539,7 +581,7 @@ fn bound_snapshot_init_locks() -> &'static AsyncMutex SnapshotResult { @@ -688,7 +730,9 @@ async fn open_bound_snapshot_manager( } if read_only { if let Some((existing, has_filesystem)) = managers.views.get(&key) { - if *has_filesystem || workspace_fs.is_none() { + if (*has_filesystem || workspace_fs.is_none()) + && existing.view_stamp.as_ref().is_some_and(|s| s.current()) + { return Ok(existing.clone()); } } @@ -706,6 +750,8 @@ async fn open_bound_snapshot_manager( tokio::fs::create_dir_all(directory).await?; } } + let view_stamp = + read_only.then(|| super::maintenance::ViewStamp::capture(&runtime_context.locks_dir)); let has_filesystem = workspace_fs.is_some(); let mut service = match workspace_fs { Some(fs) => SnapshotService::with_workspace_fs( @@ -726,6 +772,7 @@ async fn open_bound_snapshot_manager( service.initialize().await?; } let manager = Arc::new(SnapshotManager { + view_stamp, snapshot_service: Arc::new(RwLock::new(service)), }); let mut managers = bound_snapshot_managers().lock().await; @@ -1402,9 +1449,13 @@ pub async fn open_snapshot_manager_for_view( let started_at = Instant::now(); let runtime_context = get_workspace_runtime_service_arc().context_for_local_workspace(&workspace_dir); + let view_stamp = Some(super::maintenance::ViewStamp::capture( + &runtime_context.locks_dir, + )); let mut snapshot_service = SnapshotService::new(workspace_dir.clone(), runtime_context, None); snapshot_service.initialize_for_view().await?; let view = Arc::new(SnapshotManager { + view_stamp, snapshot_service: Arc::new(RwLock::new(snapshot_service)), }); if let Ok(mut views) = snapshot_view_managers().write() { @@ -1423,6 +1474,7 @@ fn get_snapshot_view_manager_for_workspace(workspace_key: &str) -> Option>, file_lock_manager: Arc, - snapshot_core: Arc>, + pub(super) writer_lease: Option, + pub(super) snapshot_core: Arc>, workspace_dir: PathBuf, runtime_context: WorkspaceRuntimeContext, workspace_fs: Option>, @@ -71,6 +72,7 @@ impl SnapshotService { config, isolation_manager, file_lock_manager, + writer_lease: None, snapshot_core, workspace_dir, runtime_context, @@ -85,6 +87,12 @@ impl SnapshotService { return Ok(()); } + let locks = self.runtime_context.locks_dir.clone(); + self.writer_lease = Some( + tokio::task::spawn_blocking(move || super::maintenance::WriterLease::register(&locks)) + .await + .map_err(|e| SnapshotError::ConfigError(e.to_string()))??, + ); let total_started_at = Instant::now(); info!("Initializing snapshot/operation history service"); @@ -464,6 +472,10 @@ impl SnapshotService { let mut snapshot_core = self.snapshot_core.write().await; snapshot_core.cleanup_session(session_id).await?; + self.release_session_file_locks(session_id).await + } + + pub(crate) async fn release_session_file_locks(&self, session_id: &str) -> SnapshotResult<()> { let released_count = self .file_lock_manager .release_session_locks(session_id) diff --git a/src/crates/assembly/core/src/service/snapshot/snapshot_core.rs b/src/crates/assembly/core/src/service/snapshot/snapshot_core.rs index 3af33cbff6..e44ce7e8bc 100644 --- a/src/crates/assembly/core/src/service/snapshot/snapshot_core.rs +++ b/src/crates/assembly/core/src/service/snapshot/snapshot_core.rs @@ -1311,6 +1311,12 @@ impl SnapshotCore { self.sessions_dir.join(format!("{}.json", safe)) } + pub(super) fn forget_cleaned_history(&mut self, removed: &super::maintenance::Removed) { + self.sessions.retain(|id, _| !removed.sessions.contains(id)); + self.snapshot_system.forget_cleaned_files(removed); + self.rebuild_operation_index(); + } + fn rebuild_operation_index(&mut self) { self.operation_index.clear(); for (session_id, session) in &self.sessions { @@ -1412,7 +1418,7 @@ fn change_kind_from_session_boundary(boundary: &SessionFileBoundary) -> &'static } } -fn sanitize_id(id: &str) -> String { +pub(super) fn sanitize_id(id: &str) -> String { id.chars() .map(|c| { if c.is_ascii_alphanumeric() || c == '-' || c == '_' { diff --git a/src/crates/assembly/core/src/service/snapshot/snapshot_system.rs b/src/crates/assembly/core/src/service/snapshot/snapshot_system.rs index d0a11f2ae1..e8fcf03aaf 100644 --- a/src/crates/assembly/core/src/service/snapshot/snapshot_system.rs +++ b/src/crates/assembly/core/src/service/snapshot/snapshot_system.rs @@ -974,6 +974,13 @@ impl FileSnapshotSystem { Ok(()) } + pub(super) fn forget_cleaned_files(&mut self, removed: &super::maintenance::Removed) { + self.active_snapshots + .retain(|id, _| !removed.handles.contains(id)); + self.hash_to_path + .retain(|hash, _| !removed.blobs.contains(hash)); + } + /// Returns storage statistics. pub async fn get_storage_stats(&self) -> SnapshotResult { let mut total_size_bytes = 0; diff --git a/src/crates/assembly/core/src/service/workspace/service.rs b/src/crates/assembly/core/src/service/workspace/service.rs index 21ea7af00c..c22a138247 100644 --- a/src/crates/assembly/core/src/service/workspace/service.rs +++ b/src/crates/assembly/core/src/service/workspace/service.rs @@ -2546,8 +2546,22 @@ static GLOBAL_WORKSPACE_SERVICE: std::sync::OnceLock> = std::sync::OnceLock::new(); pub fn set_global_workspace_service(service: Arc) { + #[cfg(feature = "agent-runtime")] + let paths = service.path_manager.clone(); match GLOBAL_WORKSPACE_SERVICE.set(service) { - Ok(_) => info!("Global workspace service set"), + Ok(_) => { + info!("Global workspace service set"); + #[cfg(feature = "agent-runtime")] + if let Ok(runtime) = tokio::runtime::Handle::try_current() { + runtime.spawn(async move { + if let Err(e) = + crate::service::snapshot::maintenance::retry_pending_deletions(&paths).await + { + warn!("Could not resume pending snapshot deletions: {e}"); + } + }); + } + } Err(_) => info!("Global workspace service already exists, skipping set"), } } diff --git a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json index eeb6df7133..44fd066c5f 100644 --- a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json +++ b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", + "digest": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -185,13 +185,13 @@ ], "counts": { "features": 24, - "settings": 23, - "userFacing": 47, - "documentedItems": 368, + "settings": 24, + "userFacing": 48, + "documentedItems": 369, "controlCoverage": { "direct": 63, "delegated": 74, - "interactive": 231, + "interactive": 232, "unsupported": 0 } }, @@ -21371,6 +21371,97 @@ "pageId": "data.usage" } }, + { + "id": "setting.data.storage:query", + "capabilityId": "setting.data.storage", + "itemIds": [ + "clean" + ], + "kind": "query", + "risk": "read", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "static" + }, + "presentationTarget": { + "kind": "settings", + "pageId": "data.storage" + } + }, + { + "id": "setting.data.storage:open:clean", + "capabilityId": "setting.data.storage", + "itemIds": [ + "clean" + ], + "kind": "open", + "risk": "ui", + "executionHost": "presentationSurface", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "product_control_presentation_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "openReason": "unstructuredInteraction", + "presentationTarget": { + "kind": "settings", + "pageId": "data.storage" + } + }, { "id": "setting.data.archived:query", "capabilityId": "setting.data.archived", @@ -35583,6 +35674,79 @@ ], "docsUrl": "https://playbook.openbitfun.com/capabilities/setting.data.usage/" }, + { + "id": "setting.data.storage", + "kind": "setting", + "categoryId": "data", + "titleZh": "存储空间", + "titleEn": "Storage", + "summaryZh": "按工作区查看本机文件快照占用,手动清理符合条件的会话。", + "summaryEn": "Inspect local file snapshot usage by workspace and clean up eligible session histories.", + "keywordsZh": [ + "存储空间", + "快照清理" + ], + "keywordsEn": [ + "storage", + "snapshot cleanup" + ], + "highlightsZh": [ + "查看每个工作区的快照占用及共享文件大小。" + ], + "highlightsEn": [ + "See snapshot usage and shared file sizes for each workspace." + ], + "items": [ + { + "id": "clean", + "titleZh": "预览并清理会话文件快照", + "titleEn": "Preview and clean up session file snapshots", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“预览并清理会话文件快照”会永久移除所选会话的文件回退记录,请在存储空间页面核对并确认。", + "reasonEn": "“Preview and clean up session file snapshots” opens Storage so you can review the affected sessions before permanently removing their file rollback history." + } + } + ], + "stepsZh": [ + "打开存储空间,选择工作区和清理范围。", + "核对预览并确认删除文件快照。" + ], + "stepsEn": [ + "Open Storage and select the workspaces and inactivity period.", + "Review the preview and confirm deletion of file snapshots." + ], + "agentExamplesZh": [ + "打开快照存储设置" + ], + "agentExamplesEn": [ + "Open snapshot storage settings" + ], + "destination": { + "kind": "settings", + "pageId": "data.storage" + }, + "operations": [], + "options": [], + "searchTerms": [ + "setting.data.storage", + "存储空间", + "Storage", + "数据与诊断", + "Data & diagnostics", + "快照清理", + "storage", + "snapshot cleanup", + "查看每个工作区的快照占用及共享文件大小。", + "See snapshot usage and shared file sizes for each workspace.", + "预览并清理会话文件快照", + "Preview and clean up session file snapshots", + "打开快照存储设置", + "Open snapshot storage settings" + ], + "docsUrl": "https://playbook.openbitfun.com/capabilities/setting.data.storage/" + }, { "id": "setting.data.archived", "kind": "setting", 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 5422bad462..eebd85b083 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:0b686be0f5103ef5", + "digest": "fnv1a64:90361f729e6ce746", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -944,6 +944,18 @@ "kind": "handled" } }, + { + "id": "clean_snapshot_storage", + "surface": "tauri_command", + "remoteWorkspace": "WorkspaceAgnostic", + "peer": { + "kind": "controller_local" + }, + "cliPeer": { + "kind": "unsupported", + "reason": "the controller keeps this command; peer hosts refuse it before dispatch" + } + }, { "id": "cleanup_invalid_workspaces", "surface": "tauri_command", @@ -4101,6 +4113,18 @@ "kind": "handled" } }, + { + "id": "inspect_snapshot_storage", + "surface": "tauri_command", + "remoteWorkspace": "WorkspaceAgnostic", + "peer": { + "kind": "controller_local" + }, + "cliPeer": { + "kind": "unsupported", + "reason": "the controller keeps this command; peer hosts refuse it before dispatch" + } + }, { "id": "install_acp_client_cli", "surface": "tauri_command", 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 d3ab0224a2..ff1307a2cc 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -163,6 +163,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("check_path_exists", Routed, Proxied, HANDLED), op("choose_external_mcp_conflict_command", Unsupported, Proxied, HANDLED), op("choose_external_subagent_conflict_command", Unsupported, Proxied, HANDLED), + op("clean_snapshot_storage", Agnostic, ControllerLocal, REFUSED), op("cleanup_invalid_workspaces", Unaudited, Proxied, HANDLED), op("clear_decision_model_credential", Agnostic, Proxied, HANDLED), op("clear_mcp_remote_auth", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), @@ -438,6 +439,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("initialize_mcp_servers_non_destructive", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("initialize_tray_after_startup", LocalOnly, ControllerLocal, REFUSED), op("initialize_workspace_startup_state", Routed, Proxied, HANDLED), + op("inspect_snapshot_storage", Agnostic, ControllerLocal, REFUSED), op("install_acp_client_cli", Unaudited, Proxied, CLI_NO_ACP_CLIENT_HOST), op("install_pending_update", Agnostic, ControllerLocal, REFUSED), op("install_update", Agnostic, ControllerLocal, REFUSED), diff --git a/src/crates/services/services-core/src/session/write_lock.rs b/src/crates/services/services-core/src/session/write_lock.rs index 022c173eb5..82ccd87250 100644 --- a/src/crates/services/services-core/src/session/write_lock.rs +++ b/src/crates/services/services-core/src/session/write_lock.rs @@ -16,6 +16,7 @@ pub struct SessionWriteLock { struct SessionWriteLockInner { lock: Option, lock_path: PathBuf, + maintenance: bool, } impl SessionWriteLock { @@ -23,7 +24,45 @@ impl SessionWriteLock { session_storage_root: &Path, session_id: &str, ) -> Result { - Self::acquire(session_storage_root, session_id, false) + Self::acquire(session_storage_root, session_id, false, false) + } + + /// Inspect ownership without creating a lock file or a Session directory. + /// This is a preview only. A mutation must still acquire the writer lock. + pub fn is_in_use( + session_storage_root: &Path, + session_id: &str, + ) -> Result { + openbitfun_core_types::validate_session_id(session_id) + .map_err(|_| SessionWriteLockError::InvalidSessionId)?; + let root = std::fs::canonicalize(session_storage_root).map_err(|source| { + SessionWriteLockError::CanonicalizeStorage { + path: session_storage_root.to_owned(), + source, + } + })?; + let path = session_lock_root(&root)?.join(format!("{}.lock", lock_key(&root, session_id))); + let file = match std::fs::File::open(&path) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(source) => return Err(SessionWriteLockError::OpenLockFile { path, source }), + }; + match file.try_lock_shared() { + Ok(()) => Ok(false), + Err(std::fs::TryLockError::WouldBlock) => Ok(true), + Err(std::fs::TryLockError::Error(source)) => { + Err(SessionWriteLockError::LockFailed { source }) + } + } + } + + /// Prevent even same-process persistence operations from borrowing this + /// guard while maintenance is revalidating and removing session history. + pub fn try_acquire_for_maintenance( + session_storage_root: &Path, + session_id: &str, + ) -> Result { + Self::acquire(session_storage_root, session_id, false, true) } /// Reuses a lock already held by this process for one persistence operation. @@ -33,13 +72,14 @@ impl SessionWriteLock { session_storage_root: &Path, session_id: &str, ) -> Result { - Self::acquire(session_storage_root, session_id, true) + Self::acquire(session_storage_root, session_id, true, false) } fn acquire( session_storage_root: &Path, session_id: &str, reuse_process_writer: bool, + maintenance: bool, ) -> Result { openbitfun_core_types::validate_session_id(session_id) .map_err(|_| SessionWriteLockError::InvalidSessionId)?; @@ -77,7 +117,7 @@ impl SessionWriteLock { .lock() .expect("Session write lock registry poisoned"); if let Some(existing) = process_locks.get(&lock_path).and_then(Weak::upgrade) { - if reuse_process_writer { + if reuse_process_writer && !existing.maintenance { return Ok(Self { inner: existing }); } return Err(SessionWriteLockError::InUse); @@ -99,6 +139,7 @@ impl SessionWriteLock { )?; let inner = Arc::new(SessionWriteLockInner { lock: Some(lock), + maintenance, lock_path: lock_path.clone(), }); process_locks.insert(lock_path, Arc::downgrade(&inner)); diff --git a/src/crates/services/services-core/tests/session_write_lock_contracts.rs b/src/crates/services/services-core/tests/session_write_lock_contracts.rs index 5cfd252804..fa4f36133b 100644 --- a/src/crates/services/services-core/tests/session_write_lock_contracts.rs +++ b/src/crates/services/services-core/tests/session_write_lock_contracts.rs @@ -200,3 +200,17 @@ fn abnormal_exit_child_holds_writer() { std::thread::park(); } } + +#[test] +fn preview_is_read_only_and_maintenance_excludes_same_process_operations() { + let root = tempfile::tempdir().unwrap(); + let sessions = root.path().join("sessions"); + std::fs::create_dir(&sessions).unwrap(); + assert!(!SessionWriteLock::is_in_use(&sessions, "old").unwrap()); + assert!(!root.path().join(".session-write-locks").exists()); + let maintenance = SessionWriteLock::try_acquire_for_maintenance(&sessions, "old").unwrap(); + assert!(SessionWriteLock::is_in_use(&sessions, "old").unwrap()); + assert!(SessionWriteLock::try_acquire_for_operation(&sessions, "old").is_err()); + drop(maintenance); + assert!(!SessionWriteLock::is_in_use(&sessions, "old").unwrap()); +} diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 178bb4af35..020f04ec9f 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -13063,6 +13063,75 @@ "operations": [], "options": [] }, + { + "id": "setting.data.storage", + "kind": "setting", + "categoryId": "data", + "directoryGroupId": "settings-data", + "order": 53, + "entryPathZh": "设置 → 数据与维护 → 存储空间", + "entryPathEn": "Settings → Data & Maintenance → Storage", + "titleZh": "存储空间", + "titleEn": "Storage", + "summaryZh": "按工作区查看本机文件快照占用,手动清理符合条件的会话。", + "summaryEn": "Inspect local file snapshot usage by workspace and clean up eligible session histories.", + "keywordsZh": [ + "存储空间", + "快照清理" + ], + "keywordsEn": [ + "storage", + "snapshot cleanup" + ], + "highlightsZh": [ + "查看每个工作区的快照占用及共享文件大小。" + ], + "highlightsEn": [ + "See snapshot usage and shared file sizes for each workspace." + ], + "items": [ + { + "id": "clean", + "titleZh": "预览并清理会话文件快照", + "titleEn": "Preview and clean up session file snapshots", + "descriptionZh": "选择工作区和未活跃时长,核对会话及预计释放空间后确认清理。", + "descriptionEn": "Choose workspaces and an inactivity period, review the affected sessions and estimated space, then confirm cleanup.", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“预览并清理会话文件快照”会永久移除所选会话的文件回退记录,请在存储空间页面核对并确认。", + "reasonEn": "“Preview and clean up session file snapshots” opens Storage so you can review the affected sessions before permanently removing their file rollback history." + }, + "evidence": [ + "command:inspect_snapshot_storage", + "command:clean_snapshot_storage" + ] + } + ], + "stepsZh": [ + "打开存储空间,选择工作区和清理范围。", + "核对预览并确认删除文件快照。" + ], + "stepsEn": [ + "Open Storage and select the workspaces and inactivity period.", + "Review the preview and confirm deletion of file snapshots." + ], + "agentExamplesZh": [ + "打开快照存储设置" + ], + "agentExamplesEn": [ + "Open snapshot storage settings" + ], + "relatedIds": [ + "setting.data.archived" + ], + "destination": { + "kind": "settings", + "pageId": "data.storage" + }, + "operations": [], + "options": [] + }, { "id": "setting.data.archived", "kind": "setting", diff --git a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json index fd428d4e10..d27a072188 100644 --- a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json +++ b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5", + "digest": "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294", "ownerDigest": "6f0746578f3c56479f7c289bb05395dfe6917042f4d419de8c9a2f719d31f815", "searchAcceptance": [ { @@ -185,13 +185,13 @@ ], "counts": { "features": 24, - "settings": 23, - "userFacing": 47, - "documentedItems": 368, + "settings": 24, + "userFacing": 48, + "documentedItems": 369, "controlCoverage": { "direct": 63, "delegated": 74, - "interactive": 231, + "interactive": 232, "unsupported": 0 } }, @@ -21371,6 +21371,97 @@ "pageId": "data.usage" } }, + { + "id": "setting.data.storage:query", + "capabilityId": "setting.data.storage", + "itemIds": [ + "clean" + ], + "kind": "query", + "risk": "read", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "static" + }, + "presentationTarget": { + "kind": "settings", + "pageId": "data.storage" + } + }, + { + "id": "setting.data.storage:open:clean", + "capabilityId": "setting.data.storage", + "itemIds": [ + "clean" + ], + "kind": "open", + "risk": "ui", + "executionHost": "presentationSurface", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1", + "product_control_presentation_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": false, + "reason": "This delivery profile has no live presentation surface" + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": false + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "openReason": "unstructuredInteraction", + "presentationTarget": { + "kind": "settings", + "pageId": "data.storage" + } + }, { "id": "setting.data.archived:query", "capabilityId": "setting.data.archived", @@ -35081,6 +35172,79 @@ ], "docsUrl": "https://playbook.openbitfun.com/capabilities/setting.data.usage/" }, + { + "id": "setting.data.storage", + "kind": "setting", + "categoryId": "data", + "titleZh": "存储空间", + "titleEn": "Storage", + "summaryZh": "按工作区查看本机文件快照占用,手动清理符合条件的会话。", + "summaryEn": "Inspect local file snapshot usage by workspace and clean up eligible session histories.", + "keywordsZh": [ + "存储空间", + "快照清理" + ], + "keywordsEn": [ + "storage", + "snapshot cleanup" + ], + "highlightsZh": [ + "查看每个工作区的快照占用及共享文件大小。" + ], + "highlightsEn": [ + "See snapshot usage and shared file sizes for each workspace." + ], + "items": [ + { + "id": "clean", + "titleZh": "预览并清理会话文件快照", + "titleEn": "Preview and clean up session file snapshots", + "control": { + "kind": "open", + "reasonCode": "unstructuredInteraction", + "reasonZh": "“预览并清理会话文件快照”会永久移除所选会话的文件回退记录,请在存储空间页面核对并确认。", + "reasonEn": "“Preview and clean up session file snapshots” opens Storage so you can review the affected sessions before permanently removing their file rollback history." + } + } + ], + "stepsZh": [ + "打开存储空间,选择工作区和清理范围。", + "核对预览并确认删除文件快照。" + ], + "stepsEn": [ + "Open Storage and select the workspaces and inactivity period.", + "Review the preview and confirm deletion of file snapshots." + ], + "agentExamplesZh": [ + "打开快照存储设置" + ], + "agentExamplesEn": [ + "Open snapshot storage settings" + ], + "destination": { + "kind": "settings", + "pageId": "data.storage" + }, + "operations": [], + "options": [], + "searchTerms": [ + "setting.data.storage", + "存储空间", + "Storage", + "数据与诊断", + "Data & diagnostics", + "快照清理", + "storage", + "snapshot cleanup", + "查看每个工作区的快照占用及共享文件大小。", + "See snapshot usage and shared file sizes for each workspace.", + "预览并清理会话文件快照", + "Preview and clean up session file snapshots", + "打开快照存储设置", + "Open snapshot storage settings" + ], + "docsUrl": "https://playbook.openbitfun.com/capabilities/setting.data.storage/" + }, { "id": "setting.data.archived", "kind": "setting", diff --git a/src/web-ui/src/app/scenes/settings/appearance.ts b/src/web-ui/src/app/scenes/settings/appearance.ts index bdfd23d3d2..5d8eb435e7 100644 --- a/src/web-ui/src/app/scenes/settings/appearance.ts +++ b/src/web-ui/src/app/scenes/settings/appearance.ts @@ -28,6 +28,7 @@ export const settingsAppearanceDescriptor: AppearanceSurfaceDescriptor = { 'tools.external-agents', 'tools.automation', 'data.usage', + 'data.storage', 'data.archived', 'data.diagnostics', ], diff --git a/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.appearance.ts b/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.appearance.ts new file mode 100644 index 0000000000..f6ada3f903 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.appearance.ts @@ -0,0 +1,9 @@ +import type { AppearanceSurfaceDescriptor } from '@/infrastructure/appearance/types'; + +export const snapshotStorageAppearanceDescriptor: AppearanceSurfaceDescriptor = { + id: 'snapshot-storage', + parts: [ + { id: 'root' }, { id: 'panel' }, { id: 'total' }, { id: 'workspaceList' }, + { id: 'filters' }, { id: 'candidateList' }, { id: 'session' }, { id: 'reviewFooter' }, + ], +}; diff --git a/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.module.scss b/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.module.scss new file mode 100644 index 0000000000..8fa23a46fe --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.module.scss @@ -0,0 +1,172 @@ +.panel { + min-inline-size: 0; + container-type: inline-size; + color: var(--openbitfun-color-content-primary); + font-size: var(--openbitfun-type-body-sm-font-size); + line-height: var(--openbitfun-type-body-sm-line-height); + font-variant-numeric: tabular-nums; + border: 1px solid var(--openbitfun-color-border-subtle); + border-radius: var(--openbitfun-radius-md); +} + +.total, .filters, .reviewFooter { padding: var(--openbitfun-space-4); } + +.total { + display: flex; + align-items: baseline; + gap: var(--openbitfun-space-3); + color: var(--openbitfun-color-content-secondary); + + strong { + font-size: var(--openbitfun-type-heading-section-font-size); + font-weight: var(--openbitfun-type-heading-section-font-weight); + color: var(--openbitfun-color-content-primary); + } +} + +.workspaceScroll, .candidateScroll { + overflow: auto; + min-inline-size: 0; + border-block-start: 1px solid var(--openbitfun-color-border-subtle); + + &:focus-visible { + outline: var(--openbitfun-focus-width) solid var(--openbitfun-color-focus-ring); + outline-offset: calc(-1 * var(--openbitfun-focus-width)); + } +} + +.workspaceScroll { + max-block-size: min(20rem, 40vh); + border-end-start-radius: inherit; + border-end-end-radius: inherit; +} + +.table { + inline-size: 100%; + table-layout: fixed; + border-spacing: 0; + text-align: start; + + th, td { + text-align: end; + padding: var(--openbitfun-space-2) var(--openbitfun-space-4); + } + th:first-child { text-align: start; } + thead th { position: sticky; inset-block-start: 0; z-index: 1; } + thead th:nth-child(2) { width: 25%; } + thead th:last-child { width: 24%; } + tbody tr:not(:first-child) > * { border-block-start: 1px solid var(--openbitfun-color-border-subtle); } + tbody th { background: transparent; } + td { color: var(--openbitfun-color-content-secondary); white-space: nowrap; } +} + +.table thead th, .listHeader { + background: var(--openbitfun-color-surface-panel); + color: var(--openbitfun-color-content-secondary); + border-block-end: 1px solid var(--openbitfun-color-border-subtle); + font-weight: var(--openbitfun-type-label-md-font-weight); + font-size: var(--openbitfun-type-meta-font-size); + line-height: var(--openbitfun-type-meta-line-height); +} + +.workspaceName, .location { + display: block; + max-inline-size: 100%; +} +.workspaceName, .usage strong, .reviewFooter strong { + color: var(--openbitfun-color-content-primary); + font-weight: var(--openbitfun-type-label-selected-font-weight); +} +.location, .groupCount, .sessionRow time, .reviewFooter p { + color: var(--openbitfun-color-content-muted); + font-size: var(--openbitfun-type-meta-font-size); + font-weight: var(--openbitfun-type-body-sm-font-weight); +} +.location { overflow-wrap: anywhere; } + +.usage { + display: grid; + justify-items: end; + gap: var(--openbitfun-space-1); +} +.track { + inline-size: min(100%, 5rem); + block-size: 3px; + overflow: hidden; + border-radius: var(--openbitfun-radius-base); + background: var(--openbitfun-color-border-subtle); + + span { display: block; block-size: 100%; background: var(--openbitfun-color-accent-default); } +} + +.filters { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--openbitfun-space-3); +} +.field { + display: grid; + min-inline-size: 0; + gap: var(--openbitfun-space-1); + color: var(--openbitfun-color-content-secondary); + font-size: var(--openbitfun-type-label-sm-font-size); +} + +.candidateScroll { max-block-size: min(22rem, 44vh); } +.listHeader { + position: sticky; + inset-block-start: 0; + z-index: 1; + display: flex; + justify-content: space-between; + padding: var(--openbitfun-space-2) var(--openbitfun-space-4); +} +.groupTrigger { + padding: var(--openbitfun-space-2) var(--openbitfun-space-4); + min-block-size: 2.25rem; +} +.groupCount { padding-inline-end: var(--openbitfun-space-2); white-space: nowrap; } +.groupBody { padding-inline: var(--openbitfun-space-4); } +.sessions { + margin: 0; + margin-inline-start: var(--openbitfun-space-2); + padding: 0; + list-style: none; + border-inline-start: 1px solid var(--openbitfun-color-border-subtle); +} +.sessionRow { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--openbitfun-space-3); + align-items: baseline; + padding: var(--openbitfun-space-1) 0 var(--openbitfun-space-1) var(--openbitfun-space-4); +} +.sessionTitle { overflow-wrap: anywhere; } +.sessionRow time { white-space: nowrap; } +.reviewFooter { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--openbitfun-space-3); + border-block-start: 1px solid var(--openbitfun-color-border-subtle); + + > div { flex: 1 1 16rem; } + p { margin: var(--openbitfun-space-1) 0 0; } +} + +@container (max-width: 26rem) { + .filters { grid-template-columns: minmax(0, 1fr); } + .table th, .table td { padding-inline: var(--openbitfun-space-2); } + .table thead th:nth-child(2), .table thead th:last-child { width: 5.25rem; } + .sessionRow { column-gap: var(--openbitfun-space-2); } +} + +@container (max-width: 20rem) { + .listHeader > :last-child { display: none; } + .sessionRow { + grid-template-columns: minmax(0, 1fr); + row-gap: 0; + padding-block: var(--openbitfun-space-2); + } +} diff --git a/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.test.tsx b/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.test.tsx new file mode 100644 index 0000000000..c0f0260a31 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.test.tsx @@ -0,0 +1,114 @@ +// @vitest-environment jsdom +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { beforeEach, afterEach, expect, it, vi } from 'vitest'; +import { PEER_CONTROLLER_LOCAL_COMMANDS } from '@/infrastructure/api/generated/remoteSurface'; +import StorageSettingsPage from './StorageSettingsPage'; + +const mocks = vi.hoisted(() => ({ inspect: vi.fn(), clean: vi.fn(), confirm: vi.fn(), desktop: true })); +vi.mock('@/infrastructure/api/service-api/SnapshotStorageAPI', () => ({ snapshotStorageAPI: mocks })); +vi.mock('@/infrastructure/confirm-dialog', () => ({ confirmDanger: mocks.confirm })); +vi.mock('@/infrastructure/runtime', () => ({ isTauriRuntime: () => mocks.desktop })); +vi.mock('@/infrastructure/i18n', () => ({ i18nService: { formatNumber: String, formatDate: () => 'date' } })); +vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) })); + +globalThis.IS_REACT_ACT_ENVIRONMENT = true; +let root: Root; +let host: HTMLDivElement; +const project = { workspaceId: 'w', name: 'Project', location: '/p', bytes: 100, sharedBytes: 10, + estimatedBytes: 90, skippedSessions: 0, warning: null, unverifiedReferences: false }; +const candidate = { sessionId: 'old', name: 'Old session', activeAt: 20, revision: '10:20' }; +beforeEach(() => { + vi.resetAllMocks(); + mocks.desktop = true; + mocks.inspect.mockResolvedValue({ scanErrors: [], totalBytes: 135, unidentifiedBytes: 35, + workspaces: [{ ...project, candidates: [candidate] }] }); + host = document.createElement('div'); + document.body.append(host); + root = createRoot(host); +}); +afterEach(() => { act(() => root.unmount()); host.remove(); }); + +it('requires confirmation and cleans only the previewed revision before refreshing usage', async () => { + await act(async () => root.render()); + expect(host.textContent).toContain('35 B'); + const cleanup = () => [...host.querySelectorAll('button')].find(b => b.textContent === 'storage.cleanup')!; + mocks.confirm.mockResolvedValueOnce(false); + await act(async () => cleanup().click()); + expect(mocks.clean).not.toHaveBeenCalled(); + mocks.confirm.mockResolvedValueOnce(true); + mocks.clean.mockResolvedValue({ removedSessions: 1, freedBytes: 90, skippedSessions: 0, errors: [] }); + await act(async () => cleanup().click()); + expect(mocks.clean).toHaveBeenCalledWith('w', 'thirtyDays', [candidate]); + expect(mocks.inspect).toHaveBeenCalledTimes(2); + expect(host.textContent).toContain('storage.result'); +}); + +it('keeps storage on the desktop controller and reports unsupported browser surfaces', async () => { + expect(PEER_CONTROLLER_LOCAL_COMMANDS.has('inspect_snapshot_storage')).toBe(true); + expect(PEER_CONTROLLER_LOCAL_COMMANDS.has('clean_snapshot_storage')).toBe(true); + mocks.desktop = false; + await act(async () => root.render()); + expect(host.textContent).toContain('storage.desktopOnly'); + expect(mocks.inspect).not.toHaveBeenCalled(); +}); + +it('shows workspace usage and expands candidate sessions independently by workspace', async () => { + mocks.inspect.mockResolvedValue({ + totalBytes: 200, unidentifiedBytes: 0, scanErrors: [], + workspaces: [ + { ...project, candidates: [candidate] }, + { ...project, workspaceId: 'other', name: 'Other', candidates: [{ ...candidate, name: 'Other session' }] }, + ], + }); + await act(async () => root.render()); + expect(host.querySelectorAll('table tbody tr')).toHaveLength(2); + expect(host.querySelector('tbody td')?.textContent).toBe('10 B'); + const groups = host.querySelectorAll('button[aria-controls][aria-expanded]'); + const other = Array.from(groups).find(button => button.textContent === 'Other')!; + expect(other.getAttribute('aria-expanded')).toBe('false'); + expect(host.textContent).not.toContain('Other session'); + await act(async () => other.click()); + expect(other.getAttribute('aria-expanded')).toBe('true'); + const content = document.getElementById(other.getAttribute('aria-controls')!); + expect(content?.textContent).toContain('Other session'); + expect(content?.querySelector('time')?.dateTime).toBe(new Date(candidate.activeAt).toISOString()); + expect(host.textContent).not.toContain('Old session'); + + const period = host.querySelector('select[aria-label="storage.period"]')!; + await act(async () => { + period.value = 'sevenDays'; + period.dispatchEvent(new Event('change', { bubbles: true })); + }); + expect(mocks.inspect).toHaveBeenLastCalledWith('sevenDays'); + const refreshedGroups = host.querySelectorAll('[data-openbitfun-part="candidateList"] button[aria-expanded]'); + expect(Array.from(refreshedGroups, button => button.getAttribute('aria-expanded'))).toEqual(['false', 'false']); +}); + +it('explains an empty preview and disables cleanup', async () => { + mocks.inspect.mockResolvedValue({ + totalBytes: 100, unidentifiedBytes: 0, scanErrors: [], + workspaces: [{ ...project, candidates: [], estimatedBytes: 0, skippedSessions: 1 }], + }); + await act(async () => root.render()); + expect(host.textContent).toContain('storage.noCandidates'); + const cleanup = Array.from(host.querySelectorAll('button')).find(button => button.textContent === 'storage.cleanup'); + expect(cleanup?.disabled).toBe(true); +}); + +it('identifies removed-session snapshots without showing a fabricated session activity date', async () => { + const removed = { ...candidate, removed: true, name: '', revision: 'removed:20' }; + mocks.inspect.mockResolvedValue({ + totalBytes: 100, unidentifiedBytes: 0, scanErrors: [], + workspaces: [{ ...project, candidates: [removed] }], + }); + await act(async () => root.render()); + const group = host.querySelector('[data-openbitfun-part="candidateList"] button')!; + expect(group.textContent).toBe(project.name); + expect(group.getAttribute('aria-expanded')).toBe('false'); + await act(async () => group.click()); + const row = host.querySelector('[data-openbitfun-part="session"]')!; + expect(row.textContent).toContain(removed.sessionId); + expect(row.textContent).toContain('storage.removedSession'); + expect(row.querySelector('time')).toBeNull(); +}); diff --git a/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.tsx new file mode 100644 index 0000000000..70ea4b2a12 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/data/StorageSettingsPage.tsx @@ -0,0 +1,256 @@ +import { useEffect, useRef, useState } from 'react'; +import { Folder, Trash2 } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { Button, Disclosure, OverflowText, Select, captureConfirmationAnchor } from '@openbitfun/ui'; +import { snapshotStorageAPI, type StorageOverview, type StoragePeriod, type WorkspaceUsage } from '@/infrastructure/api/service-api/SnapshotStorageAPI'; +import { ConfigLoadingState, ConfigMessage, ConfigPageSection, ConfigRefreshButton } from '@/infrastructure/config/components/common'; +import { confirmDanger } from '@/infrastructure/confirm-dialog'; +import { i18nService } from '@/infrastructure/i18n'; +import { isTauriRuntime } from '@/infrastructure/runtime'; +import type { SettingsPageProps } from '../../settingsTypes'; +import { SettingsPage } from '../shared/SettingsPage'; +import styles from './StorageSettingsPage.module.scss'; + +function size(bytes: number) { + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; + const index = Math.min(units.length - 1, Math.floor(Math.log2(Math.max(1, bytes)) / 10)); + return `${i18nService.formatNumber(bytes / 1024 ** index, { maximumFractionDigits: 1 })} ${units[index]}`; +} + +function WorkspaceStorage({ data }: { data: StorageOverview }) { + const { t } = useTranslation('settings'); + const usage = (bytes: number) => ( +
+ {size(bytes)} +
+ ); + + return ( +
+
+ {t('storage.total')} + {size(data.totalBytes)} +
+ {(data.workspaces.length > 0 || data.unidentifiedBytes > 0) && ( +
+ + + + + + + + + + {data.workspaces.map(row => ( + + + + + + ))} + {data.unidentifiedBytes > 0 && ( + + + + + + )} + +
{t('shared:features.workspace')}{t('storage.sharedColumn')}{t('storage.usedColumn')}
+ {row.name} + {row.location} + {row.warning ? '—' : size(row.sharedBytes)}{usage(row.bytes)}
+ {t('storage.unidentified')} + {t('storage.unidentifiedHint')} + —{usage(data.unidentifiedBytes)}
+
+ )} +
+ ); +} + +function SessionRows({ workspace }: { workspace: WorkspaceUsage }) { + const { t } = useTranslation('settings'); + return ( +
    + {workspace.candidates.map(session => ( +
  • + {session.name || session.sessionId} + {session.removed ? {t('storage.removedSession')} : } +
  • + ))} +
+ ); +} + +function CandidateList({ rows }: { rows: WorkspaceUsage[] }) { + const { t } = useTranslation('settings'); + return ( +
+
+ {t('storage.candidates')} + {t('storage.lastActive')} +
+ {rows.filter(row => row.candidates.length > 0).map(row => ( + } + triggerClassName={styles.groupTrigger} contentInnerClassName={styles.groupBody} + actions={ + {t('storage.sessionCount', { sessions: i18nService.formatNumber(row.candidates.length) })} + }> + + + ))} +
+ ); +} + +function FileSnapshotStorageSection({ isActive }: { isActive: boolean }) { + const { t } = useTranslation('settings'); + const [period, setPeriod] = useState('thirtyDays'); + const [workspace, setWorkspace] = useState(''); + const [refresh, setRefresh] = useState(0); + const [data, setData] = useState(); + const [loading, setLoading] = useState(true); + const [cleaning, setCleaning] = useState(false); + const [error, setError] = useState(''); + const [outcome, setOutcome] = useState<{ type: 'success' | 'warning'; text: string } | null>(null); + const inProgress = useRef(false); + const supported = isTauriRuntime(); + + useEffect(() => { + if (!isActive || !supported) return; + let current = true; + setLoading(true); + setError(''); + snapshotStorageAPI.inspect(period).then(result => { + if (current) setData(result); + }).catch(e => { + if (current) { setError(String(e)); setData(undefined); } + }).finally(() => { if (current) setLoading(false); }); + return () => { current = false; }; + }, [period, refresh, isActive, supported]); + + const rows = (data?.workspaces ?? []).filter(row => !workspace || workspace === row.workspaceId); + const count = rows.reduce((n, row) => n + row.candidates.length, 0); + const estimated = rows.reduce((n, row) => n + row.estimatedBytes, 0); + const skipped = rows.reduce((n, row) => n + row.skippedSessions, 0); + const busy = loading || cleaning; + const preview = t('storage.preview', { sessions: i18nService.formatNumber(count), size: size(estimated) }); + + async function clean(trigger: HTMLElement) { + if (inProgress.current || busy || !count) return; + inProgress.current = true; + setCleaning(true); + try { + if (!await confirmDanger(t('storage.confirmTitle'), t('storage.confirm', { preview }), { + anchor: captureConfirmationAnchor(trigger), confirmText: t('storage.cleanup'), + })) return; + let bytes = 0; + let removed = 0; + let missed = 0; + const errors: string[] = []; + for (const row of rows) { + if (!row.candidates.length) continue; + try { + const result = await snapshotStorageAPI.clean(row.workspaceId, period, row.candidates); + bytes += result.freedBytes; + removed += result.removedSessions; + missed += result.skippedSessions; + errors.push(...result.errors); + } catch (e) { + missed += row.candidates.length; + errors.push(`${row.name} · ${String(e)}`); + } + } + const summary = t('storage.result', { sessions: i18nService.formatNumber(removed), skipped: i18nService.formatNumber(missed), size: size(bytes) }); + setOutcome({ type: errors.length || missed ? 'warning' : 'success', text: [summary, ...errors].join('\n') }); + setLoading(true); + setRefresh(v => v + 1); + } finally { + setCleaning(false); + inProgress.current = false; + } + } + + if (!supported) return ; + + return ( + <> + { setLoading(true); setRefresh(v => v + 1); }} />}> + {loading && !data && } + {error && } + {data && <> + {data.scanErrors.length > 0 && ( + + )} + + } + + {data && ( + +
+
+
+ {t('storage.scope')} + { + if (period !== v) { setLoading(true); setOutcome(null); setPeriod(v as StoragePeriod); } + }} + options={[ + { value: 'thirtyDays', label: t('storage.thirtyDays') }, + { value: 'sevenDays', label: t('storage.sevenDays') }, + { value: 'all', label: t('storage.all') }, + ]} /> +
+
+ {loading ? : <> + {rows.filter(row => row.warning || row.unverifiedReferences).map(row => ( + + ))} + {count > 0 && } +
+
+ {count ? preview : t('storage.noCandidates')} +

{t('storage.skipped', { sessions: i18nService.formatNumber(skipped) })}

+
+ +
+ } +
+
+ )} + + + ); +} + +export default function StorageSettingsPage({ isActive = true }: SettingsPageProps) { + return ( + + + + ); +} diff --git a/src/web-ui/src/app/scenes/settings/settingsRegistry.test.ts b/src/web-ui/src/app/scenes/settings/settingsRegistry.test.ts index f773c87b99..8f053853a5 100644 --- a/src/web-ui/src/app/scenes/settings/settingsRegistry.test.ts +++ b/src/web-ui/src/app/scenes/settings/settingsRegistry.test.ts @@ -26,9 +26,9 @@ describe('settings information architecture', () => { ai: ['ai.models', 'ai.session-memory', 'ai.execution', 'ai.permissions'], development: ['development.editor', 'development.terminal', 'development.workspace'], tools: ['tools.external-import', 'tools.web-search', 'tools.desktop-control', 'tools.mcp', 'tools.external-agents', 'tools.automation'], - data: ['data.usage', 'data.archived', 'data.diagnostics'], + data: ['data.usage', 'data.storage', 'data.archived', 'data.diagnostics'], }); - expect(new Set(SETTINGS_PAGE_MANIFESTS.map(page => page.id)).size).toBe(20); + expect(new Set(SETTINGS_PAGE_MANIFESTS.map(page => page.id)).size).toBe(21); expect(SETTINGS_PAGE_MANIFESTS.filter(page => page.views?.length).map(page => page.id)).toEqual(['tools.external-agents']); expect(getSettingsPageManifest('tools.external-agents').views?.map(view => view.id)).toEqual(['local', 'ssh', 'json']); expect(getSettingsPageManifest('application.input').sections?.map(section => section.id)).toEqual(['voice', 'message-sending', 'text-selection', 'shortcuts']); diff --git a/src/web-ui/src/app/scenes/settings/settingsRegistry.ts b/src/web-ui/src/app/scenes/settings/settingsRegistry.ts index 692931d248..10067f784f 100644 --- a/src/web-ui/src/app/scenes/settings/settingsRegistry.ts +++ b/src/web-ui/src/app/scenes/settings/settingsRegistry.ts @@ -11,6 +11,7 @@ import { FileInput, FolderGit2, Globe, + HardDrive, Keyboard, MousePointerClick, Palette, @@ -512,6 +513,17 @@ export const SETTINGS_PAGE_MANIFESTS: readonly SettingsPageManifest[] = [ searchPhrases: [phrase('settings/usage', 'title'), phrase('settings/usage', 'subtitle')], load: () => import('./pages/data/UsageStatisticsSettingsPage'), }), + definePage({ + id: 'data.storage', + categoryId: 'data', + icon: HardDrive, + labelKey: 'navigation.pages.storage.label', + descriptionKey: 'navigation.pages.storage.description', + keywords: ['storage', 'disk', 'space', 'cleanup', 'snapshot', 'history'], + namespaces: ['settings'], + searchPhrases: [phrase('settings', 'storage.snapshots'), phrase('settings', 'storage.cleanup')], + load: () => import('./pages/data/StorageSettingsPage'), + }), definePage({ id: 'data.archived', categoryId: 'data', diff --git a/src/web-ui/src/app/scenes/settings/settingsTypes.ts b/src/web-ui/src/app/scenes/settings/settingsTypes.ts index 6178d217b0..47d236d1a4 100644 --- a/src/web-ui/src/app/scenes/settings/settingsTypes.ts +++ b/src/web-ui/src/app/scenes/settings/settingsTypes.ts @@ -24,6 +24,7 @@ export type SettingsPageId = | 'tools.external-agents' | 'tools.external-import' | 'data.usage' + | 'data.storage' | 'data.archived' | 'data.diagnostics'; diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index 97385cc696..e0c1da5eb5 100644 --- a/src/web-ui/src/infrastructure/api/generated/productControl.ts +++ b/src/web-ui/src/infrastructure/api/generated/productControl.ts @@ -1,7 +1,7 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. -export const PRODUCT_CONTROL_GRAPH_DIGEST = "1e9b09293cfab7a47682d9decab4e0626137d6e79cd2405688d7f16e05a8e6b5" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "f592c3304b41651db62ca8afeff8bb8e3d56a3e49d6420eff960b3cfe9eb9294" as const; -export type ProductControlCapabilityId = "feature.home-search" | "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.cli-tui" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "feature.tasks-automation" | "feature.insights" | "feature.ecosystem-compatibility" | "feature.remote-workspaces" | "feature.remote-connect" | "feature.detached-dispatch" | "feature.pages" | "feature.voice-input" | "feature.desktop-pet" | "feature.desktop-cards" | "setting.application.general" | "setting.application.appearance" | "setting.application.pet" | "setting.application.input" | "setting.application.shortcuts" | "setting.application.development" | "setting.ai.models" | "setting.ai.permissions" | "setting.ai.memory" | "setting.workspace.session" | "setting.workspace.worktrees" | "setting.tools.execution" | "setting.application.terminal" | "setting.tools.desktop-control" | "setting.tools.browser-control" | "setting.tools.automation" | "setting.tools.web-search" | "setting.tools.mcp" | "setting.tools.acp" | "setting.data.usage" | "setting.data.archived" | "setting.data.diagnostics" | "feature.generative-ui"; +export type ProductControlCapabilityId = "feature.home-search" | "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.cli-tui" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "feature.tasks-automation" | "feature.insights" | "feature.ecosystem-compatibility" | "feature.remote-workspaces" | "feature.remote-connect" | "feature.detached-dispatch" | "feature.pages" | "feature.voice-input" | "feature.desktop-pet" | "feature.desktop-cards" | "setting.application.general" | "setting.application.appearance" | "setting.application.pet" | "setting.application.input" | "setting.application.shortcuts" | "setting.application.development" | "setting.ai.models" | "setting.ai.permissions" | "setting.ai.memory" | "setting.workspace.session" | "setting.workspace.worktrees" | "setting.tools.execution" | "setting.application.terminal" | "setting.tools.desktop-control" | "setting.tools.browser-control" | "setting.tools.automation" | "setting.tools.web-search" | "setting.tools.mcp" | "setting.tools.acp" | "setting.data.usage" | "setting.data.storage" | "setting.data.archived" | "setting.data.diagnostics" | "feature.generative-ui"; export interface ProductControlOptionIdsByCapability { "feature.home-search": never; @@ -48,6 +48,7 @@ export interface ProductControlOptionIdsByCapability { "setting.tools.mcp": never; "setting.tools.acp": never; "setting.data.usage": never; + "setting.data.storage": never; "setting.data.archived": never; "setting.data.diagnostics": "log-level" | "sensitive-diagnostics"; "feature.generative-ui": never; @@ -98,6 +99,7 @@ export interface ProductControlOperationIdsByCapability { "setting.tools.mcp": "list-servers" | "configure-server" | "start-server" | "stop-server" | "restart-server" | "delete-server"; "setting.tools.acp": never; "setting.data.usage": never; + "setting.data.storage": never; "setting.data.archived": never; "setting.data.diagnostics": never; "feature.generative-ui": never; diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index bfec5b864c..fc8de1e0ae 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:0b686be0f5103ef5" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:90361f729e6ce746" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -41,6 +41,7 @@ export const PEER_CONTROLLER_LOCAL_COMMANDS: ReadonlySet = new Set([ "cancel_app_update_download", "cancel_insights_generation", "check_for_updates", + "clean_snapshot_storage", "confirm_frontend_update", "debug_devtools_available", "debug_open_devtools", @@ -87,6 +88,7 @@ export const PEER_CONTROLLER_LOCAL_COMMANDS: ReadonlySet = new Set([ "i18n_set_language", "import_agent_companion_pet_package", "initialize_tray_after_startup", + "inspect_snapshot_storage", "install_pending_update", "install_update", "list_agent_companion_pets", diff --git a/src/web-ui/src/infrastructure/api/service-api/SnapshotStorageAPI.ts b/src/web-ui/src/infrastructure/api/service-api/SnapshotStorageAPI.ts new file mode 100644 index 0000000000..418bf90b68 --- /dev/null +++ b/src/web-ui/src/infrastructure/api/service-api/SnapshotStorageAPI.ts @@ -0,0 +1,43 @@ +import { api } from './ApiClient'; + +export type StoragePeriod = 'sevenDays' | 'thirtyDays' | 'all'; + +export interface SnapshotCandidate { + sessionId: string; + name: string; + activeAt: number; + revision: string; + removed?: boolean; +} +export interface WorkspaceUsage { + workspaceId: string; + name: string; + location: string; + bytes: number; + sharedBytes: number; + estimatedBytes: number; + removedEstimatedBytes?: number; + skippedSessions: number; + candidates: SnapshotCandidate[]; + warning: string | null; + unverifiedReferences: boolean; +} +export interface StorageOverview { + scanErrors: string[]; + totalBytes: number; + unidentifiedBytes: number; + workspaces: WorkspaceUsage[]; +} +interface CleanupResult { + removedSessions: number; + skippedSessions: number; + freedBytes: number; + errors: string[]; +} + +export const snapshotStorageAPI = { + inspect: (period: StoragePeriod) => + api.invoke('inspect_snapshot_storage', { request: { period } }, { timeout: 0, retries: 0 }), + clean: (workspaceId: string, period: StoragePeriod, candidates: SnapshotCandidate[]) => + api.invoke('clean_snapshot_storage', { request: { workspaceId, period, candidates } }, { timeout: 0, retries: 0 }), +}; diff --git a/src/web-ui/src/infrastructure/appearance/registry/defaultAppearanceRegistry.ts b/src/web-ui/src/infrastructure/appearance/registry/defaultAppearanceRegistry.ts index e7a4bbc76b..4abad6ffc4 100644 --- a/src/web-ui/src/infrastructure/appearance/registry/defaultAppearanceRegistry.ts +++ b/src/web-ui/src/infrastructure/appearance/registry/defaultAppearanceRegistry.ts @@ -130,6 +130,7 @@ import { themeTokenAppearanceAdapter } from '../adapters/ThemeTokenAppearanceAda import { tiptapEditorAppearanceDescriptor } from '@/tools/editor/meditor/components/TiptapEditor.appearance'; import { workspaceProjectPermissionsDialogAppearanceDescriptor } from '@/app/components/NavPanel/sections/workspaces/WorkspaceProjectPermissionsDialog.appearance'; import { workspaceSessionBatchModalAppearanceDescriptor } from '@/app/components/NavPanel/sections/workspaces/WorkspaceSessionBatchModal.appearance'; +import { snapshotStorageAppearanceDescriptor } from '@/app/scenes/settings/pages/data/StorageSettingsPage.appearance'; import { archivedSessionsConfigAppearanceDescriptor } from '@/app/scenes/settings/pages/data/ArchivedSessionsSettingsPage.appearance'; import { automationSettingsPageAppearanceDescriptor, @@ -406,6 +407,7 @@ export function createDefaultAppearanceRegistry(): AppearanceRegistry { .registerComponent(tiptapEditorAppearanceDescriptor) .registerComponent(workspaceProjectPermissionsDialogAppearanceDescriptor) .registerComponent(workspaceSessionBatchModalAppearanceDescriptor) + .registerComponent(snapshotStorageAppearanceDescriptor) .registerComponent(archivedSessionsConfigAppearanceDescriptor) .registerComponent(usageStatisticsConfigAppearanceDescriptor) .registerComponent(settingsNavAppearanceDescriptor) diff --git a/src/web-ui/src/locales/en-US/scenes/capabilities.json b/src/web-ui/src/locales/en-US/scenes/capabilities.json index a980901557..43f319e548 100644 --- a/src/web-ui/src/locales/en-US/scenes/capabilities.json +++ b/src/web-ui/src/locales/en-US/scenes/capabilities.json @@ -686,6 +686,13 @@ "trend": "Track Input and Output token volume over time in the stacked bar chart" } }, + "storage": { + "title": "Storage", + "summary": "Inspect local file snapshot usage by workspace and clean up eligible session histories.", + "items": { + "clean": "Preview and clean up session file snapshots" + } + }, "archived": { "title": "Archived sessions", "summary": "Review archived conversations grouped by collapsible workspace headers, restore sessions back to their original workspace, delete individual native or imported entries, or clear all archives.", diff --git a/src/web-ui/src/locales/en-US/settings.json b/src/web-ui/src/locales/en-US/settings.json index 1e0ee4a6cc..28e7694e7c 100644 --- a/src/web-ui/src/locales/en-US/settings.json +++ b/src/web-ui/src/locales/en-US/settings.json @@ -91,6 +91,10 @@ "externalImport": { "label": "External import", "description": "Import and manage content from other AI applications" + }, + "storage": { + "label": "Storage", + "description": "View storage on this device and clean up file snapshots" } }, "views": { @@ -628,5 +632,36 @@ }, "archivedSessions": { "sectionDescription": "Grouped by workspace; restore a session to continue it, or delete it permanently with no undo" + }, + "storage": { + "snapshots": "File snapshots", + "device": "Snapshot files stored on this device, including snapshots from SSH workspaces.", + "total": "Snapshot storage", + "refresh": "Refresh storage usage", + "unverified": "Some snapshot references could not be verified. Files with uncertain ownership will be kept.", + "incomplete": "Some directories could not be scanned. Totals cover the readable directories.", + "scanning": "Calculating snapshot sizes…", + "unidentified": "Unidentified workspace", + "unidentifiedHint": "These snapshot files are retained because their workspace owner could not be verified.", + "cleanup": "Clean up snapshots", + "scope": "Workspaces to clean", + "allWorkspaces": "All workspaces", + "period": "Sessions to clean", + "thirtyDays": "Inactive for over 30 days", + "sevenDays": "Inactive for over 7 days", + "all": "All eligible sessions", + "preview": "{{sessions}} sessions · estimated {{size}} to free", + "skipped": "{{sessions}} sessions excluded.", + "confirmTitle": "Permanently delete these file snapshots?", + "confirm": "{{preview}}. The affected file diffs and snapshot rollback points will be lost. Your conversations and workspace files will be kept.", + "result": "Cleaned {{sessions}} sessions and freed {{size}}. Skipped {{skipped}} sessions from the preview.", + "desktopOnly": "Open Storage in the desktop app to manage snapshots on this device.", + "sharedColumn": "Shared or unassigned", + "usedColumn": "Snapshot size", + "candidates": "Sessions to clean up", + "lastActive": "Last active", + "sessionCount": "Sessions · {{sessions}}", + "removedSession": "Session removed", + "noCandidates": "No sessions match this cleanup scope" } } diff --git a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json index 3326e0b281..045907297f 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json @@ -686,6 +686,13 @@ "trend": "通过堆叠柱状图查看输入与输出 Token 随时间的变化趋势" } }, + "storage": { + "title": "存储空间", + "summary": "按工作区查看本机文件快照占用,手动清理符合条件的会话。", + "items": { + "clean": "预览并清理会话文件快照" + } + }, "archived": { "title": "已归档会话", "summary": "按工作区折叠分组盘点已归档的对话历史,支持一键恢复回原项目侧栏、单条删除或移除外部导入来源,以及二次确认清空全部归档。", diff --git a/src/web-ui/src/locales/zh-CN/settings.json b/src/web-ui/src/locales/zh-CN/settings.json index fa7ed2cd07..3b3e05287c 100644 --- a/src/web-ui/src/locales/zh-CN/settings.json +++ b/src/web-ui/src/locales/zh-CN/settings.json @@ -91,6 +91,10 @@ "externalImport": { "label": "外部导入", "description": "导入并管理其他 AI 应用中的内容" + }, + "storage": { + "label": "存储空间", + "description": "查看本机存储占用并清理文件快照" } }, "views": { @@ -628,5 +632,36 @@ }, "archivedSessions": { "sectionDescription": "按工作区分组;恢复后可继续原会话,永久删除无法撤销" + }, + "storage": { + "snapshots": "文件快照", + "device": "统计本机保存的快照,包括 SSH 工作区的快照。", + "total": "快照总占用", + "refresh": "刷新存储占用", + "unverified": "部分快照引用无法核实,清理时会保留归属不确定的文件。", + "incomplete": "部分目录无法扫描。占用统计仅包含成功读取的目录。", + "scanning": "正在统计快照大小…", + "unidentified": "无法识别的工作区", + "unidentifiedHint": "这些快照无法核实所属工作区,清理时会保留。", + "cleanup": "清理快照", + "scope": "工作区范围", + "allWorkspaces": "所有工作区", + "period": "清理范围", + "thirtyDays": "超过 30 天未活跃", + "sevenDays": "超过 7 天未活跃", + "all": "全部符合条件的会话", + "preview": "涉及 {{sessions}} 个会话,预计释放 {{size}}", + "skipped": "已排除 {{sessions}} 个会话。", + "confirmTitle": "永久删除这些文件快照?", + "confirm": "{{preview}}。相关文件差异和快照回退点将永久失效。对话记录和工作区文件会保留。", + "result": "已清理 {{sessions}} 个会话的快照,释放 {{size}}。预览中有 {{skipped}} 个会话被跳过。", + "desktopOnly": "请在桌面应用的存储空间页面管理本机快照。", + "sharedColumn": "共享或未归属", + "usedColumn": "快照占用", + "candidates": "待清理会话", + "lastActive": "最近活跃", + "sessionCount": "{{sessions}} 个会话", + "removedSession": "会话已移除", + "noCandidates": "当前范围没有可清理的会话" } } diff --git a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json index bc10ce109f..c7ea4a209a 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json @@ -686,6 +686,13 @@ "trend": "透過堆疊柱狀圖檢視輸入與輸出 Token 隨時間的變化趨勢" } }, + "storage": { + "title": "儲存空間", + "summary": "依工作區檢視本機檔案快照佔用,手動清理符合條件的會話。", + "items": { + "clean": "預覽並清理會話檔案快照" + } + }, "archived": { "title": "已歸檔會話", "summary": "依工作區折疊分組盤點已歸檔的對話歷史,支援一鍵還原回原專案側欄、單條刪除或移除外部匯入來源,以及二次確認清空全部歸檔。", diff --git a/src/web-ui/src/locales/zh-TW/settings.json b/src/web-ui/src/locales/zh-TW/settings.json index ed816b8a40..bddaa46b31 100644 --- a/src/web-ui/src/locales/zh-TW/settings.json +++ b/src/web-ui/src/locales/zh-TW/settings.json @@ -91,6 +91,10 @@ "externalImport": { "label": "外部匯入", "description": "匯入並管理其他 AI 應用程式中的內容" + }, + "storage": { + "label": "儲存空間", + "description": "檢視本機儲存用量並清理檔案快照" } }, "views": { @@ -628,5 +632,36 @@ }, "archivedSessions": { "sectionDescription": "依工作區分組;還原後可繼續原會話,永久刪除無法復原" + }, + "storage": { + "snapshots": "檔案快照", + "device": "統計本機儲存的快照,包含 SSH 工作區快照。", + "total": "快照總用量", + "refresh": "重新整理儲存用量", + "unverified": "部分快照引用無法核實,清理時會保留歸屬不確定的檔案。", + "incomplete": "部分目錄無法掃描。用量統計僅包含成功讀取的目錄。", + "scanning": "正在統計快照大小…", + "unidentified": "無法識別的工作區", + "unidentifiedHint": "這些快照無法核實所屬工作區,清理時會保留。", + "cleanup": "清理快照", + "scope": "工作區範圍", + "allWorkspaces": "所有工作區", + "period": "清理範圍", + "thirtyDays": "超過 30 天未活動", + "sevenDays": "超過 7 天未活動", + "all": "全部符合條件的工作階段", + "preview": "涉及 {{sessions}} 個工作階段,預計釋放 {{size}}", + "skipped": "已排除 {{sessions}} 個工作階段。", + "confirmTitle": "永久刪除這些檔案快照?", + "confirm": "{{preview}}。相關檔案差異與快照還原點將永久失效。對話記錄與工作區檔案會保留。", + "result": "已清理 {{sessions}} 個工作階段的快照,釋放 {{size}}。預覽中有 {{skipped}} 個工作階段已略過。", + "desktopOnly": "請在桌面應用程式的儲存空間頁面管理本機快照。", + "sharedColumn": "共用或未歸屬", + "usedColumn": "快照用量", + "candidates": "待清理工作階段", + "lastActive": "最近活動", + "sessionCount": "{{sessions}} 個工作階段", + "removedSession": "工作階段已移除", + "noCandidates": "目前範圍內沒有可清理的工作階段" } }