diff --git a/crates/application/src/domain.rs b/crates/application/src/domain.rs index a4ed7b885..6d1e8616b 100644 --- a/crates/application/src/domain.rs +++ b/crates/application/src/domain.rs @@ -595,6 +595,10 @@ domain_commands! { ConversationStopAsyncTask => "conversation_stop_async_task" / "conversation.write", ConversationTruncateToTurn => "conversation_truncate_to_turn" / "conversation.write", ConversationCheckpointPreview => "conversation_checkpoint_file_changes_preview" / "conversation.read", + ConversationProjects => "conversation_projects" / "conversation.read", + ConversationWorkspaceTree => "conversation_workspace_tree" / "artifact.read", + ConversationWorkspaceFile => "conversation_workspace_file" / "artifact.read", + ConversationWorkspaceDiff => "conversation_workspace_diff" / "artifact.read", ConversationClose => "conversation_close" / "conversation.write", ConversationExport => "conversation_export" / "conversation.read", ConversationExportMarkdown => "conversation_export_markdown" / "conversation.read", diff --git a/crates/server/src/domains.rs b/crates/server/src/domains.rs index 7d43e2dcf..49f726d62 100644 --- a/crates/server/src/domains.rs +++ b/crates/server/src/domains.rs @@ -185,6 +185,16 @@ impl ServerApplicationDomains { DomainCommand::ConversationCheckpointPreview => { self.conversation_checkpoint_preview(args).await } + DomainCommand::ConversationProjects => self.conversation_projects().await, + DomainCommand::ConversationWorkspaceTree => { + self.conversation_workspace_tree(args).await + } + DomainCommand::ConversationWorkspaceFile => { + self.conversation_workspace_file(args).await + } + DomainCommand::ConversationWorkspaceDiff => { + self.conversation_workspace_diff(args).await + } DomainCommand::ConversationImport => self.conversation_import_host(args).await, DomainCommand::ConversationFork => self.conversation_fork_host(args).await, DomainCommand::WorkspaceContinueConflicts diff --git a/crates/server/src/host/mod.rs b/crates/server/src/host/mod.rs index 6e430d278..1b2bc05e0 100644 --- a/crates/server/src/host/mod.rs +++ b/crates/server/src/host/mod.rs @@ -16,6 +16,7 @@ pub mod remote_profiles; pub mod row_ops; pub mod streams; pub mod surface; +pub mod workspace_files; pub mod workspace_parity; pub use events::{HostEvent, HostEventBus, patch_stream_channel, patch_stream_subscribe_command}; diff --git a/crates/server/src/host/product.rs b/crates/server/src/host/product.rs index cb91ea02f..f37933a99 100644 --- a/crates/server/src/host/product.rs +++ b/crates/server/src/host/product.rs @@ -1438,7 +1438,7 @@ impl ServerApplicationDomains { self.primary_worktree(workspace_id, repo_id).await } - async fn primary_worktree( + pub(crate) async fn primary_worktree( &self, workspace_id: Uuid, repo_id: Option, diff --git a/crates/server/src/host/workspace_files.rs b/crates/server/src/host/workspace_files.rs new file mode 100644 index 000000000..7de92c346 --- /dev/null +++ b/crates/server/src/host/workspace_files.rs @@ -0,0 +1,416 @@ +//! Read-only workspace browsing for Companion devices (`artifact.read`). +//! +//! Every path is relative to the workspace root and is resolved inside it; nothing +//! here can name an absolute path, leave the root through `..` or a symlink, or +//! read hidden files (apart from a few project config files), VCS internals and +//! credential files. A scratch workspace's root can be the user's home directory, +//! so the policy cannot rely on the root being a clean project. + +use std::path::{Component, Path, PathBuf}; + +use application::ApplicationError; +use db::models::workspace_repo::WorkspaceRepo; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use uuid::Uuid; + +use crate::domains::{ServerApplicationDomains, internal_error, parse, serialize}; + +const MAX_ENTRIES: usize = 500; +const MAX_FILE_BYTES: usize = 256 * 1024; +const MAX_DIFF_BYTES: usize = 200 * 1024; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct WorkspacePathArgs { + workspace_id: Uuid, + #[serde(default)] + path: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct WorkspaceArgs { + workspace_id: Uuid, +} + +#[derive(Debug, Serialize)] +struct TreeEntry { + name: String, + path: String, + directory: bool, +} + +#[derive(Debug, Serialize)] +struct Tree { + path: String, + entries: Vec, + truncated: bool, +} + +#[derive(Debug, Serialize)] +struct FileContent { + path: String, + size: u64, + binary: bool, + truncated: bool, + content: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct ProjectSummary { + id: Uuid, + name: String, + workspace_ids: Vec, +} + +impl ServerApplicationDomains { + /// Projects with the workspaces they own, so a client can group conversations by project. + pub(crate) async fn conversation_projects(&self) -> Result { + let rows = sqlx::query_as::<_, (Uuid, String, Uuid)>( + r#"SELECT p.id, p.name, w.id + FROM workspaces w + JOIN projects p ON p.id = w.project_id + ORDER BY p.name COLLATE NOCASE, w.created_at"#, + ) + .fetch_all(&self.pool) + .await + .map_err(internal_error)?; + let mut projects: Vec = Vec::new(); + for (id, name, workspace_id) in rows { + match projects.iter_mut().find(|project| project.id == id) { + Some(project) => project.workspace_ids.push(workspace_id), + None => projects.push(ProjectSummary { + id, + name, + workspace_ids: vec![workspace_id], + }), + } + } + serialize(projects) + } + + /// The directory the Agent works in; scratch workspaces have one even without a repository. + async fn browsable_root(&self, workspace_id: Uuid) -> Result { + db::SqliteConversationRepository::new(self.pool.clone()) + .workspace_root(workspace_id) + .await + .map_err(internal_error)? + .map(PathBuf::from) + .ok_or_else(|| ApplicationError::not_found("workspace")) + } + + pub(crate) async fn conversation_workspace_tree( + &self, + args: Value, + ) -> Result { + let args: WorkspacePathArgs = parse(args)?; + let root = self.browsable_root(args.workspace_id).await?; + let tree = tokio::task::spawn_blocking(move || list_directory(&root, &args.path)) + .await + .map_err(internal_error)??; + serialize(tree) + } + + pub(crate) async fn conversation_workspace_file( + &self, + args: Value, + ) -> Result { + let args: WorkspacePathArgs = parse(args)?; + let root = self.browsable_root(args.workspace_id).await?; + let file = tokio::task::spawn_blocking(move || read_text_file(&root, &args.path)) + .await + .map_err(internal_error)??; + serialize(file) + } + + /// Unified diffs of the working tree against HEAD, one entry per changed file. + pub(crate) async fn conversation_workspace_diff( + &self, + args: Value, + ) -> Result { + let args: WorkspaceArgs = parse(args)?; + let repositories = WorkspaceRepo::find_repos_for_workspace(&self.pool, args.workspace_id) + .await + .map_err(internal_error)?; + if repositories.is_empty() { + // A workspace without a repository simply has no changes to show. + return Ok(Value::Array(Vec::new())); + } + let root = self.primary_worktree(args.workspace_id, None).await?; + let mut diffs = self.git_read(root, git::GitService::get_file_diffs).await?; + if let Some(entries) = diffs.as_array_mut() { + for entry in entries { + bound_diff(entry); + } + } + Ok(diffs) + } +} + +/// Keeps a phone-sized payload: an oversized diff is cut at a line boundary and flagged. +fn bound_diff(entry: &mut Value) { + let Some(object) = entry.as_object_mut() else { + return; + }; + let mut truncated = false; + if let Some(Value::String(diff)) = object.get_mut("diff") + && diff.len() > MAX_DIFF_BYTES + { + let mut end = MAX_DIFF_BYTES; + while !diff.is_char_boundary(end) { + end -= 1; + } + let cut = diff[..end].rfind('\n').unwrap_or(end); + diff.truncate(cut); + truncated = true; + } + object.insert("truncated".to_string(), Value::Bool(truncated)); +} + +fn forbidden(reason: &str) -> ApplicationError { + ApplicationError::forbidden(reason) +} + +/// Hidden project files that are safe and useful to read from a phone. +const VISIBLE_DOT_NAMES: &[&str] = &[ + ".github", + ".vscode", + ".gitignore", + ".gitattributes", + ".editorconfig", + ".prettierrc", + ".eslintrc", + ".nvmrc", + ".node-version", +]; + +/// Names that hold credentials wherever they appear. +fn is_credential_name(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + lower.ends_with(".pem") + || lower.ends_with(".key") + || lower.ends_with(".p12") + || lower.ends_with(".pfx") + || lower.starts_with("id_rsa") + || lower.starts_with("id_ed25519") + || lower.starts_with("id_ecdsa") + || lower == "credentials" + || lower == ".netrc" +} + +/// A name the phone may list and read. +fn is_readable_name(name: &str) -> bool { + if is_credential_name(name) { + return false; + } + !name.starts_with('.') + || VISIBLE_DOT_NAMES + .iter() + .any(|allowed| name.starts_with(allowed)) +} + +/// Resolves `relative` below `root`, refusing anything that could escape or expose secrets. +fn resolve_inside(root: &Path, relative: &str) -> Result { + let relative_path = Path::new(relative); + for component in relative_path.components() { + match component { + Component::Normal(name) => { + if !is_readable_name(&name.to_string_lossy()) { + return Err(forbidden("this path is not readable from a paired device")); + } + } + Component::CurDir => {} + _ => return Err(ApplicationError::bad_request("path must be relative")), + } + } + let root = root + .canonicalize() + .map_err(|_| ApplicationError::not_found("workspace directory"))?; + let resolved = root + .join(relative_path) + .canonicalize() + .map_err(|_| ApplicationError::not_found(format!("path {relative}")))?; + if !resolved.starts_with(&root) { + return Err(forbidden("path is outside the workspace")); + } + Ok(resolved) +} + +fn relative_string(root: &Path, resolved: &Path) -> String { + let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + resolved + .strip_prefix(&root) + .unwrap_or(resolved) + .components() + .map(|part| part.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/") +} + +fn list_directory(root: &Path, relative: &str) -> Result { + let directory = resolve_inside(root, relative)?; + if !directory.is_dir() { + return Err(ApplicationError::bad_request("path is not a directory")); + } + let base = relative_string(root, &directory); + let mut entries = Vec::new(); + let mut truncated = false; + let read = std::fs::read_dir(&directory).map_err(internal_error)?; + for entry in read.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + if !is_readable_name(&name) { + continue; + } + if entries.len() >= MAX_ENTRIES { + truncated = true; + break; + } + let directory = entry.path().is_dir(); + let path = if base.is_empty() { + name.clone() + } else { + format!("{base}/{name}") + }; + entries.push(TreeEntry { + name, + path, + directory, + }); + } + entries.sort_by(|left, right| { + right + .directory + .cmp(&left.directory) + .then_with(|| left.name.to_lowercase().cmp(&right.name.to_lowercase())) + }); + Ok(Tree { + path: base, + entries, + truncated, + }) +} + +fn read_text_file(root: &Path, relative: &str) -> Result { + let file = resolve_inside(root, relative)?; + let metadata = std::fs::metadata(&file).map_err(internal_error)?; + if !metadata.is_file() { + return Err(ApplicationError::bad_request("path is not a file")); + } + let size = metadata.len(); + let path = relative_string(root, &file); + let mut bytes = Vec::new(); + { + use std::io::Read; + std::fs::File::open(&file) + .map_err(internal_error)? + .take(MAX_FILE_BYTES as u64) + .read_to_end(&mut bytes) + .map_err(internal_error)?; + } + if bytes.contains(&0) { + return Ok(FileContent { + path, + size, + binary: true, + truncated: false, + content: None, + }); + } + let truncated = size > MAX_FILE_BYTES as u64; + // A cut can land inside a multi-byte character; lossy decoding keeps the readable prefix. + let content = String::from_utf8_lossy(&bytes).into_owned(); + Ok(FileContent { + path, + size, + binary: false, + truncated, + content: Some(content), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn workspace() -> tempfile::TempDir { + let dir = tempfile::tempdir().expect("tempdir"); + std::fs::create_dir_all(dir.path().join("src/nested")).unwrap(); + std::fs::create_dir_all(dir.path().join(".git")).unwrap(); + std::fs::write(dir.path().join("README.md"), "# hello\n").unwrap(); + std::fs::write(dir.path().join("src/main.rs"), "fn main() {}\n").unwrap(); + std::fs::write(dir.path().join(".env"), "SECRET=1\n").unwrap(); + std::fs::write(dir.path().join(".gitignore"), "target\n").unwrap(); + std::fs::create_dir_all(dir.path().join(".ssh")).unwrap(); + std::fs::write(dir.path().join(".ssh/id_rsa"), "key").unwrap(); + std::fs::write(dir.path().join("server.pem"), "key").unwrap(); + std::fs::write(dir.path().join("blob.bin"), [0u8, 1, 2]).unwrap(); + dir + } + + #[test] + fn lists_one_level_directories_first_and_hides_secrets() { + let dir = workspace(); + let root = list_directory(dir.path(), "").unwrap(); + let names: Vec<_> = root + .entries + .iter() + .map(|entry| entry.name.as_str()) + .collect(); + assert_eq!(names, ["src", ".gitignore", "blob.bin", "README.md"]); + let src = list_directory(dir.path(), "src").unwrap(); + assert_eq!(src.path, "src"); + assert_eq!( + src.entries + .iter() + .map(|entry| entry.path.as_str()) + .collect::>(), + ["src/nested", "src/main.rs"] + ); + } + + #[test] + fn refuses_to_leave_the_workspace_or_read_secrets() { + let dir = workspace(); + assert!(read_text_file(dir.path(), "../outside").is_err()); + assert!(read_text_file(dir.path(), "/etc/passwd").is_err()); + assert!(read_text_file(dir.path(), ".env").is_err()); + assert!(read_text_file(dir.path(), ".ssh/id_rsa").is_err()); + assert!(read_text_file(dir.path(), "server.pem").is_err()); + assert!(read_text_file(dir.path(), ".gitignore").is_ok()); + assert!(list_directory(dir.path(), ".git").is_err()); + #[cfg(unix)] + { + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("secret.txt"), "x").unwrap(); + std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap(); + assert!(read_text_file(dir.path(), "link/secret.txt").is_err()); + } + } + + #[test] + fn reads_text_and_flags_binary_and_oversize() { + let dir = workspace(); + let readme = read_text_file(dir.path(), "README.md").unwrap(); + assert_eq!(readme.content.as_deref(), Some("# hello\n")); + assert!(!readme.binary && !readme.truncated); + let blob = read_text_file(dir.path(), "blob.bin").unwrap(); + assert!(blob.binary && blob.content.is_none()); + std::fs::write(dir.path().join("big.txt"), "a".repeat(MAX_FILE_BYTES + 10)).unwrap(); + let big = read_text_file(dir.path(), "big.txt").unwrap(); + assert!(big.truncated); + assert_eq!(big.content.unwrap().len(), MAX_FILE_BYTES); + } + + #[test] + fn oversized_diffs_are_cut_at_a_line_and_flagged() { + let mut entry = serde_json::json!({ "path": "a", "diff": "x\n".repeat(MAX_DIFF_BYTES) }); + bound_diff(&mut entry); + assert_eq!(entry["truncated"], true); + assert!(entry["diff"].as_str().unwrap().len() <= MAX_DIFF_BYTES); + let mut small = serde_json::json!({ "path": "a", "diff": "@@ -1 +1 @@\n-a\n+b\n" }); + bound_diff(&mut small); + assert_eq!(small["truncated"], false); + } +} diff --git a/shared/hostCommands.ts b/shared/hostCommands.ts index 91d1bcc6d..701d2f7a5 100644 --- a/shared/hostCommands.ts +++ b/shared/hostCommands.ts @@ -153,6 +153,7 @@ export const HOST_COMMANDS = [ 'conversation_list_feedback', 'conversation_list_recent', 'conversation_output', + 'conversation_projects', 'conversation_rebind_session', 'conversation_relation_list', 'conversation_rename', @@ -174,7 +175,10 @@ export const HOST_COMMANDS = [ 'conversation_touch', 'conversation_truncate_to_turn', 'conversation_workspace_create', + 'conversation_workspace_diff', 'conversation_workspace_entries', + 'conversation_workspace_file', + 'conversation_workspace_tree', 'copy_item', 'crash_report_delete', 'crash_report_read', @@ -774,6 +778,7 @@ export const HOST_COMMAND_DESCRIPTORS = [ { name: 'conversation_list_feedback', scope: 'conversation.read', kind: 'core', argShape: 'compat' }, { name: 'conversation_list_recent', scope: 'conversation.read', kind: 'core', argShape: 'compat' }, { name: 'conversation_output', scope: 'conversation.read', kind: 'core', argShape: 'compat' }, + { name: 'conversation_projects', scope: 'conversation.read', kind: 'domain', argShape: 'compat' }, { name: 'conversation_rebind_session', scope: 'conversation.write', kind: 'domain', argShape: 'compat' }, { name: 'conversation_relation_list', scope: 'conversation.read', kind: 'core', argShape: 'compat' }, { name: 'conversation_rename', scope: 'conversation.write', kind: 'core', argShape: 'compat' }, @@ -795,7 +800,10 @@ export const HOST_COMMAND_DESCRIPTORS = [ { name: 'conversation_touch', scope: 'conversation.write', kind: 'domain', argShape: 'compat' }, { name: 'conversation_truncate_to_turn', scope: 'conversation.write', kind: 'domain', argShape: 'compat' }, { name: 'conversation_workspace_create', scope: 'conversation.write', kind: 'core', argShape: 'compat' }, + { name: 'conversation_workspace_diff', scope: 'artifact.read', kind: 'domain', argShape: 'compat' }, { name: 'conversation_workspace_entries', scope: 'conversation.write', kind: 'core', argShape: 'compat' }, + { name: 'conversation_workspace_file', scope: 'artifact.read', kind: 'domain', argShape: 'compat' }, + { name: 'conversation_workspace_tree', scope: 'artifact.read', kind: 'domain', argShape: 'compat' }, { name: 'copy_item', scope: 'application.call', kind: 'domain', argShape: 'compat' }, { name: 'crash_report_delete', scope: 'application.call', kind: 'domain', argShape: 'compat' }, { name: 'crash_report_read', scope: 'application.call', kind: 'domain', argShape: 'compat' },