diff --git a/AGENTS.md b/AGENTS.md index a31fe2b..3990b73 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -137,7 +137,7 @@ These are product rules, not implementation details. A change that breaks one ne **Machines** - Add Machine connects first: a Machine is kept only once `ssh localhost remote --stdio` works, otherwise the typed `MachineProblem` says why and what to do next. The SSH host field suggests the `Host`s of `~/.ssh/config`, read only. - A lost connection is made again on its own, after 1 s growing to 30 s, or at once when the computer wakes; a problem waiting won't fix (a host key, a sign-in that needs a prompt, no or an old localhost there, anything SSH says that localhost doesn't recognize) is shown once and waits for Reconnect. Reconnecting never starts or stops a Service. -- A Machine's Projects show below this computer's and act like them: Start, Stop, Restart, logs, Open in Browser. They are edited on the Machine. Open in Browser forwards the Port to the same port here first; if that port is taken here, it says so (`PortConflict`) rather than using another. +- A Machine's Projects show below this computer's and act like them: Start, Stop, Restart, logs, Open in Browser, and add, import, edit, remove and favourite through the same editors. Each change is made by the Machine's core (`Origin::Machine`), with its folders picked in localhost's own picker (`ListDirectory`) and scanned there; nothing of them, and no Secret typed here, is stored on this computer. While the Machine isn't connected the editors are disabled and say why; nothing is queued. An older localhost there answers `Unsupported`, and the app says to update it there. Open in Browser forwards the Port to the same port here first; if that port is taken here, it says so (`PortConflict`) rather than using another. - Quitting asks first when Services started from here on another Machine are active: that Machine stops them once the connection ends, unless localhost is open on it. **Detection** diff --git a/README.md b/README.md index 97eefcc..164e5e5 100644 --- a/README.md +++ b/README.md @@ -172,7 +172,7 @@ A dev box or home server you reach with `ssh` can be a **Machine**: its Projects 1. Check that `ssh devbox localhost --version` works from a terminal without asking anything (a key, in the SSH agent if it has a passphrase, and a host key you already trusted). It runs without your interactive profile: with zsh, put `localhost` on the `PATH` in `~/.zshenv`, not `~/.zshrc`. 2. Open **Settings → Machines → Add Machine…**. In **SSH host**, type a `Host` from `~/.ssh/config` (the field lists them), or `user@host:port`. localhost connects first, and says why and what to do if it can't. -3. The Machine's Projects show in the sidebar under its name, below this computer's: Start, Stop, Restart, logs. They are edited on the Machine. +3. The Machine's Projects show in the sidebar under its name, below this computer's: Start, Stop, Restart, logs, and add, import, edit or remove them there, with its folders picked and scanned on the Machine. 4. **Open in Browser** forwards the Service's Port to the same port here, through the SSH connection and on loopback only, then opens it. Any network `ssh` uses works: a LAN, a VPN, `ProxyJump`, Tailscale. Nothing new listens on either computer. A lost connection is made again on its own; Services you started from here stop on the Machine when the connection ends, unless localhost is open there. More in the [Machines docs](https://www.getlocalhost.app/docs/machines). diff --git a/apps/desktop/src-tauri/src/dialogs.rs b/apps/desktop/src-tauri/src/dialogs.rs index 969f34f..8b632fd 100644 --- a/apps/desktop/src-tauri/src/dialogs.rs +++ b/apps/desktop/src-tauri/src/dialogs.rs @@ -133,7 +133,7 @@ async fn pick(open: impl FnOnce(Box) + Send>)) -> Op /// `path` relative to `base`, e.g. `web` or `../shared`; `.` for `base` /// itself. `None` on another Windows drive or share, which no relative path reaches. -fn relative_path(path: &Path, base: &Path) -> Option { +pub(crate) fn relative_path(path: &Path, base: &Path) -> Option { let prefix = |path: &Path| match path.components().next() { Some(Component::Prefix(prefix)) => Some(prefix.as_os_str().to_string_lossy().to_lowercase()), _ => None, diff --git a/apps/desktop/src-tauri/src/editors.rs b/apps/desktop/src-tauri/src/editors.rs index 814c5c6..f8ae729 100644 --- a/apps/desktop/src-tauri/src/editors.rs +++ b/apps/desktop/src-tauri/src/editors.rs @@ -5,18 +5,17 @@ //! types (Keys, Ports, variables), so a mistake comes back in the core's //! words. Removing stops what is running first. -use std::collections::HashSet; - +use localhost_core::editing::{self, clashing, removed_by}; use localhost_core::{ - Id, Key, KeyClash, LocalhostError, NewService, Origin, ProfileChanges, Project, ProjectChanges, ProjectDocument, + Id, Key, KeyClash, LocalhostError, NewService, Origin, ProfileInput, Project, ProjectChanges, ProjectDocument, Service, ServiceChanges, ServiceSuggestion, VariableInput, VariableLayer, }; use serde::{Deserialize, Serialize}; use specta::Type; +use crate::AppState; use crate::bridge::{CommandError, CommandResult}; use crate::dialogs::ProjectFolder; -use crate::{AppState, Core}; const ORIGIN: Origin = Origin::MainWindow; @@ -57,7 +56,7 @@ impl From for VariableInput { } } -fn inputs(variables: Vec) -> Vec { +pub(crate) fn inputs(variables: Vec) -> Vec { variables.into_iter().map(VariableInput::from).collect() } @@ -102,6 +101,44 @@ pub struct ServiceEdit { run_before: String, } +impl ServiceEdit { + /// The Service to add, its variables, and its Dependencies. + pub(crate) fn new_service(self) -> Result<(NewService, Vec, Vec), CommandError> { + let new = NewService { + name: self.name, + key: parse_key(&self.key)?, + working_directory: self.working_directory, + command_line: self.command_line, + port: parse_port(&self.port, None)?, + url: Some(self.url), + port_can_change: self.port_can_change, + is_excluded_from_start_all: self.is_excluded_from_start_all, + dependency_keys: Vec::new(), + python_environment: Some(self.python_environment), + run_before: Some(self.run_before), + }; + Ok((new, inputs(self.variables), self.dependencies)) + } + + /// Every field of the editor, as changes to the Service. + pub(crate) fn changes(self) -> Result { + Ok(ServiceChanges { + name: Some(self.name), + key: Some(parse_key(&self.key)?), + working_directory: Some(self.working_directory), + command_line: Some(self.command_line), + variables: Some(inputs(self.variables)), + dependencies: Some(self.dependencies), + is_excluded_from_start_all: Some(self.is_excluded_from_start_all), + port: Some(parse_port(&self.port, None)?), + url: Some(Some(self.url)), + port_can_change: Some(self.port_can_change), + python_environment: Some(Some(self.python_environment)), + run_before: Some(Some(self.run_before)), + }) + } +} + /// One Environment Profile as edited; `profile_id` is `None` for a new one. #[derive(Clone, Debug, Deserialize, Type)] #[serde(rename_all = "camelCase")] @@ -111,6 +148,13 @@ pub struct ProfileEdit { variables: Vec, } +pub(crate) fn profile_inputs(profiles: Vec) -> Vec { + profiles + .into_iter() + .map(|edit| ProfileInput { profile_id: edit.profile_id, name: edit.name, variables: inputs(edit.variables) }) + .collect() +} + /// What a Service's editor needs to know about the others of its Project. #[derive(Debug, Serialize, Type)] #[serde(rename_all = "camelCase")] @@ -186,6 +230,15 @@ pub enum ImportChoice { Replace, } +impl From for KeyClash { + fn from(choice: ImportChoice) -> KeyClash { + match choice { + ImportChoice::KeepBoth => KeyClash::KeepBoth, + ImportChoice::Replace => KeyClash::Replace, + } + } +} + // MARK: Keys /// A Key derived from `name` that no other Project uses. @@ -247,13 +300,6 @@ pub async fn edit_project( folder: ProjectFolder, ) -> CommandResult { let core = state.core()?; - let project = core.library.project(project_id)?; - let moves = project.execution_target != folder.target; - if moves { - for service in &project.services { - core.targets.stop(service.id, ORIGIN).await?; - } - } let changes = ProjectChanges { name: Some(name), key: Some(parse_key(&key)?), @@ -261,12 +307,7 @@ pub async fn edit_project( execution_target: Some(folder.target), ..Default::default() }; - core.library.edit_project(project_id, changes, ORIGIN)?; - if moves { - for service in &project.services { - core.targets.remove_logs(&project.execution_target, service.id).await?; - } - } + editing::edit_project(&core.library, &core.targets, project_id, changes, ORIGIN).await?; Ok(()) } @@ -284,15 +325,7 @@ pub fn set_favorite(state: tauri::State<'_, AppState>, project_id: Id, is_favori #[specta::specta] pub async fn remove_project(state: tauri::State<'_, AppState>, project_id: Id) -> CommandResult { let core = state.core()?; - let project = core.library.project(project_id)?; - for service in &project.services { - core.targets.stop(service.id, ORIGIN).await?; - } - core.library.remove_project(project_id, ORIGIN)?; - for service in &project.services { - core.targets.remove_logs(&project.execution_target, service.id).await?; - } - Ok(()) + Ok(editing::remove_project(&core.library, &core.targets, project_id, ORIGIN).await?) } // MARK: Services @@ -300,41 +333,14 @@ pub async fn remove_project(state: tauri::State<'_, AppState>, project_id: Id) - #[tauri::command] #[specta::specta] pub fn add_service(state: tauri::State<'_, AppState>, project_id: Id, service: ServiceEdit) -> CommandResult { - let new = NewService { - name: service.name, - key: parse_key(&service.key)?, - working_directory: service.working_directory, - command_line: service.command_line, - port: parse_port(&service.port, None)?, - url: Some(service.url), - port_can_change: service.port_can_change, - is_excluded_from_start_all: service.is_excluded_from_start_all, - dependency_keys: Vec::new(), - python_environment: Some(service.python_environment), - run_before: Some(service.run_before), - }; - let library = &state.core()?.library; - Ok(library.add_service(project_id, new, inputs(service.variables), service.dependencies, ORIGIN)?) + let (new, variables, dependencies) = service.new_service()?; + Ok(state.core()?.library.add_service(project_id, new, variables, dependencies, ORIGIN)?) } #[tauri::command] #[specta::specta] pub fn edit_service(state: tauri::State<'_, AppState>, service_id: Id, service: ServiceEdit) -> CommandResult { - let changes = ServiceChanges { - name: Some(service.name), - key: Some(parse_key(&service.key)?), - working_directory: Some(service.working_directory), - command_line: Some(service.command_line), - variables: Some(inputs(service.variables)), - dependencies: Some(service.dependencies), - is_excluded_from_start_all: Some(service.is_excluded_from_start_all), - port: Some(parse_port(&service.port, None)?), - url: Some(Some(service.url)), - port_can_change: Some(service.port_can_change), - python_environment: Some(Some(service.python_environment)), - run_before: Some(Some(service.run_before)), - }; - state.core()?.library.edit_service(service_id, changes, ORIGIN)?; + state.core()?.library.edit_service(service_id, service.changes()?, ORIGIN)?; Ok(()) } @@ -362,11 +368,7 @@ pub fn add_services( #[specta::specta] pub async fn remove_service(state: tauri::State<'_, AppState>, service_id: Id) -> CommandResult { let core = state.core()?; - let (project, _) = core.library.service(service_id)?; - core.targets.stop(service_id, ORIGIN).await?; - core.library.remove_service(service_id, ORIGIN)?; - core.targets.remove_logs(&project.execution_target, service_id).await?; - Ok(()) + Ok(editing::remove_service(&core.library, &core.targets, service_id, ORIGIN).await?) } /// The Dependencies the Service can't have, and who depends on it. @@ -377,7 +379,7 @@ pub fn service_relations(state: tauri::State<'_, AppState>, service_id: Id) -> C Ok(relations(&project, service_id)) } -fn relations(project: &Project, service_id: Id) -> ServiceRelations { +pub(crate) fn relations(project: &Project, service_id: Id) -> ServiceRelations { let cycles = project .services .iter() @@ -462,29 +464,8 @@ pub fn save_environment( active: Option, ) -> CommandResult { let library = &state.core()?.library; - let project = library.project(project_id)?; - let changes = ProjectChanges { variables: Some(inputs(variables)), ..Default::default() }; - library.edit_project(project_id, changes, ORIGIN)?; - let kept: HashSet = profiles.iter().filter_map(|profile| profile.profile_id).collect(); - for profile in project.profiles.iter().filter(|profile| !kept.contains(&profile.id)) { - library.remove_profile(profile.id, ORIGIN)?; - } - let mut active_id = None; - for (index, edit) in profiles.into_iter().enumerate() { - let variables = inputs(edit.variables); - let id = match edit.profile_id { - Some(id) => { - let changes = ProfileChanges { name: Some(edit.name), variables: Some(variables) }; - library.edit_profile(id, changes, ORIGIN)?.id - } - None => library.add_profile(project_id, &edit.name, variables, ORIGIN)?.id, - }; - if active == Some(index as u32) { - active_id = Some(id); - } - } - library.set_active_profile(active_id, project_id, ORIGIN)?; - Ok(()) + let (variables, profiles) = (inputs(variables), profile_inputs(profiles)); + Ok(editing::save_environment(library, project_id, variables, profiles, active, ORIGIN)?) } #[tauri::command] @@ -513,7 +494,10 @@ pub fn secret_value( pub fn read_project_file(state: tauri::State<'_, AppState>, file: String) -> CommandResult { let core = state.core()?; let document = read_document(&file)?; - Ok(preview(core, &document, file_name(&file))) + let folder = ProjectFolder { target: document.execution_target().clone(), path: document.path().to_string() }; + let folder_exists = folder.exists(); + let is_active = |id: Id| core.targets.status(id).state.is_active(); + Ok(preview(&core.library.projects(), is_active, &document, file_name(&file), folder, folder_exists)) } /// Imports the Project file into `folder`. On Replace, Services the file no @@ -531,33 +515,8 @@ pub async fn import_project( let mut document = read_document(&file)?; document.set_path(folder.path); document.set_execution_target(folder.target); - let on_key_clash = choice.map(|choice| match choice { - ImportChoice::KeepBoth => KeyClash::KeepBoth, - ImportChoice::Replace => KeyClash::Replace, - }); - let replaced = match on_key_clash { - Some(KeyClash::Replace) => clashing(core, &document), - _ => None, - }; - let moves = |existing: &Project| existing.execution_target != *document.execution_target(); - if let Some(existing) = &replaced { - let stopped: Vec<&Service> = if moves(existing) { - existing.services.iter().collect() - } else { - removed_by(existing, &document).collect() - }; - for service in stopped { - core.targets.stop(service.id, ORIGIN).await?; - } - } - let project = core.library.import_project(&document, on_key_clash, ORIGIN)?; - if let Some(existing) = &replaced { - let gone = |service: &&Service| moves(existing) || project.service(service.id).is_none(); - for service in existing.services.iter().filter(gone) { - core.targets.remove_logs(&existing.execution_target, service.id).await?; - } - } - Ok(project) + let on_key_clash = choice.map(KeyClash::from); + Ok(editing::import_project(&core.library, &core.targets, &document, on_key_clash, ORIGIN).await?) } /// Writes the Project's file to `file`. @@ -576,27 +535,26 @@ fn read_document(file: &str) -> Result { ProjectDocument::from_yaml(&text) } -fn file_name(file: &str) -> String { +pub(crate) fn file_name(file: &str) -> String { std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |name| name.to_string_lossy().into_owned()) } -fn clashing(core: &Core, document: &ProjectDocument) -> Option { - core.library.projects().into_iter().find(|project| project.key == *document.key()) -} - -/// The existing Project's Services that the file doesn't have. -fn removed_by<'a>(existing: &'a Project, document: &ProjectDocument) -> impl Iterator { - let kept: HashSet = document.services().iter().map(|service| service.key.clone()).collect(); - existing.services.iter().filter(move |service| !kept.contains(&service.key)) -} - -fn preview(core: &Core, document: &ProjectDocument, file_name: String) -> ImportPreview { - let clash = clashing(core, document).map(|existing| ImportClash { +/// The review of an import among `projects` (this computer's, or a +/// Machine's), whose active Services `is_active` says. +pub(crate) fn preview( + projects: &[Project], + is_active: impl Fn(Id) -> bool, + document: &ProjectDocument, + file_name: String, + folder: ProjectFolder, + folder_exists: bool, +) -> ImportPreview { + let clash = clashing(projects, document).map(|existing| ImportClash { project_name: existing.name.clone(), - free_key: core.library.free_project_key(document.key()), + free_key: localhost_core::free_project_key(projects, document.key()), removed: removed_by(&existing, document) .map(|service| { - if core.targets.status(service.id).state.is_active() { + if is_active(service.id) { format!("{} (running, stopped first)", service.name) } else { service.name.clone() @@ -631,12 +589,11 @@ fn preview(core: &Core, document: &ProjectDocument, file_name: String) -> Import profile.variables.secret_names.iter().map(|name| secret(name, format!("profile {}", profile.name))) })) .collect(); - let folder = ProjectFolder { target: document.execution_target().clone(), path: document.path().to_string() }; ImportPreview { file_name, name: document.name().to_string(), key: document.key().clone(), - folder_exists: folder.exists(), + folder_exists, folder, services, environment: environment_summary(document), @@ -673,7 +630,7 @@ fn environment_summary(document: &ProjectDocument) -> Option { // MARK: Parsing -fn parse_key(raw: &str) -> Result { +pub(crate) fn parse_key(raw: &str) -> Result { Key::new(raw.trim()) } @@ -693,7 +650,7 @@ fn parse_port(raw: &str, service: Option<&str>) -> Result, CommandEr }) } -fn new_services(edits: Vec) -> Result, CommandError> { +pub(crate) fn new_services(edits: Vec) -> Result, CommandError> { edits .into_iter() .map(|edit| { @@ -716,6 +673,7 @@ mod tests { use localhost_core::MemorySecretStore; use super::*; + use crate::Core; fn core() -> (Core, std::path::PathBuf) { let root = std::env::temp_dir().join(format!("localhost-editors-{}-{}", std::process::id(), Id::new())); @@ -806,7 +764,9 @@ mod tests { .add_services(new_services(vec![suggestion("Docs", "docs", "")]).unwrap(), project.id, ORIGIN) .unwrap(); - let preview = preview(&core, &document, "shop.yaml".into()); + let folder = ProjectFolder { target: document.execution_target().clone(), path: document.path().to_string() }; + let is_active = |id| core.targets.status(id).state.is_active(); + let preview = preview(&core.library.projects(), is_active, &document, "shop.yaml".into(), folder, false); assert!(!preview.folder_exists); assert_eq!(preview.services.len(), 1); assert_eq!(preview.environment.as_deref(), Some("1 project variable · profile Testing")); diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 83811fd..191fdef 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -15,6 +15,7 @@ mod launch; mod lifecycle; mod listeners; mod logs; +mod machine_editors; mod machines; mod palette; mod perf; @@ -191,6 +192,27 @@ fn specta_builder() -> tauri_specta::Builder { machines::machine_start_all, machines::machine_stop_all, machines::machine_open_service, + machine_editors::machine_list_directory, + machine_editors::relative_folder, + machine_editors::machine_suggested_project_key, + machine_editors::machine_suggested_service_key, + machine_editors::machine_add_project, + machine_editors::machine_edit_project, + machine_editors::machine_set_favorite, + machine_editors::machine_remove_project, + machine_editors::machine_add_service, + machine_editors::machine_edit_service, + machine_editors::machine_add_services, + machine_editors::machine_remove_service, + machine_editors::machine_service_relations, + machine_editors::machine_scan_folder, + machine_editors::machine_scan_project, + machine_editors::machine_detect_python_environment, + machine_editors::machine_save_environment, + machine_editors::machine_set_active_profile, + machine_editors::machine_secret_value, + machine_editors::machine_read_project_file, + machine_editors::machine_import_project, ]) .events(collect_events![lifecycle::Reveal, launch::OrphansFound, updates::UpdateState]) } diff --git a/apps/desktop/src-tauri/src/machine_editors.rs b/apps/desktop/src-tauri/src/machine_editors.rs new file mode 100644 index 0000000..e2defb8 --- /dev/null +++ b/apps/desktop/src-tauri/src/machine_editors.rs @@ -0,0 +1,322 @@ +//! The editors, on another Machine: the same sheets as for this computer's +//! Projects (`editors`), whose changes are made on the Machine, as +//! `Origin::Machine`. Its folders are browsed with `machine_list_directory`, +//! since no system dialog here can. What changed comes back with the +//! Machine's Projects (`machines`); nothing of it is kept here, and a +//! Secret typed here goes to the Machine's secret store only. +//! +//! An older localhost there refuses with `MachineNeedsUpdate`, and a lost +//! connection with `MachineUnavailable`: nothing waits to be sent later. + +use localhost_core::machine::Machines; +use localhost_core::{ + DirectoryListing, ExecutionTarget, Id, Key, LocalhostError, Project, ProjectChanges, ProjectDocument, Service, + ServiceStatus, ServiceSuggestion, VariableLayer, +}; + +use crate::AppState; +use crate::bridge::CommandResult; +use crate::dialogs::ProjectFolder; +use crate::editors::{ + ImportChoice, ImportPreview, ProfileEdit, ServiceEdit, ServiceRelations, SuggestionEdit, VariableEdit, file_name, + inputs, new_services, parse_key, preview, profile_inputs, relations, +}; + +/// The Machine's Projects, as last read from it. +fn projects(machines: &Machines, machine_id: Id) -> Result, LocalhostError> { + machines.projects(machine_id) +} + +fn project(machines: &Machines, machine_id: Id, project_id: Id) -> Result { + projects(machines, machine_id)? + .into_iter() + .find(|project| project.id == project_id) + .ok_or(LocalhostError::ProjectNotFound(project_id)) +} + +/// A folder of the Machine, for the folder picker: its folders, and with +/// `include_files` its files. `None` is the home folder there. +#[tauri::command] +#[specta::specta] +pub async fn machine_list_directory( + state: tauri::State<'_, AppState>, + machine_id: Id, + path: Option, + show_hidden: bool, + include_files: bool, +) -> CommandResult { + Ok(state.machines()?.list_directory(machine_id, path, show_hidden, include_files).await?) +} + +/// `path` relative to the Project's folder `base`, e.g. `web` or +/// `../shared`, for a working directory picked on a Machine. +#[tauri::command] +#[specta::specta] +pub fn relative_folder(path: String, base: String) -> Option { + crate::dialogs::relative_path(std::path::Path::new(&path), std::path::Path::new(&base)) +} + +#[tauri::command] +#[specta::specta] +pub fn machine_suggested_project_key( + state: tauri::State<'_, AppState>, + machine_id: Id, + name: String, + excluding: Option, +) -> CommandResult { + let projects = projects(state.machines()?, machine_id)?; + Ok(localhost_core::suggested_project_key(&projects, &name, excluding)) +} + +#[tauri::command] +#[specta::specta] +pub fn machine_suggested_service_key( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, + name: String, + excluding: Option, +) -> CommandResult { + Ok(project(state.machines()?, machine_id, project_id)?.suggested_service_key(&name, excluding)) +} + +// MARK: Projects + +/// Adds a Project in the Machine's folder `path`, with the reviewed +/// Suggestions as its first Services. +#[tauri::command] +#[specta::specta] +pub async fn machine_add_project( + state: tauri::State<'_, AppState>, + machine_id: Id, + name: String, + key: String, + path: String, + services: Vec, +) -> CommandResult { + let services = new_services(services)?; + Ok(state.machines()?.add_project(machine_id, name, parse_key(&key)?, path, services).await?) +} + +#[tauri::command] +#[specta::specta] +pub async fn machine_edit_project( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, + name: String, + key: String, + path: String, +) -> CommandResult { + let changes = + ProjectChanges { name: Some(name), key: Some(parse_key(&key)?), path: Some(path), ..Default::default() }; + state.machines()?.edit_project(machine_id, project_id, changes).await?; + Ok(()) +} + +#[tauri::command] +#[specta::specta] +pub async fn machine_set_favorite( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, + is_favorite: bool, +) -> CommandResult { + let changes = ProjectChanges { is_favorite: Some(is_favorite), ..Default::default() }; + state.machines()?.edit_project(machine_id, project_id, changes).await?; + Ok(()) +} + +/// Stops the Project's Services there, then removes it and their logs. Its +/// folder is not touched. +#[tauri::command] +#[specta::specta] +pub async fn machine_remove_project( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, +) -> CommandResult { + Ok(state.machines()?.remove_project(machine_id, project_id).await?) +} + +// MARK: Services + +#[tauri::command] +#[specta::specta] +pub async fn machine_add_service( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, + service: ServiceEdit, +) -> CommandResult { + let (new, variables, dependencies) = service.new_service()?; + Ok(state.machines()?.add_service(machine_id, project_id, new, variables, dependencies).await?) +} + +#[tauri::command] +#[specta::specta] +pub async fn machine_edit_service( + state: tauri::State<'_, AppState>, + machine_id: Id, + service_id: Id, + service: ServiceEdit, +) -> CommandResult { + state.machines()?.edit_service(machine_id, service_id, service.changes()?).await?; + Ok(()) +} + +#[tauri::command] +#[specta::specta] +pub async fn machine_add_services( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, + services: Vec, +) -> CommandResult> { + let services = new_services(services)?; + Ok(state.machines()?.add_services(machine_id, project_id, services).await?) +} + +/// Stops the Service there, then removes it and its logs. +#[tauri::command] +#[specta::specta] +pub async fn machine_remove_service( + state: tauri::State<'_, AppState>, + machine_id: Id, + service_id: Id, +) -> CommandResult { + Ok(state.machines()?.remove_service(machine_id, service_id).await?) +} + +/// The Dependencies the Service can't have, and who depends on it. +#[tauri::command] +#[specta::specta] +pub fn machine_service_relations( + state: tauri::State<'_, AppState>, + machine_id: Id, + service_id: Id, +) -> CommandResult { + let projects = projects(state.machines()?, machine_id)?; + let project = projects + .iter() + .find(|project| project.service(service_id).is_some()) + .ok_or(LocalhostError::ServiceNotFound(service_id))?; + Ok(relations(project, service_id)) +} + +// MARK: Detection + +/// Suggestions for a folder of the Machine, scanned there. +#[tauri::command] +#[specta::specta] +pub async fn machine_scan_folder( + state: tauri::State<'_, AppState>, + machine_id: Id, + path: String, +) -> CommandResult> { + Ok(state.machines()?.scan_folder(machine_id, path).await?) +} + +#[tauri::command] +#[specta::specta] +pub async fn machine_scan_project( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, +) -> CommandResult> { + Ok(state.machines()?.scan_project(machine_id, project_id).await?) +} + +#[tauri::command] +#[specta::specta] +pub async fn machine_detect_python_environment( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, + working_directory: String, + command_line: String, +) -> CommandResult> { + let machines = state.machines()?; + Ok(machines.detect_python_environment(machine_id, project_id, working_directory, command_line).await?) +} + +// MARK: Environment + +#[tauri::command] +#[specta::specta] +pub async fn machine_save_environment( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, + variables: Vec, + profiles: Vec, + active: Option, +) -> CommandResult { + let (variables, profiles) = (inputs(variables), profile_inputs(profiles)); + Ok(state.machines()?.save_environment(machine_id, project_id, variables, profiles, active).await?) +} + +#[tauri::command] +#[specta::specta] +pub async fn machine_set_active_profile( + state: tauri::State<'_, AppState>, + machine_id: Id, + project_id: Id, + profile_id: Option, +) -> CommandResult { + Ok(state.machines()?.set_active_profile(machine_id, project_id, profile_id).await?) +} + +/// A Secret's value there, to reveal it in the editor. Not kept here. +#[tauri::command] +#[specta::specta] +pub async fn machine_secret_value( + state: tauri::State<'_, AppState>, + machine_id: Id, + name: String, + layer: VariableLayer, +) -> CommandResult> { + Ok(state.machines()?.secret_value(machine_id, name, layer).await?) +} + +// MARK: Import + +/// Reads a Project file of the Machine for the import's review, among the +/// Machine's Projects. +#[tauri::command] +#[specta::specta] +pub async fn machine_read_project_file( + state: tauri::State<'_, AppState>, + machine_id: Id, + file: String, +) -> CommandResult { + let machines = state.machines()?; + let read = machines.read_project_file(machine_id, file.clone()).await?; + let document = ProjectDocument::from_yaml(&read.text)?; + let folder = ProjectFolder { target: ExecutionTarget::ThisMachine, path: document.path().to_string() }; + let (snapshots, _) = machines.subscribe(); + let statuses: Vec = snapshots + .into_iter() + .find(|snapshot| snapshot.machine.id == machine_id) + .map(|snapshot| snapshot.statuses) + .unwrap_or_default(); + let is_active = |id: Id| statuses.iter().any(|status| status.service_id == id && status.state.is_active()); + let projects = projects(machines, machine_id)?; + Ok(preview(&projects, is_active, &document, file_name(&file), folder, read.folder_exists)) +} + +/// Imports the Machine's Project file into its folder `path` there, read +/// again as Import is pressed. +#[tauri::command] +#[specta::specta] +pub async fn machine_import_project( + state: tauri::State<'_, AppState>, + machine_id: Id, + file: String, + path: String, + choice: Option, +) -> CommandResult { + let machines = state.machines()?; + let read = machines.read_project_file(machine_id, file).await?; + Ok(machines.import_project(machine_id, read.text, path, choice.map(Into::into)).await?) +} diff --git a/apps/desktop/src-tauri/src/machines.rs b/apps/desktop/src-tauri/src/machines.rs index 0bec693..d233ec0 100644 --- a/apps/desktop/src-tauri/src/machines.rs +++ b/apps/desktop/src-tauri/src/machines.rs @@ -28,6 +28,9 @@ pub struct MachineView { is_connected: bool, /// It waits for the user to connect it again. needs_user: bool, + /// Why its Projects can't be added, edited or removed now: it isn't + /// connected, or its localhost is too old. `None` when they can. + edit_problem: Option, projects: Vec, statuses: Vec, project_states: Vec, @@ -66,6 +69,7 @@ impl Shown { summary: self.state.summary(&self.machine.name), is_connected: matches!(self.state, MachineState::Connected { .. }), needs_user: self.state.needs_user(), + edit_problem: edit_problem(&self.state, &self.machine.name), machine: self.machine.clone(), state: self.state.clone(), projects: self.view.projects.clone(), @@ -75,6 +79,17 @@ impl Shown { } } +/// Why the Machine's Projects can't be changed from here now, if they can't. +fn edit_problem(state: &MachineState, machine: &str) -> Option { + match state { + MachineState::Connected { manages_projects: true, .. } => None, + MachineState::Connected { manages_projects: false, .. } => { + Some(LocalhostError::MachineNeedsUpdate { machine: machine.to_string() }.message()) + } + other => Some(other.summary(machine)), + } +} + /// The Machines as they are, then every change over `events` until the /// window goes away. #[tauri::command] @@ -302,14 +317,20 @@ mod tests { let sent = apply(&mut shown, MachinesEvent::MachinesChanged { machines: vec![devbox.clone()] }); let [MachineEvent::Machines { machines }] = sent.as_slice() else { panic!("not every Machine") }; assert_eq!((machines[0].summary.as_str(), machines[0].needs_user), ("Not connected", true)); + assert_eq!(machines[0].edit_problem.as_deref(), Some("Not connected")); let project = project(); let web = project.services[0].clone(); apply(&mut shown, MachinesEvent::ProjectsChanged { machine_id: devbox.id, projects: vec![project.clone()] }); - let state = MachineState::Connected { version: "0.5.0".into() }; + let state = MachineState::Connected { version: "0.5.6".into(), manages_projects: false }; + let sent = apply(&mut shown, MachinesEvent::StateChanged { machine_id: devbox.id, state }); + let [MachineEvent::Machines { machines }] = sent.as_slice() else { panic!("not every Machine") }; + assert_eq!(machines[0].edit_problem.as_deref(), Some("Update localhost on devbox to manage its Projects.")); + let state = MachineState::Connected { version: "0.5.7".into(), manages_projects: true }; let sent = apply(&mut shown, MachinesEvent::StateChanged { machine_id: devbox.id, state }); let [MachineEvent::Machines { machines }] = sent.as_slice() else { panic!("not every Machine") }; assert!(machines[0].is_connected); + assert_eq!(machines[0].edit_problem, None); assert_eq!(machines[0].project_states[0].state, Some(ServiceState::Stopped)); let mut status = ServiceStatus::never_run(web.id); diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index cc40208..bf5405f 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -9,7 +9,7 @@ import { Sheets } from "./components/Sheets"; import { FolderIcon, LinesIcon } from "./components/Icons"; import { LogPane } from "./components/LogPane"; import { PortsView } from "./components/PortsView"; -import { type Place, ProjectActions, ServicesColumn, thisComputer } from "./components/ServicesColumn"; +import { machinePlace, type Place, ProjectActions, ServicesColumn, thisComputer } from "./components/ServicesColumn"; import { Sidebar } from "./components/Sidebar"; import { Toolbar } from "./components/Toolbar"; import { importProject } from "./editors"; @@ -84,8 +84,7 @@ function MainWindow({ view }: { view: CoreView }) { const onMachine = sidebarSelection?.kind === "machineProject" ? sidebarSelection : null; const machine = onMachine ? machines.find((shown) => shown.machine.id === onMachine.machineId) : undefined; const machineProject = machine?.view.projects.find((project) => project.id === onMachine?.projectId); - const place: Place = - machine && machineProject ? { machineId: machine.machine.id, isReachable: machine.isConnected } : thisComputer; + const place: Place = machine && machineProject ? machinePlace(machine) : thisComputer; const selectedView = machine && machineProject ? machine.view : view; const selected = isPorts ? undefined @@ -204,10 +203,26 @@ function MainWindow({ view }: { view: CoreView }) { )} - + + onMachine ? select({ kind: "machineProject", machineId: onMachine.id, projectId }) : navigator.selectProject(projectId) + } + onSelectService={(projectId, serviceId, onMachine) => { + if (!onMachine) return navigator.selectService(projectId, serviceId); + setSidebarSelection({ kind: "machineProject", machineId: onMachine.id, projectId }); + setSelection({ kind: "service", serviceId }); + }} + /> {isPaletteOpen && ( - // Another Machine's Projects are controlled from the window for now. - + )} diff --git a/apps/desktop/src/bindings.ts b/apps/desktop/src/bindings.ts index ed99789..f1b714d 100644 --- a/apps/desktop/src/bindings.ts +++ b/apps/desktop/src/bindings.ts @@ -759,6 +759,205 @@ async machineOpenService(machineId: Id, serviceId: Id) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_list_directory", { machineId, path, showHidden, includeFiles }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * `path` relative to the Project's folder `base`, e.g. `web` or + * `../shared`, for a working directory picked on a Machine. + */ +async relativeFolder(path: string, base: string) : Promise { + return await TAURI_INVOKE("relative_folder", { path, base }); +}, +async machineSuggestedProjectKey(machineId: Id, name: string, excluding: Id | null) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_suggested_project_key", { machineId, name, excluding }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineSuggestedServiceKey(machineId: Id, projectId: Id, name: string, excluding: Id | null) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_suggested_service_key", { machineId, projectId, name, excluding }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * Adds a Project in the Machine's folder `path`, with the reviewed + * Suggestions as its first Services. + */ +async machineAddProject(machineId: Id, name: string, key: string, path: string, services: SuggestionEdit[]) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_add_project", { machineId, name, key, path, services }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineEditProject(machineId: Id, projectId: Id, name: string, key: string, path: string) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_edit_project", { machineId, projectId, name, key, path }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineSetFavorite(machineId: Id, projectId: Id, isFavorite: boolean) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_set_favorite", { machineId, projectId, isFavorite }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * Stops the Project's Services there, then removes it and their logs. Its + * folder is not touched. + */ +async machineRemoveProject(machineId: Id, projectId: Id) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_remove_project", { machineId, projectId }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineAddService(machineId: Id, projectId: Id, service: ServiceEdit) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_add_service", { machineId, projectId, service }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineEditService(machineId: Id, serviceId: Id, service: ServiceEdit) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_edit_service", { machineId, serviceId, service }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineAddServices(machineId: Id, projectId: Id, services: SuggestionEdit[]) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_add_services", { machineId, projectId, services }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * Stops the Service there, then removes it and its logs. + */ +async machineRemoveService(machineId: Id, serviceId: Id) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_remove_service", { machineId, serviceId }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * The Dependencies the Service can't have, and who depends on it. + */ +async machineServiceRelations(machineId: Id, serviceId: Id) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_service_relations", { machineId, serviceId }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * Suggestions for a folder of the Machine, scanned there. + */ +async machineScanFolder(machineId: Id, path: string) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_scan_folder", { machineId, path }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineScanProject(machineId: Id, projectId: Id) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_scan_project", { machineId, projectId }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineDetectPythonEnvironment(machineId: Id, projectId: Id, workingDirectory: string, commandLine: string) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_detect_python_environment", { machineId, projectId, workingDirectory, commandLine }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineSaveEnvironment(machineId: Id, projectId: Id, variables: VariableEdit[], profiles: ProfileEdit[], active: number | null) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_save_environment", { machineId, projectId, variables, profiles, active }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +async machineSetActiveProfile(machineId: Id, projectId: Id, profileId: Id | null) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_set_active_profile", { machineId, projectId, profileId }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * A Secret's value there, to reveal it in the editor. Not kept here. + */ +async machineSecretValue(machineId: Id, name: string, layer: VariableLayer) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_secret_value", { machineId, name, layer }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * Reads a Project file of the Machine for the import's review, among the + * Machine's Projects. + */ +async machineReadProjectFile(machineId: Id, file: string) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_read_project_file", { machineId, file }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} +}, +/** + * Imports the Machine's Project file into its folder `path` there, read + * again as Import is pressed. + */ +async machineImportProject(machineId: Id, file: string, path: string, choice: ImportChoice | null) : Promise> { + try { + return { status: "ok", data: await TAURI_INVOKE("machine_import_project", { machineId, file, path, choice }) }; +} catch (e) { + if(e instanceof Error) throw e; + else return { status: "error", error: e as any }; +} } } @@ -922,6 +1121,27 @@ export type CoreEvent = { kind: "library"; event: ProjectLibraryEvent } | */ { kind: "projectState"; event: ProjectState } export type Cycle = { serviceId: Id; message: string } +export type DirectoryEntry = { name: string; isDirectory: boolean } +/** + * A folder as a picker shows it: where it is, its parent, and what it holds. + */ +export type DirectoryListing = { +/** + * Absolute and standardized. + */ +path: string; +/** + * `None` at the root. + */ +parent: string | null; +/** + * The user's home folder, where a picker starts. + */ +home: string; +/** + * Folders first, then files; each sorted by name, ignoring case. + */ +entries: DirectoryEntry[] } /** * A named set of environment variables for a Project (e.g. Development, * Testing) applying to all its Services; at most one is active at a time. @@ -1223,7 +1443,16 @@ export type LocalhostError = { kind: "invalidKey"; detail: string } | { kind: "i /** * The other end runs an older localhost, which can't do this. */ -{ kind: "unsupported" } +{ kind: "unsupported" } | +/** + * The Machine (by name) runs a localhost too old to change its + * Projects from here; they can still be viewed and run. + */ +{ kind: "machineNeedsUpdate"; detail: { machine: string } } | +/** + * A folder exists but can't be listed: the system's reason. + */ +{ kind: "folderUnreadable"; detail: { path: string; reason: string } } export type LogBatch = { lines: LogLine[]; /** * Lines that arrived but were left out because the batch kept only its @@ -1341,9 +1570,11 @@ export type MachineProblem = */ export type MachineState = { kind: "notConnected" } | { kind: "connecting" } | /** - * Connected to the localhost of this version there. + * Connected to the localhost of this version there. Without + * `manages_projects`, it is too old for its Projects to be changed from + * here: they are shown and run only. */ -{ kind: "connected"; detail: { version: string } } | +{ kind: "connected"; detail: { version: string; managesProjects?: boolean } } | /** * Not connected, for this reason. `is_retrying`: another attempt comes * on its own. @@ -1361,7 +1592,12 @@ summary: string; isConnected: boolean; /** * It waits for the user to connect it again. */ -needsUser: boolean; projects: Project[]; statuses: StatusView[]; projectStates: ProjectState[] } +needsUser: boolean; +/** + * Why its Projects can't be added, edited or removed now: it isn't + * connected, or its localhost is too old. `None` when they can. + */ +editProblem: string | null; projects: Project[]; statuses: StatusView[]; projectStates: ProjectState[] } /** * Where the user is in the first run: whether the welcome was finished * or skipped, whether the Get started checklist is over (dismissed, diff --git a/apps/desktop/src/components/Alerts.tsx b/apps/desktop/src/components/Alerts.tsx index 142d969..6652db1 100644 --- a/apps/desktop/src/components/Alerts.tsx +++ b/apps/desktop/src/components/Alerts.tsx @@ -10,6 +10,7 @@ import type { BlockedStart } from "../bindings"; import { removeProject, removeService } from "../editors"; import { type CoreView, findService } from "../core"; import { processDescription } from "../listeners"; +import { currentMachines } from "../machines"; import { formatList } from "../status"; import { isNativeWindows } from "../targets"; import { type Alert, alertKey, dismissAlert, useUi } from "../ui"; @@ -171,14 +172,19 @@ function AlertDialog({ alert, view }: { alert: Alert; view: CoreView }) { case "removeProject": case "removeService": { + const machineId = alert.machine?.id ?? null; + const shown = machineId ? currentMachines().find((one) => one.machine.id === machineId)?.view : view; const name = alert.kind === "removeProject" - ? view.projects.find((project) => project.id === alert.projectId)?.name + ? shown?.projects.find((project) => project.id === alert.projectId)?.name : (() => { - const found = findService(view, alert.serviceId); + const found = shown && findService(shown, alert.serviceId); return found?.project.services[found.index].name; })(); - const remove = alert.kind === "removeProject" ? () => removeProject(alert.projectId) : () => removeService(alert.serviceId); + const remove = + alert.kind === "removeProject" + ? () => removeProject(alert.projectId, machineId) + : () => removeService(alert.serviceId, machineId); return ( ): string[] { const paragraphs = [ - "Running services are stopped first. Their configuration is deleted; the project folder is not touched.", + alert.machine + ? `Running services are stopped first, on ${alert.machine.name}. Their configuration is deleted there; the project folder is not touched.` + : "Running services are stopped first. Their configuration is deleted; the project folder is not touched.", ]; if (alert.kind === "removeService" && alert.dependents.length > 0) { paragraphs.push(`${formatList(alert.dependents.map((name) => `“${name}”`))} will no longer depend on it.`); diff --git a/apps/desktop/src/components/CommandPalette.tsx b/apps/desktop/src/components/CommandPalette.tsx index 8d1a23f..56cddf7 100644 --- a/apps/desktop/src/components/CommandPalette.tsx +++ b/apps/desktop/src/components/CommandPalette.tsx @@ -2,7 +2,16 @@ import { type CSSProperties, useEffect, useId, useMemo, useRef, useState } from import type { Project } from "../bindings"; import type { CoreView } from "../core"; import { focusColumn } from "../keyboard"; -import { emptyQueryResults, type Navigator, type PaletteIcon, type PaletteItem, paletteItems, rankItems } from "../palette"; +import type { ShownMachine } from "../machines"; +import { + emptyQueryResults, + machinePaletteItems, + type Navigator, + type PaletteIcon, + type PaletteItem, + paletteItems, + rankItems, +} from "../palette"; import type { ServiceSelection } from "../selection"; import { setPaletteOpen } from "../ui"; import { @@ -25,9 +34,13 @@ import styles from "./CommandPalette.module.css"; type Props = { view: CoreView; + /** The selected Project of this computer; none while another Machine's is. */ selected: Project | undefined; selection: ServiceSelection; navigator: Navigator; + /** Other Machines, and the selected Project when it is one of theirs. */ + machines?: ShownMachine[]; + onMachine?: { machine: ShownMachine; project: Project } | null; }; /** @@ -35,9 +48,15 @@ type Props = { * and action. ↑/↓ (or Ctrl+P/Ctrl+N) move, ↩ runs, Escape or a click outside * closes, and focus goes back where it was. */ -export function CommandPalette({ view, selected, selection, navigator }: Props) { +/** No other Machines, the same array each render so the items aren't rebuilt. */ +const NO_MACHINES: ShownMachine[] = []; + +export function CommandPalette({ view, selected, selection, navigator, machines = NO_MACHINES, onMachine = null }: Props) { const [query, setQuery] = useState(""); - const items = useMemo(() => paletteItems(view, selected, selection, navigator), [view, selected, selection, navigator]); + const items = useMemo(() => { + const { first, rest } = machinePaletteItems(machines, onMachine && { ...onMachine, selection }); + return [...first, ...paletteItems(view, selected, selection, navigator), ...rest]; + }, [view, selected, selection, navigator, machines, onMachine]); const [results, setResults] = useState(() => emptyQueryResults(items)); const [selectedId, setSelectedId] = useState(() => results[0]?.id ?? null); const listId = useId(); diff --git a/apps/desktop/src/components/EnvironmentForm.tsx b/apps/desktop/src/components/EnvironmentForm.tsx index fd48940..6e11839 100644 --- a/apps/desktop/src/components/EnvironmentForm.tsx +++ b/apps/desktop/src/components/EnvironmentForm.tsx @@ -1,8 +1,9 @@ import { type Dispatch, type SetStateAction, useState } from "react"; -import { commands, type Id, type Project } from "../bindings"; +import type { Id, Project } from "../bindings"; +import { editorCommands, type MachineRef } from "../editing"; import { type VariableDraft, variableDrafts, variableEdits } from "../editors"; import { closeSheet } from "../ui"; -import { ChipList, ChipToggle, Field, FieldHint, FieldLabel, FormSheet } from "./Form"; +import { ChipList, ChipToggle, Field, FieldHint, FieldLabel, FormSheet, ProjectContext } from "./Form"; import { LayersIcon, PlusIcon, TrashIcon } from "./Icons"; import { VariableEditor } from "./VariableEditor"; import styles from "./EnvironmentForm.module.css"; @@ -13,7 +14,7 @@ type ProfileDraft = { id: number; profileId: Id | null; name: string; variables: let nextProfileId = 0; /** Edits a Project's variables and its Environment Profiles, and which Profile is active. */ -export function EnvironmentForm({ project }: { project: Project }) { +export function EnvironmentForm({ project, machine }: { project: Project; machine?: MachineRef }) { const [variables, setVariables] = useState(() => variableDrafts(project.variables)); const [profiles, setProfiles] = useState(() => (project.profiles ?? []).map((profile) => ({ @@ -56,7 +57,7 @@ export function EnvironmentForm({ project }: { project: Project }) { setIsSaving(true); setError(null); const active = profiles.findIndex((profile) => profile.id === activeId); - const result = await commands.saveEnvironment( + const result = await editorCommands(machine ?? null).saveEnvironment( project.id, variableEdits(variables), profiles.map((profile) => ({ @@ -76,9 +77,13 @@ export function EnvironmentForm({ project }: { project: Project }) { icon={} title="Environment" subtitle={ - <> - for {project.name} - + machine ? ( + + ) : ( + <> + for {project.name} + + ) } hint="Running services show “restart to apply” when their environment changes." error={error} @@ -95,6 +100,7 @@ export function EnvironmentForm({ project }: { project: Project }) { setVariables={setVariables} layer={{ kind: "project", id: project.id }} label="Project variables" + machine={machine} /> )} @@ -171,6 +177,7 @@ export function EnvironmentForm({ project }: { project: Project }) { setVariables={profileVariables(profile.id)} layer={profile.profileId ? { kind: "profile", id: profile.profileId } : null} label={`Variables of ${profile.name || "the profile"}`} + machine={machine} /> ))} diff --git a/apps/desktop/src/components/Form.tsx b/apps/desktop/src/components/Form.tsx index 47a54f3..a6be099 100644 --- a/apps/desktop/src/components/Form.tsx +++ b/apps/desktop/src/components/Form.tsx @@ -117,6 +117,29 @@ type FieldProps = { children: (id: string) => ReactNode; }; +/** + * Which Project a sheet works on, under its title: "in My SaaS · ~/code/saas", + * or "in My SaaS on devbox · /srv/saas", whose path isn't one here. + */ +export function ProjectContext({ + preposition = "in", + name, + path, + machine, +}: { + preposition?: string; + name: string; + path: string; + machine?: string; +}) { + return ( + <> + {preposition} {name} + {machine && ` on ${machine}`} · {machine ? path : tildePath(path)} + + ); +} + /** A labelled field: the label above, then the control, then an optional hint. */ export function Field({ title, note, hint, width, children }: FieldProps) { const id = useId(); @@ -203,12 +226,14 @@ type FolderProps = { id?: string; path: string; target?: ExecutionTarget; + /** The Machine the folder is on, when it isn't this computer. */ + machine?: string; onChoose: () => void; }; -/** A Project's folder, after its distro's name when it runs in WSL. */ -export function FolderField({ id, path, target, onChoose }: FolderProps) { - const distro = distroOf(target); +/** A Project's folder, after its distro's or Machine's name when it isn't this computer's. */ +export function FolderField({ id, path, target, machine, onChoose }: FolderProps) { + const distro = machine ?? distroOf(target); return ( + + +
+ {isLoading && !listing ? ( + Reading {machine.name}… + ) : entries.length === 0 ? ( +

+ {error ? "Nothing to show." : isFile ? "No folders or Project files here." : "No folders here."} +

+ ) : ( +
    + {entries.map((entry) => ( +
  • setSelected(pathOf(entry))} + onDoubleClick={() => activate(entry)} + > + {entry.isDirectory ? : } + {entry.name} +
  • + ))} +
+ )} +
+ { + setShowsHidden(isOn); + void open(listing?.path ?? pick.start, isOn); + }} + /> + + ); +} diff --git a/apps/desktop/src/components/ServiceForm.tsx b/apps/desktop/src/components/ServiceForm.tsx index 39d77e7..f44ff1b 100644 --- a/apps/desktop/src/components/ServiceForm.tsx +++ b/apps/desktop/src/components/ServiceForm.tsx @@ -5,13 +5,13 @@ import { type Service, type ServiceRelations, } from "../bindings"; +import { editorCommands, type MachineRef } from "../editing"; import { serviceVariables, type VariableDraft, variableDrafts, variableEdits, } from "../editors"; -import { tildePath } from "../paths"; import { formatList } from "../status"; import { portVariable, projectFolder } from "../targets"; import { closeSheet } from "../ui"; @@ -25,6 +25,7 @@ import { FieldHint, FieldRow, FormSheet, + ProjectContext, PythonEnvironmentField, SwitchRow, TextField, @@ -38,6 +39,8 @@ type Props = { project: Project; /** The Service to edit; a new one when absent. */ editing?: Service; + /** The Machine whose Project it is, when it isn't this computer's. */ + machine?: MachineRef; onAdded?: (service: Service) => void; }; @@ -49,13 +52,14 @@ type Props = { * A new Service takes the virtual environment the core finds for its * command until the user edits that field; an existing one only offers it. */ -export function ServiceForm({ project, editing, onAdded }: Props) { +export function ServiceForm({ project, editing, machine, onAdded }: Props) { + const editor = editorCommands(machine ?? null); const [name, setName] = useState(editing?.name ?? ""); const key = useFollowingKey( editing?.key ?? "", editing !== undefined, async (name) => { - const result = await commands.suggestedServiceKey( + const result = await editor.suggestedServiceKey( project.id, name, editing?.id ?? null, @@ -103,10 +107,11 @@ export function ServiceForm({ project, editing, onAdded }: Props) { useEffect(() => { if (!editing) return; - void commands.serviceRelations(editing.id).then((result) => { + void editor.serviceRelations(editing.id).then((result) => { if (result.status === "ok") setRelations(result.data); }); - }, [editing]); + // The editor changes with `machine`, which a sheet keeps. + }, [editing, machine?.id]); useEffect(() => { let isCurrent = true; @@ -121,7 +126,7 @@ export function ServiceForm({ project, editing, onAdded }: Props) { useEffect(() => { let isCurrent = true; const timer = window.setTimeout(() => { - void commands + void editor .detectPythonEnvironment(project.id, workingDirectory, commandLine) .then((result) => { if (!isCurrent) return; @@ -134,7 +139,7 @@ export function ServiceForm({ project, editing, onAdded }: Props) { isCurrent = false; window.clearTimeout(timer); }; - }, [project.id, workingDirectory, commandLine, isPythonEnvironmentEdited]); + }, [project.id, workingDirectory, commandLine, isPythonEnvironmentEdited, machine?.id]); const changePythonEnvironment = (value: string) => { setIsPythonEnvironmentEdited(true); @@ -186,7 +191,7 @@ export function ServiceForm({ project, editing, onAdded }: Props) { }; const chooseDirectory = async () => { - const chosen = await commands.chooseWorkingDirectory( + const chosen = await editor.chooseWorkingDirectory( projectFolder(project), ); if (chosen !== null) setWorkingDirectory(chosen); @@ -210,12 +215,12 @@ export function ServiceForm({ project, editing, onAdded }: Props) { runBefore, }; if (editing) { - const result = await commands.editService(editing.id, service); + const result = await editor.editService(editing.id, service); setIsSaving(false); if (result.status === "error") return setError(result.error.message); closeSheet(); } else { - const result = await commands.addService(project.id, service); + const result = await editor.addService(project.id, service); setIsSaving(false); if (result.status === "error") return setError(result.error.message); closeSheet(); @@ -229,12 +234,7 @@ export function ServiceForm({ project, editing, onAdded }: Props) { icon={} tint={serviceColor(index)} title={editing ? `Edit ${editing.name}` : "New Service"} - subtitle={ - <> - in {project.name} ·{" "} - {tildePath(project.path)} - - } + subtitle={} hint={`↩ to ${editing ? "save" : "add"}`} error={error} primaryTitle={editing ? "Save" : "Add Service"} @@ -359,6 +359,7 @@ export function ServiceForm({ project, editing, onAdded }: Props) { setVariables={setVariables} layer={editing ? { kind: "service", id: editing.id } : null} label="Service variables" + machine={machine} /> )} diff --git a/apps/desktop/src/components/ServicesColumn.module.css b/apps/desktop/src/components/ServicesColumn.module.css index 5fdffc2..b611d1f 100644 --- a/apps/desktop/src/components/ServicesColumn.module.css +++ b/apps/desktop/src/components/ServicesColumn.module.css @@ -130,3 +130,13 @@ display: inline-flex; flex: none; } + +/* Why another Machine's Services can't be added from here now. */ +.column > .editProblem { + margin: 0; + font-size: 11.5px; +} + +.editProblem:hover { + color: var(--text-secondary); +} diff --git a/apps/desktop/src/components/ServicesColumn.tsx b/apps/desktop/src/components/ServicesColumn.tsx index 7d651da..5d9e53b 100644 --- a/apps/desktop/src/components/ServicesColumn.tsx +++ b/apps/desktop/src/components/ServicesColumn.tsx @@ -1,7 +1,9 @@ import { type CSSProperties, useId, useState } from "react"; import { openFolder, openUrl, restart, start, startAll, stop, stopAll } from "../actions"; import type { Folder, Id, Project, Service, StatusView } from "../bindings"; +import { machineRef, type MachineRef } from "../editing"; import { exportProject, requestRemoveService, setActiveProfile, setFavorite } from "../editors"; +import type { ShownMachine } from "../machines"; import { type CoreView, serviceStatus } from "../core"; import type { ServiceSelection } from "../selection"; import { isActive, isManual, isWarning, projectServicesSummary, rowSummary, rowSummaryHelp, serviceRowLabel } from "../status"; @@ -19,12 +21,33 @@ import styles from "./ServicesColumn.module.css"; /** * Where a Project is: this computer (`machineId` null), or another Machine, - * whose Services are controlled while it is connected and edited there. + * whose Services are controlled while it is connected, and whose Projects + * are edited there unless `editProblem` says why not. */ -export type Place = { machineId: Id | null; isReachable: boolean }; +export type Place = { + machineId: Id | null; + isReachable: boolean; + machine?: MachineRef; + editProblem?: string | null; +}; export const thisComputer: Place = { machineId: null, isReachable: true }; +/** Where another Machine's Projects are. */ +export function machinePlace(shown: ShownMachine): Place { + return { + machineId: shown.machine.id, + isReachable: shown.isConnected, + machine: machineRef(shown), + editProblem: shown.editProblem, + }; +} + +/** Why the Place's Projects can't be changed now; `null` when they can. */ +function editProblem(place: Place): string | null { + return place.machineId ? (place.editProblem ?? null) : null; +} + type Props = { project: Project; view: CoreView; @@ -35,31 +58,29 @@ type Props = { /** The selected Project's Services with their state and actions, the combined stream on top. */ export function ServicesColumn({ project, view, selection, onSelect, place = thisComputer }: Props) { - if (project.services.length === 0 && place.machineId) { - return ( -
- } - title="No Services" - description="Add services to this project on its machine." - /> -
- ); - } + const machine = place.machine; + const problem = editProblem(place); if (project.services.length === 0) { return (
} title="No Services" - description={SERVICE_CONCEPT} + description={problem ?? (machine ? `${SERVICE_CONCEPT} They run on ${machine.name}.` : SERVICE_CONCEPT)} > - - + {!problem && ( + <> + + + + )}
); @@ -117,10 +138,12 @@ export function ServicesColumn({ project, view, selection, onSelect, place = thi /> ))} - {!place.machineId && ( + {problem ? ( +

{problem}

+ ) : ( - {!place.machineId && ( - - setShowsStats(true) }, "separator", ...projectMenuItems(project, true)]} - /> - {showsStats && setShowsStats(false)} />} - + {place.machineId ? ( + + ) : ( + + setShowsStats(true) }, "separator", ...projectMenuItems(project, true)]} + /> + {showsStats && setShowsStats(false)} />} + )} ); } /** Switches the active Environment Profile; opens the Environment editor. */ -function ProfileMenu({ project }: { project: Project }) { +function ProfileMenu({ project, place }: { project: Project; place: Place }) { const profiles = project.profiles ?? []; + const { machineId, machine } = place; + const disabledReason = editProblem(place); const active = profiles.find((profile) => profile.id === project.activeProfileID); return ( void setActiveProfile(project.id, null) }, + { + label: "No Profile", + isChecked: !active, + disabledReason, + onSelect: () => void setActiveProfile(project.id, null, machineId), + }, ...profiles.map((profile) => ({ label: profile.name, isChecked: profile.id === active?.id, - onSelect: () => void setActiveProfile(project.id, profile.id), + disabledReason, + onSelect: () => void setActiveProfile(project.id, profile.id, machineId), })), "separator", - { label: "Edit Environment…", onSelect: () => showSheet({ kind: "environment", projectId: project.id }) }, + { + label: "Edit Environment…", + disabledReason, + onSelect: () => showSheet({ kind: "environment", projectId: project.id, machine }), + }, ]} /> ); } -/** A Project's actions, in the toolbar's `⋯` (with Detect Services…) and the sidebar's context menu. */ -export function projectMenuItems(project: Project, withDetect = false): MenuItem[] { +/** + * A Project's actions, in the toolbar's `⋯` (with Detect Services…) and the + * sidebar's context menu. Another Machine's are made there, and say why not + * while they can't be; its folder isn't one here to open or export to. + */ +export function projectMenuItems(project: Project, withDetect = false, place: Place = thisComputer): MenuItem[] { const projectId = project.id; + if (place.machineId) { + const { machineId, machine } = place; + const disabledReason = editProblem(place); + return [ + { label: "Edit Project…", disabledReason, onSelect: () => showSheet({ kind: "editProject", projectId, machine }) }, + { label: "Edit Environment…", disabledReason, onSelect: () => showSheet({ kind: "environment", projectId, machine }) }, + ...(withDetect + ? [{ label: "Detect Services…", disabledReason, onSelect: () => showSheet({ kind: "detectServices", projectId, machine }) }] + : []), + { + label: project.isFavorite ? "Unfavorite" : "Favorite", + disabledReason, + onSelect: () => void setFavorite(project, !project.isFavorite, machineId), + }, + "separator", + { + label: "Remove Project…", + isDestructive: true, + disabledReason, + onSelect: () => showAlert({ kind: "removeProject", projectId, machine }), + }, + ]; + } return [ { label: "Edit Project…", onSelect: () => showSheet({ kind: "editProject", projectId }) }, { label: "Edit Environment…", onSelect: () => showSheet({ kind: "environment", projectId }) }, @@ -240,12 +305,24 @@ function ServiceRow({ project, service, status, index, id, isSelected, onSelect, const port = isActive(state) ? (status.run?.port ?? service.port) : service.port; const summary = rowSummary(project, service, status); const summaryClass = state === "failed" ? styles.failed : isWarning(status) ? styles.warning : "secondary"; + const problem = editProblem(place); const edit = () => { - if (!place.machineId) showSheet({ kind: "editService", serviceId: service.id }); + if (!problem) showSheet({ kind: "editService", serviceId: service.id, machine: place.machine }); }; const context = useContextMenu(`${service.name} actions`, () => place.machineId - ? stateMenuItems(service, status, place) + ? [ + ...stateMenuItems(service, status, place), + "separator", + { label: "Edit Service…", disabledReason: problem, onSelect: edit }, + "separator", + { + label: "Remove Service…", + isDestructive: true, + disabledReason: problem, + onSelect: () => void requestRemoveService(service.id, place.machine ?? null), + }, + ] : [ ...stateMenuItems(service, status, place), "separator", @@ -346,16 +423,15 @@ function ServiceActions({ service, status, place }: { service: Service; status: > Start - {!machineId && ( - - )} + ); } diff --git a/apps/desktop/src/components/Sheets.tsx b/apps/desktop/src/components/Sheets.tsx index 09d1c59..2b849c9 100644 --- a/apps/desktop/src/components/Sheets.tsx +++ b/apps/desktop/src/components/Sheets.tsx @@ -1,60 +1,108 @@ import { useEffect } from "react"; import type { Id } from "../bindings"; import { type CoreView, findService } from "../core"; +import type { MachineRef } from "../editing"; +import { useMachines } from "../machines"; import { closeSheet, type Sheet, useUi } from "../ui"; import { ConnectAgentsSheet } from "./ConnectAgents"; import { EnvironmentForm } from "./EnvironmentForm"; import { ImportProjectForm } from "./ImportProjectForm"; import { ProjectForm } from "./ProjectForm"; +import { RemoteFolderPicker } from "./RemoteFolderPicker"; import { ServiceForm } from "./ServiceForm"; import { DetectServicesForm } from "./SuggestionReview"; import { Welcome } from "./Welcome"; type Props = { view: CoreView; - /** Selects what was just added. */ - onSelectProject: (projectId: Id) => void; - onSelectService: (projectId: Id, serviceId: Id) => void; + /** Selects what was just added; on another Machine with `machine`. */ + onSelectProject: (projectId: Id, machine?: MachineRef) => void; + onSelectService: (projectId: Id, serviceId: Id, machine?: MachineRef) => void; }; -/** The editor on screen, if any. One whose Project or Service went away closes. */ +/** + * The editor on screen, if any, and the remote folder picker over it. One + * whose Project or Service went away closes, as does one for a Machine that + * was removed. + */ export function Sheets({ view, onSelectProject, onSelectService }: Props) { const { sheet } = useUi(); - const content = sheet && sheetContent(sheet, view, onSelectProject, onSelectService); - const isGone = sheet !== null && content === null; + const machines = useMachines(); + const machine = sheet && "machine" in sheet ? sheet.machine : undefined; + const machineView = machine ? machines.find((shown) => shown.machine.id === machine.id)?.view : view; + // This computer's are selected as before; a Machine's say which Machine. + const selectProject: Props["onSelectProject"] = (projectId) => + machine ? onSelectProject(projectId, machine) : onSelectProject(projectId); + const selectService: Props["onSelectService"] = (projectId, serviceId) => + machine ? onSelectService(projectId, serviceId, machine) : onSelectService(projectId, serviceId); + const content = sheet && machineView && sheetContent(sheet, machineView, machine, selectProject, selectService); + const isGone = sheet !== null && !content; useEffect(() => { if (isGone) closeSheet(); }, [isGone]); - return content; + return ( + <> + {content} + + + ); } -function sheetContent(sheet: Sheet, view: CoreView, onSelectProject: Props["onSelectProject"], onSelectService: Props["onSelectService"]) { +function sheetContent( + sheet: Sheet, + view: CoreView, + machine: MachineRef | undefined, + onSelectProject: Props["onSelectProject"], + onSelectService: Props["onSelectService"], +) { const project = (id: Id) => view.projects.find((project) => project.id === id); switch (sheet.kind) { case "addProject": - return onSelectProject(added.id)} />; + return onSelectProject(added.id)} />; case "editProject": { const editing = project(sheet.projectId); - return editing ? : null; + return editing ? : null; } case "addService": { const target = project(sheet.projectId); - return target ? onSelectService(target.id, added.id)} /> : null; + return target ? ( + onSelectService(target.id, added.id)} /> + ) : null; } case "editService": { const found = findService(view, sheet.serviceId); - return found ? : null; + return found ? ( + + ) : null; } case "detectServices": { const target = project(sheet.projectId); - return target ? onSelectService(target.id, serviceId)} /> : null; + return target ? ( + onSelectService(target.id, serviceId)} + /> + ) : null; } case "environment": { const target = project(sheet.projectId); - return target ? : null; + return target ? : null; } case "importProject": - return onSelectProject(imported.id)} />; + return ( + onSelectProject(imported.id)} + /> + ); case "connectAgents": return ; case "welcome": diff --git a/apps/desktop/src/components/Sidebar.module.css b/apps/desktop/src/components/Sidebar.module.css index 18dd650..5b79dec 100644 --- a/apps/desktop/src/components/Sidebar.module.css +++ b/apps/desktop/src/components/Sidebar.module.css @@ -92,6 +92,27 @@ color: var(--text-secondary); } +/* Another Machine's name, with its Add Project menu. */ +.machineHeading { + display: flex; + align-items: center; + gap: 4px; + margin-bottom: 0; +} + +.machineName { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.machineAdd { + width: 20px; + height: 20px; +} + .note { padding: 4px 8px; font-size: 12px; diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsx index 126f23f..a9d41a6 100644 --- a/apps/desktop/src/components/Sidebar.tsx +++ b/apps/desktop/src/components/Sidebar.tsx @@ -3,6 +3,7 @@ import { report, startAll, stopAll } from "../actions"; import { commands, type Project } from "../bindings"; import { type CoreView, serviceState } from "../core"; import type { SidebarSelection } from "../selection"; +import { machineRef } from "../editing"; import { importProject } from "../editors"; import { SHORTCUTS, shortcutLabel } from "../keyboard"; import type { ShownMachine } from "../machines"; @@ -13,7 +14,7 @@ import { useUpdate } from "../updates"; import { GetStarted } from "./GetStarted"; import { ClearIcon, GearIcon, GlobeIcon, HelpIcon, PlusIcon, SearchIcon } from "./Icons"; import { Menu, type MenuItem, useContextMenu } from "./Menu"; -import { projectMenuItems } from "./ServicesColumn"; +import { machinePlace, projectMenuItems } from "./ServicesColumn"; import { ShortcutBadge } from "./ShortcutBadge"; import { StateGlyph } from "./StateGlyph"; import { TelemetryNotice } from "./TelemetryNotice"; @@ -132,8 +133,13 @@ export function Sidebar({ view, machines = [], selection, onSelect }: Props) { {machines.map((shown) => { const machineId = shown.machine.id; return [ -
  • - {shown.machine.name} +
  • + {shown.machine.name} + }} + items={machineAddItems(shown)} + />
  • , , ...matching(shown.view.projects).map((project) => ( @@ -245,9 +251,8 @@ function ProjectRow({ project, view, index, id, isSelected, onSelect, isDimmed = function MachineNote({ shown }: { shown: ShownMachine }) { const isReconnecting = shown.state.kind === "connecting" && shown.view.projects.length > 0; const text = shown.isConnected - ? shown.view.projects.length === 0 - ? `No projects on ${shown.machine.name}.` - : null + ? // Connected to an older localhost: its Projects are shown and run only. + (shown.editProblem ?? (shown.view.projects.length === 0 ? `No projects on ${shown.machine.name}.` : null)) : isReconnecting ? null : shown.summary; @@ -272,7 +277,17 @@ async function reconnect(machineId: string) { report(await commands.reconnectMachine(machineId)); } -/** Another Machine's Project: Start All and Stop All; it is edited there. */ +/** New Project… and Import Project… on another Machine, with why not while they can't be. */ +export function machineAddItems(shown: ShownMachine): MenuItem[] { + const machine = machineRef(shown); + const disabledReason = shown.editProblem; + return [ + { label: `New Project on ${machine.name}…`, disabledReason, onSelect: () => showSheet({ kind: "addProject", machine }) }, + { label: `Import Project on ${machine.name}…`, disabledReason, onSelect: () => void importProject(machine) }, + ]; +} + +/** Another Machine's Project: Start All and Stop All, then its edits, made there. */ function machineProjectMenuItems(shown: ShownMachine, project: Project): MenuItem[] { const machineId = shown.machine.id; const anyActive = project.services.some((service) => isActive(serviceState(shown.view, service.id))); @@ -282,5 +297,7 @@ function machineProjectMenuItems(shown: ShownMachine, project: Project): MenuIte : []), ...(shown.isConnected && anyActive ? [{ label: "Stop All", onSelect: () => void stopAll(project.id, machineId) }] : []), { label: "Reconnect", onSelect: () => void reconnect(machineId) }, + "separator", + ...projectMenuItems(project, true, machinePlace(shown)), ]; } diff --git a/apps/desktop/src/components/SuggestionReview.tsx b/apps/desktop/src/components/SuggestionReview.tsx index 6021bbb..f2312bd 100644 --- a/apps/desktop/src/components/SuggestionReview.tsx +++ b/apps/desktop/src/components/SuggestionReview.tsx @@ -12,6 +12,7 @@ import { type ProjectFolder, type Service, } from "../bindings"; +import { editorCommands, type MachineRef, onMachine } from "../editing"; import { canSplit, directoryLabel, @@ -23,7 +24,6 @@ import { suggestionDrafts, suggestionEdits, } from "../editors"; -import { tildePath } from "../paths"; import { portVariable, projectFolder } from "../targets"; import { closeSheet } from "../ui"; import { @@ -36,6 +36,7 @@ import { FieldRow, FormCard, FormSheet, + ProjectContext, SwitchRow, TextField, Working, @@ -51,6 +52,8 @@ type Props = { isScanning: boolean; /** The Project's folder, where working directories are chosen. */ project: ProjectFolder; + /** The Machine the folder is on, when it isn't this computer. */ + machine?: MachineRef; /** * The Services the Project already has: new ones show the colours they'll * keep after them, and can start after them. @@ -70,6 +73,7 @@ export function SuggestionReview({ setDrafts, isScanning, project, + machine, existingServices = [], emptyMessage, }: Props) { @@ -157,6 +161,7 @@ export function SuggestionReview({ draft={draft} color={color(draft)} project={project} + machine={machine} isExpanded={merging === null && expandedId === draft.id} onToggleExpanded={() => setExpandedId(expandedId === draft.id ? null : draft.id) @@ -296,6 +301,7 @@ type RowProps = { draft: SuggestionDraft; color: string; project: ProjectFolder; + machine?: MachineRef; isExpanded: boolean; onToggleExpanded: () => void; onChange: (change: Partial) => void; @@ -333,7 +339,7 @@ function SuggestionRow(props: RowProps) { } }; const chooseDirectory = async () => { - const workingDirectory = await commands.chooseWorkingDirectory(project); + const workingDirectory = await editorCommands(props.machine ?? null).chooseWorkingDirectory(project); if (workingDirectory !== null) onChange({ workingDirectory }); }; const after = draft.isChecked @@ -526,11 +532,15 @@ function SuggestionRow(props: RowProps) { /** Scans an existing Project's folder again and adds the Services the user picks from what it finds. */ export function DetectServicesForm({ project, + machine, onAdded, }: { project: Project; + /** The Machine whose Project it is, scanned there. */ + machine?: MachineRef; onAdded: (serviceId: string) => void; }) { + const editor = editorCommands(machine ?? null); const [drafts, setDrafts] = useState([]); const [isScanning, setIsScanning] = useState(true); const [error, setError] = useState(null); @@ -538,7 +548,7 @@ export function DetectServicesForm({ useEffect(() => { let isCurrent = true; - void commands.scanProject(project.id).then((result) => { + void editor.scanProject(project.id).then((result) => { if (!isCurrent) return; if (result.status === "ok") setDrafts(suggestionDrafts(result.data)); else setError(result.error.message); @@ -547,12 +557,13 @@ export function DetectServicesForm({ return () => { isCurrent = false; }; - }, [project.id]); + // The editor changes with `machine`, which a sheet keeps. + }, [project.id, machine?.id]); const count = drafts.filter((draft) => draft.isChecked).length; const save = async () => { setIsSaving(true); - const result = await commands.addServices( + const result = await editor.addServices( project.id, suggestionEdits(drafts), ); @@ -564,13 +575,8 @@ export function DetectServicesForm({ return ( } - title="Detect Services" - subtitle={ - <> - in {project.name} ·{" "} - {tildePath(project.path)} - - } + title={`Detect Services${onMachine(machine)}`} + subtitle={} hint={count === 0 ? null : "↩ to add"} error={error} primaryTitle={ @@ -588,6 +594,7 @@ export function DetectServicesForm({ setDrafts={setDrafts} isScanning={isScanning} project={projectFolder(project)} + machine={machine} existingServices={project.services} emptyMessage="Nothing new found. Services this project already runs aren’t suggested again." /> diff --git a/apps/desktop/src/components/VariableEditor.tsx b/apps/desktop/src/components/VariableEditor.tsx index a2d21a4..13dc017 100644 --- a/apps/desktop/src/components/VariableEditor.tsx +++ b/apps/desktop/src/components/VariableEditor.tsx @@ -1,6 +1,7 @@ import type { Dispatch, SetStateAction } from "react"; -import { commands, type VariableLayer } from "../bindings"; +import type { VariableLayer } from "../bindings"; import { report } from "../actions"; +import { editorCommands, type MachineRef } from "../editing"; import { newVariableDraft, type VariableDraft } from "../editors"; import { FormCard } from "./Form"; import { EyeIcon, EyeSlashIcon, LockIcon, LockOpenIcon, MinusCircleIcon, PlusIcon } from "./Icons"; @@ -13,6 +14,8 @@ type Props = { layer: VariableLayer | null; /** Names the table for screen readers, e.g. "Project variables". */ label: string; + /** The Machine whose secret store keeps the layer's Secrets, when it isn't this computer. */ + machine?: MachineRef; }; /** @@ -20,14 +23,15 @@ type Props = { * lock turns a variable into a Secret or back. A stored Secret's value is only * read from the system's secret store when revealed or made plain. */ -export function VariableEditor({ variables, setVariables, layer, label }: Props) { +export function VariableEditor({ variables, setVariables, layer, label, machine }: Props) { const update = (id: number, change: Partial) => setVariables((variables) => variables.map((draft) => (draft.id === id ? { ...draft, ...change } : draft))); /** The draft with its stored value loaded, if it had one to load. */ const withStoredValue = async (draft: VariableDraft): Promise => { if (draft.isValueKnown || !layer || draft.storedSecretName === null) return draft; - const result = await commands.secretValue(draft.storedSecretName, layer); + // Shown here only; it stays in the Machine's store. + const result = await editorCommands(machine ?? null).secretValue(draft.storedSecretName, layer); if (result.status === "error") { report(result); return draft; @@ -90,7 +94,7 @@ export function VariableEditor({ variables, setVariables, layer, label }: Props) aria-pressed={draft.isSecret} title={ draft.isSecret - ? "Secret: stored in your system’s secret store, never in the project file. Click to make it a plain variable." + ? `Secret: stored in ${machine ? `${machine.name}’s` : "your system’s"} secret store, never in the project file. Click to make it a plain variable.` : "Make it a secret" } onClick={() => void toggleSecret(draft)} diff --git a/apps/desktop/src/editing.ts b/apps/desktop/src/editing.ts new file mode 100644 index 0000000..3ae1d64 --- /dev/null +++ b/apps/desktop/src/editing.ts @@ -0,0 +1,83 @@ +import { commands, type ExecutionTarget, type Id, type ProjectFolder } from "./bindings"; +import type { ShownMachine } from "./machines"; +import { chooseOnMachine } from "./remoteFolders"; +import { thisMachine } from "./targets"; + +// Where an editor saves: this computer, or another Machine, whose Projects +// are changed there. The sheets are the same; `editorCommands` sends their +// calls to one or the other, and a Machine's folders are picked with the +// remote folder picker, as no system dialog here can browse them. + +/** A Machine an editor works on, by id and by the name it is shown under. */ +export type MachineRef = { id: Id; name: string }; + +export function machineRef(shown: ShownMachine): MachineRef { + return { id: shown.machine.id, name: shown.machine.name }; +} + +/** " on devbox" after an editor's title, or nothing on this computer. */ +export function onMachine(machine: MachineRef | null | undefined): string { + return machine ? ` on ${machine.name}` : ""; +} + +/** The editors' calls, on this computer (`null`) or on `machine`. */ +export function editorCommands(machine: MachineRef | null) { + if (!machine) { + return { + suggestedProjectKey: commands.suggestedProjectKey, + suggestedServiceKey: commands.suggestedServiceKey, + addProject: commands.addProject, + editProject: commands.editProject, + scanFolder: commands.scanFolder, + scanProject: commands.scanProject, + addService: commands.addService, + editService: commands.editService, + addServices: commands.addServices, + serviceRelations: commands.serviceRelations, + detectPythonEnvironment: commands.detectPythonEnvironment, + saveEnvironment: commands.saveEnvironment, + secretValue: commands.secretValue, + importProject: commands.importProject, + chooseFolder: commands.chooseFolder, + chooseWorkingDirectory: commands.chooseWorkingDirectory, + }; + } + const id = machine.id; + return { + suggestedProjectKey: (name: string, excluding: Id | null) => commands.machineSuggestedProjectKey(id, name, excluding), + suggestedServiceKey: (projectId: Id, name: string, excluding: Id | null) => + commands.machineSuggestedServiceKey(id, projectId, name, excluding), + addProject: (...[name, key, folder, services]: Parameters) => + commands.machineAddProject(id, name, key, folder.path, services), + editProject: (...[projectId, name, key, folder]: Parameters) => + commands.machineEditProject(id, projectId, name, key, folder.path), + scanFolder: (folder: ProjectFolder) => commands.machineScanFolder(id, folder.path), + scanProject: (projectId: Id) => commands.machineScanProject(id, projectId), + addService: (...[projectId, service]: Parameters) => + commands.machineAddService(id, projectId, service), + editService: (...[serviceId, service]: Parameters) => + commands.machineEditService(id, serviceId, service), + addServices: (...[projectId, services]: Parameters) => + commands.machineAddServices(id, projectId, services), + serviceRelations: (serviceId: Id) => commands.machineServiceRelations(id, serviceId), + detectPythonEnvironment: (...[projectId, workingDirectory, commandLine]: Parameters) => + commands.machineDetectPythonEnvironment(id, projectId, workingDirectory, commandLine), + saveEnvironment: (...[projectId, variables, profiles, active]: Parameters) => + commands.machineSaveEnvironment(id, projectId, variables, profiles, active), + secretValue: (...[name, layer]: Parameters) => commands.machineSecretValue(id, name, layer), + importProject: (...[file, folder, choice]: Parameters) => + commands.machineImportProject(id, file, folder.path, choice), + /** A folder of the Machine, as one this app's editors take. */ + chooseFolder: async (_target: ExecutionTarget, start: string | null): Promise => { + const path = await chooseOnMachine(machine, { start }); + return path === null ? null : { target: thisMachine, path }; + }, + /** A folder of the Machine, relative to the Project's. */ + chooseWorkingDirectory: async (project: ProjectFolder): Promise => { + const path = await chooseOnMachine(machine, { start: project.path }); + return path === null ? null : commands.relativeFolder(path, project.path); + }, + }; +} + +export type EditorCommands = ReturnType; diff --git a/apps/desktop/src/editors.ts b/apps/desktop/src/editors.ts index 18c17af..bd803de 100644 --- a/apps/desktop/src/editors.ts +++ b/apps/desktop/src/editors.ts @@ -9,6 +9,8 @@ import { type Variables, } from "./bindings"; import { report } from "./actions"; +import type { MachineRef } from "./editing"; +import { chooseOnMachine } from "./remoteFolders"; import { showAlert, showSheet } from "./ui"; // What the editors work on before saving: variable rows and reviewed @@ -343,13 +345,17 @@ export function directoryLabel(workingDirectory: string): string { : `./${workingDirectory}`; } -/** Asks for a Project file, reads it, and opens its review sheet, or says why it can't be imported. */ -export async function importProject() { - const file = await commands.chooseProjectFile(); +/** + * Asks for a Project file, reads it, and opens its review sheet, or says why + * it can't be imported. On `machine`, the file is that Machine's, picked + * with the remote folder picker and read there. + */ +export async function importProject(machine: MachineRef | null = null) { + const file = machine ? await chooseOnMachine(machine, { isFile: true }) : await commands.chooseProjectFile(); if (!file) return; - const result = await commands.readProjectFile(file); + const result = machine ? await commands.machineReadProjectFile(machine.id, file) : await commands.readProjectFile(file); if (result.status === "ok") { - showSheet({ kind: "importProject", file, preview: result.data }); + showSheet({ kind: "importProject", file, preview: result.data, machine: machine ?? undefined }); } else { showAlert({ kind: "importFailure", @@ -366,29 +372,42 @@ export async function exportProject(projectId: Id) { if (file.data) report(await commands.exportProject(projectId, file.data)); } -export async function setFavorite(project: Project, isFavorite: boolean) { - report(await commands.setFavorite(project.id, isFavorite)); +// Each on this computer, or with `machineId` on that Machine. + +export async function setFavorite(project: Project, isFavorite: boolean, machineId: Id | null = null) { + report( + await (machineId + ? commands.machineSetFavorite(machineId, project.id, isFavorite) + : commands.setFavorite(project.id, isFavorite)), + ); } -export async function setActiveProfile(projectId: Id, profileId: Id | null) { - report(await commands.setActiveProfile(projectId, profileId)); +export async function setActiveProfile(projectId: Id, profileId: Id | null, machineId: Id | null = null) { + report( + await (machineId + ? commands.machineSetActiveProfile(machineId, projectId, profileId) + : commands.setActiveProfile(projectId, profileId)), + ); } -export async function removeProject(projectId: Id) { - report(await commands.removeProject(projectId)); +export async function removeProject(projectId: Id, machineId: Id | null = null) { + report(await (machineId ? commands.machineRemoveProject(machineId, projectId) : commands.removeProject(projectId))); } /** Asks before removing the Service, naming the Services that depend on it. */ -export async function requestRemoveService(serviceId: Id) { - const relations = await commands.serviceRelations(serviceId); +export async function requestRemoveService(serviceId: Id, machine: MachineRef | null = null) { + const relations = machine + ? await commands.machineServiceRelations(machine.id, serviceId) + : await commands.serviceRelations(serviceId); if (relations.status === "error") return report(relations); showAlert({ kind: "removeService", serviceId, dependents: relations.data.dependents, + machine: machine ?? undefined, }); } -export async function removeService(serviceId: Id) { - report(await commands.removeService(serviceId)); +export async function removeService(serviceId: Id, machineId: Id | null = null) { + report(await (machineId ? commands.machineRemoveService(machineId, serviceId) : commands.removeService(serviceId))); } diff --git a/apps/desktop/src/machines.ts b/apps/desktop/src/machines.ts index f2e0480..d5aca40 100644 --- a/apps/desktop/src/machines.ts +++ b/apps/desktop/src/machines.ts @@ -17,6 +17,8 @@ export type ShownMachine = { isConnected: boolean; /** It waits for the user to connect it again. */ needsUser: boolean; + /** Why its Projects can't be changed from here now (not connected, or an older localhost there); `null` when they can. */ + editProblem: string | null; /** Its Projects and statuses, those of its last connection while it reconnects. */ view: CoreView; }; @@ -28,6 +30,7 @@ export function shownMachine(view: MachineView): ShownMachine { summary: view.summary, isConnected: view.isConnected, needsUser: view.needsUser, + editProblem: view.editProblem, view: viewFromSnapshot({ projects: view.projects, statuses: view.statuses, projectStates: view.projectStates }), }; } diff --git a/apps/desktop/src/palette.ts b/apps/desktop/src/palette.ts index f8dc1b6..7767e6f 100644 --- a/apps/desktop/src/palette.ts +++ b/apps/desktop/src/palette.ts @@ -1,6 +1,9 @@ import { openFolder, openUrl, restart, start, startAll, stop, stopAll } from "./actions"; import { commands, type Id, type Project, type Service, type ServiceState } from "./bindings"; import { type CoreView, serviceStatus } from "./core"; +import { machineRef } from "./editing"; +import { importProject, setFavorite } from "./editors"; +import type { ShownMachine } from "./machines"; import { projectShortcut, SHORTCUTS, type Shortcut, serviceShortcut, shortcutLabel } from "./keyboard"; import { tildePath } from "./paths"; import type { ServiceSelection } from "./selection"; @@ -249,3 +252,88 @@ function projectActions(view: CoreView, project: Project, isSelected: boolean): item("project-files", `Open ${project.name} in File Manager`, "folder", null, () => void openFolder(folder, "fileManager")); return items; } + +/** + * Another Machine's actions: for its selected Project, the same as for one + * here (first, as an empty query shows them), made there; and for every + * Machine, New Project… and Import Project… there, found by typing. While + * its Projects can't be changed, an edit says why instead. + */ +export function machinePaletteItems( + machines: ShownMachine[], + selected: { machine: ShownMachine; project: Project; selection: ServiceSelection } | null, +): { first: PaletteItem[]; rest: PaletteItem[] } { + const first: PaletteItem[] = []; + const symbol = (name: Extract["name"]): PaletteIcon => ({ kind: "symbol", name }); + /** Runs `run`, or says why the Machine's Projects can't be changed now. */ + const editing = (shown: ShownMachine, run: () => void) => () => + shown.editProblem ? showAlert({ kind: "error", message: shown.editProblem }) : run(); + if (selected) { + const { machine: shown, project } = selected; + const machine = machineRef(shown); + const machineId = machine.id; + const view = shown.view; + const where = `${project.name} on ${machine.name}`; + const item = (id: string, title: string, icon: PaletteIcon, shortcut: Shortcut | null, run: () => void, subtitle = where) => + first.push({ id: `machine:${id}:${project.id}`, title, subtitle, icon, shortcut: label(shortcut), keywords: project.key, boost: 2, run }); + const selection = selected.selection; + const service = + selection.kind === "service" ? project.services.find((one) => one.id === selection.serviceId) : undefined; + if (service && shown.isConnected) { + const status = serviceStatus(view, service.id); + if (status.state === "starting" || status.state === "running") { + item(`restart:${service.id}`, `Restart ${service.name}`, symbol("restart"), SHORTCUTS.startOrRestart, () => void restart(service.id, machineId)); + item(`stop:${service.id}`, `Stop ${service.name}`, symbol("stop"), SHORTCUTS.stop, () => void stop(service.id, machineId)); + if (status.urlToOpen) { + item(`open-url:${service.id}`, `Open ${service.name} in Browser`, symbol("browser"), SHORTCUTS.openUrl, () => void openUrl(service.id, machineId)); + } + } else if (status.state !== "stopping") { + item(`start:${service.id}`, `Start ${service.name}`, symbol("play"), SHORTCUTS.startOrRestart, () => void start(service.id, null, machineId)); + } + } + if (shown.isConnected && project.services.length > 0) { + item("start-all", `Start All in ${project.name}`, symbol("play"), SHORTCUTS.startAll, () => void startAll(project.id, machineId)); + } + if (shown.isConnected && project.services.some((one) => isActive(serviceStatus(view, one.id).state))) { + item("stop-all", `Stop All in ${project.name}`, symbol("stop"), SHORTCUTS.stopAll, () => void stopAll(project.id, machineId)); + } + const subtitle = shown.editProblem ?? where; + const projectId = project.id; + item("new-service", "New Service…", symbol("new"), SHORTCUTS.newService, editing(shown, () => showSheet({ kind: "addService", projectId, machine })), subtitle); + item("edit-project", "Edit Project…", symbol("folder"), null, editing(shown, () => showSheet({ kind: "editProject", projectId, machine })), subtitle); + item("environment", "Edit Environment…", symbol("folder"), null, editing(shown, () => showSheet({ kind: "environment", projectId, machine })), subtitle); + item("detect", "Detect Services…", symbol("service"), null, editing(shown, () => showSheet({ kind: "detectServices", projectId, machine })), subtitle); + item( + "favorite", + project.isFavorite ? `Unfavorite ${project.name}` : `Favorite ${project.name}`, + symbol("folder"), + null, + editing(shown, () => void setFavorite(project, !project.isFavorite, machineId)), + subtitle, + ); + item("remove", `Remove ${project.name}…`, symbol("stop"), null, editing(shown, () => showAlert({ kind: "removeProject", projectId, machine })), subtitle); + } + const rest: PaletteItem[] = machines.flatMap((shown) => { + const machine = machineRef(shown); + const subtitle = shown.editProblem ?? undefined; + return [ + { + id: `other:machine-new-project:${machine.id}`, + title: `New Project on ${machine.name}…`, + subtitle, + icon: symbol("new"), + keywords: "add machine remote", + run: editing(shown, () => showSheet({ kind: "addProject", machine })), + }, + { + id: `other:machine-import:${machine.id}`, + title: `Import Project on ${machine.name}…`, + subtitle, + icon: symbol("new"), + keywords: "add machine remote file yaml", + run: editing(shown, () => void importProject(machine)), + }, + ]; + }); + return { first, rest }; +} diff --git a/apps/desktop/src/remoteFolders.ts b/apps/desktop/src/remoteFolders.ts new file mode 100644 index 0000000..7ea1c76 --- /dev/null +++ b/apps/desktop/src/remoteFolders.ts @@ -0,0 +1,79 @@ +import { useSyncExternalStore } from "react"; +import type { MachineRef } from "./editing"; + +// The remote folder picker, asked for like a system dialog: `chooseOnMachine` +// opens it over whatever is on screen and resolves with the chosen path, or +// `null` on Cancel. One at a time; asking again cancels the open one. + +/** What the picker on screen was asked for. */ +export type RemotePick = { + machine: MachineRef; + /** Where it opens; the home folder there when `null` or not found. */ + start: string | null; + /** Picks a Project file (YAML) instead of a folder. */ + isFile: boolean; + resolve: (path: string | null) => void; +}; + +let current: RemotePick | null = null; +const listeners = new Set<() => void>(); + +function set(pick: RemotePick | null) { + current = pick; + listeners.forEach((listener) => listener()); +} + +/** A folder (or with `isFile`, a Project file) on the Machine; `null` if cancelled. */ +export function chooseOnMachine( + machine: MachineRef, + { start = null, isFile = false }: { start?: string | null; isFile?: boolean } = {}, +): Promise { + current?.resolve(null); + return new Promise((resolve) => { + set({ + machine, + start, + isFile, + resolve: (path) => { + set(null); + resolve(path); + }, + }); + }); +} + +export function useRemotePick(): RemotePick | null { + return useSyncExternalStore( + (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + () => current, + ); +} + +/** A Project file, by its extension. */ +export function isProjectFile(name: string): boolean { + return /\.ya?ml$/i.test(name); +} + +/** `name` inside the folder `path`, with the folder's own separator. */ +export function childPath(path: string, name: string): string { + const separator = path.includes("\\") && !path.includes("/") ? "\\" : "/"; + return path.endsWith("/") || path.endsWith("\\") ? `${path}${name}` : `${path}${separator}${name}`; +} + +/** The folders from the root down to `path`, each with its own path, for a breadcrumb. */ +export function pathCrumbs(path: string): { name: string; path: string }[] { + const windowsRoot = /^[A-Za-z]:[\\/]?/.exec(path); + const root = windowsRoot ? windowsRoot[0].replace(/[\\/]?$/, "\\") : path.startsWith("/") ? "/" : ""; + const separator = windowsRoot ? "\\" : "/"; + const parts = path.slice(windowsRoot ? windowsRoot[0].length : root.length).split(/[\\/]/).filter(Boolean); + const crumbs = root ? [{ name: root, path: root }] : []; + let walked = root; + for (const part of parts) { + walked = walked === root ? `${root}${part}` : `${walked}${separator}${part}`; + crumbs.push({ name: part, path: walked }); + } + return crumbs; +} diff --git a/apps/desktop/src/shortcuts.ts b/apps/desktop/src/shortcuts.ts index 10406b7..4a7de0a 100644 --- a/apps/desktop/src/shortcuts.ts +++ b/apps/desktop/src/shortcuts.ts @@ -101,10 +101,14 @@ function runShortcut(event: KeyboardEvent, context: ShortcutContext): boolean { else if (is(SHORTCUTS.ports)) navigator.selectPorts(); else if (is(SHORTCUTS.settings)) showAlert({ kind: "settings" }); else if (is(SHORTCUTS.keyboardShortcuts)) showAlert({ kind: "keyboardShortcuts" }); - else if (is(SHORTCUTS.newProject)) showSheet({ kind: "addProject" }); - else if (is(SHORTCUTS.newService)) { - // Another Machine's Services are added there. - if (selected && !machineId) showSheet({ kind: "addService", projectId: selected.id }); + // With another Machine's Project selected, they add there, once it can. + else if (is(SHORTCUTS.newProject)) { + if (!machineId) showSheet({ kind: "addProject" }); + else if (place.editProblem) showAlert({ kind: "error", message: place.editProblem }); + else showSheet({ kind: "addProject", machine: place.machine }); + } else if (is(SHORTCUTS.newService)) { + if (selected && machineId && place.editProblem) showAlert({ kind: "error", message: place.editProblem }); + else if (selected) showSheet({ kind: "addService", projectId: selected.id, machine: place.machine }); } else if (is(SHORTCUTS.startOrRestart)) { if (service && canControl && state !== "stopping") { void (isLive ? restart(service.id, machineId) : start(service.id, null, machineId)); diff --git a/apps/desktop/src/test/fixtures.ts b/apps/desktop/src/test/fixtures.ts index 89507ef..df76f9e 100644 --- a/apps/desktop/src/test/fixtures.ts +++ b/apps/desktop/src/test/fixtures.ts @@ -51,10 +51,11 @@ export function machineView( ): MachineView { return { machine: { id: id(), name, destination: name }, - state: { kind: "connected", detail: { version: "0.5.0" } }, + state: { kind: "connected", detail: { version: "0.5.0", managesProjects: true } }, summary: "Connected · localhost 0.5.0", isConnected: true, needsUser: false, + editProblem: null, projects, statuses, projectStates: [], diff --git a/apps/desktop/src/ui.ts b/apps/desktop/src/ui.ts index 430dbdc..321ce97 100644 --- a/apps/desktop/src/ui.ts +++ b/apps/desktop/src/ui.ts @@ -1,5 +1,6 @@ import { useSyncExternalStore } from "react"; import type { BlockedStart, Id, ImportPreview, ListenerDetails } from "./bindings"; +import type { MachineRef } from "./editing"; /** A question or report over the main window. They are asked one at a time, in order. */ export type Alert = @@ -17,9 +18,9 @@ export type Alert = | { kind: "settings"; section?: SettingsSection; forEditor?: () => void } /** Every shortcut, grouped (Ctrl+/). */ | { kind: "keyboardShortcuts" } - /** Removing a Project or Service, which stops it first. */ - | { kind: "removeProject"; projectId: Id } - | { kind: "removeService"; serviceId: Id; dependents: string[] } + /** Removing a Project or Service, which stops it first; on `machine`, there. */ + | { kind: "removeProject"; projectId: Id; machine?: MachineRef } + | { kind: "removeService"; serviceId: Id; dependents: string[]; machine?: MachineRef } /** A Project file that can't be imported, and why. */ | { kind: "importFailure"; fileName: string; message: string } /** Check for Updates found nothing newer than `version`. */ @@ -28,16 +29,19 @@ export type Alert = /** The sections of Settings, in the rail's order. */ export type SettingsSection = "general" | "appearance" | "ports" | "machines" | "agents"; -/** An editor over the main window, one at a time. */ +/** + * An editor over the main window, one at a time. With `machine`, it edits + * that Machine's Projects, there. + */ export type Sheet = - | { kind: "addProject" } - | { kind: "editProject"; projectId: Id } - | { kind: "addService"; projectId: Id } - | { kind: "editService"; serviceId: Id } - | { kind: "detectServices"; projectId: Id } - | { kind: "environment"; projectId: Id } - /** The review step of an import, before anything is saved. */ - | { kind: "importProject"; file: string; preview: ImportPreview } + | { kind: "addProject"; machine?: MachineRef } + | { kind: "editProject"; projectId: Id; machine?: MachineRef } + | { kind: "addService"; projectId: Id; machine?: MachineRef } + | { kind: "editService"; serviceId: Id; machine?: MachineRef } + | { kind: "detectServices"; projectId: Id; machine?: MachineRef } + | { kind: "environment"; projectId: Id; machine?: MachineRef } + /** The review step of an import, before anything is saved; `file` is the Machine's with `machine`. */ + | { kind: "importProject"; file: string; preview: ImportPreview; machine?: MachineRef } /** Connect your agents: Claude Code, Cursor and Codex, and the command in terminals. */ | { kind: "connectAgents" } /** The first launch's welcome, ending in Add Project…; also Help › Show Welcome…. */ diff --git a/apps/macos/App/AppModel+Machines.swift b/apps/macos/App/AppModel+Machines.swift index c0580fe..e5d821b 100644 --- a/apps/macos/App/AppModel+Machines.swift +++ b/apps/macos/App/AppModel+Machines.swift @@ -109,3 +109,80 @@ extension AppModel { shown.state.needsUser } } + +// MARK: Its Projects + +// A Machine's Projects are changed there, through its connection, and come +// back as it reports them: nothing here edits a copy, and nothing waits for +// a Machine that isn't connected. +extension AppModel { + /// The Machines, to make a change on `machineID`. + func machines(for machineID: UUID) throws(LocalhostError) -> Machines { + guard let machines else { throw machinesError ?? .MachineNotFound(machineID) } + return machines + } + + /// The name of the Machine `place` is, or `nil` for this Mac. + func machineName(_ place: Place) -> String? { + guard case .machine(let machineID) = place else { return nil } + return shownMachine(machineID)?.machine.name ?? "its Machine" + } + + /// Why the Projects of `place` can't be changed now, or `nil` when they + /// can: another Machine while it isn't connected says how it is, and one + /// with an older localhost says to update it. + func reasonCantChange(_ place: Place) -> String? { + switch place { + case .thisMac: + return core == nil ? startupError?.message : nil + case .machine(let machineID): + guard let shown = shownMachine(machineID) else { return LocalhostError.MachineNotFound(machineID).message } + guard shown.isConnected else { return stateDescription(of: shown) } + return shown.managesProjects ? nil : LocalhostError.MachineNeedsUpdate(machine: shown.machine.name).message + } + } + + /// Whether Projects can be added to `place`, and its Projects changed, now. + func canChange(_ place: Place) -> Bool { + place == .thisMac ? core != nil : reasonCantChange(place) == nil + } + + /// The note a Machine's Projects show while its localhost is too old to + /// change them; `nil` elsewhere. + func needsUpdateNote(_ place: Place) -> String? { + guard case .machine(let machineID) = place, let shown = shownMachine(machineID), + shown.isConnected, !shown.managesProjects + else { return nil } + return LocalhostError.MachineNeedsUpdate(machine: shown.machine.name).message + } + + /// A folder on the Machine, for its folder picker; `nil` is its home folder. + func listDirectory( + _ path: String?, on machineID: UUID, showHidden: Bool, includeFiles: Bool + ) async throws(LocalhostError) -> DirectoryListing { + try await machines(for: machineID).listDirectory(path, on: machineID, showHidden: showHidden, includeFiles: includeFiles) + } + + /// Import Project… for `place`: the open panel on this Mac, the + /// Machine's own file picker on another. + func chooseProjectFile(on place: Place) { + switch place { + case .thisMac: isChoosingImportFile = true + case .machine(let machineID): presentedSheet = .chooseProjectFile(machine: machineID) + } + } + + /// Reads a Project file on the Machine and opens its review sheet, or + /// says why it can't be imported. + func openProjectFile(at path: String, on machineID: UUID) async { + let fileName = path.split(separator: "/").last.map(String.init) ?? path + do throws(LocalhostError) { + let file = try await machines(for: machineID).readProjectFile(at: path, on: machineID) + presentedSheet = .importProject( + try ProjectDocument(yaml: file.text), fileName: fileName, on: .machine(machineID), folderExists: file.folderExists + ) + } catch { + importFailure = ImportFailure(fileName: fileName, error: error) + } + } +} diff --git a/apps/macos/App/AppModel+ProjectFiles.swift b/apps/macos/App/AppModel+ProjectFiles.swift index a95dbca..2876d0d 100644 --- a/apps/macos/App/AppModel+ProjectFiles.swift +++ b/apps/macos/App/AppModel+ProjectFiles.swift @@ -59,13 +59,15 @@ extension AppModel { } } - /// The Project already using the document's Key, which the import would replace. - func projectClashing(with document: ProjectDocument) -> Project? { - projects.first { $0.key == document.key } + /// The Project of `place` already using the document's Key, which the import would replace. + func projectClashing(with document: ProjectDocument, on place: Place = .thisMac) -> Project? { + projects(on: place).first { $0.key == document.key } } - /// The Key "Keep both" would give the import. - func freeProjectKey(basedOn key: Key) async -> Key { - core?.library.freeProjectKey(basedOn: key) ?? key + /// The Key "Keep both" would give the import, by the core's rule; on + /// another Machine, among its Projects as shown. + func freeProjectKey(basedOn key: Key, on place: Place = .thisMac) async -> Key { + guard place == .thisMac else { return Project.freeKey(basedOn: key, among: projects(on: place)) } + return core?.library.freeProjectKey(basedOn: key) ?? key } } diff --git a/apps/macos/App/AppModel.swift b/apps/macos/App/AppModel.swift index 4755e86..eecb0cb 100644 --- a/apps/macos/App/AppModel.swift +++ b/apps/macos/App/AppModel.swift @@ -17,15 +17,21 @@ final class AppModel { var logs: Targets { services } } + /// The forms say where they make their changes: this Mac, or another + /// Machine, which makes them there. enum Sheet: Identifiable, Hashable { - case addProject - case editProject(UUID) - case addService(projectID: UUID) - case detectServices(projectID: UUID) - case editService(UUID) - case projectEnvironment(UUID) - /// The review step of an import, before anything is saved. - case importProject(ProjectDocument, fileName: String) + case addProject(on: Place = .thisMac) + case editProject(UUID, on: Place = .thisMac) + case addService(projectID: UUID, on: Place = .thisMac) + case detectServices(projectID: UUID, on: Place = .thisMac) + case editService(UUID, on: Place = .thisMac) + case projectEnvironment(UUID, on: Place = .thisMac) + /// The review step of an import, before anything is saved. On + /// another Machine, `folderExists` says whether the file's folder is + /// there; this Mac checks its own. + case importProject(ProjectDocument, fileName: String, on: Place = .thisMac, folderExists: Bool = true) + /// Import Project… on another Machine: choosing the Project file there. + case chooseProjectFile(machine: UUID) /// Every shortcut, grouped (⌘/). case keyboardShortcuts /// Connect Your Agents, as in Settings › Agents. @@ -62,8 +68,8 @@ final class AppModel { } enum Removal: Identifiable, Hashable { - case project(UUID) - case service(UUID) + case project(UUID, on: Place = .thisMac) + case service(UUID, on: Place = .thisMac) var id: Self { self } } @@ -275,7 +281,7 @@ final class AppModel { return project(id, on: selectedPlace) } - /// The selected Project when it is on this Mac: what can be edited. + /// The selected Project when it is on this Mac: its folder is here, and it can be exported. var selectedLocalProject: Project? { selectedPlace == .thisMac ? selectedProject : nil } @@ -345,9 +351,17 @@ final class AppModel { } } - /// A Key derived from `name` that no other Project uses. - func suggestedProjectKey(for name: String, excluding projectID: UUID? = nil) -> String { - Project.suggestedKey(for: name, among: projects, excluding: projectID).rawValue + /// The Projects of `place`: this Mac's, or another Machine's as last shown. + func projects(on place: Place) -> [Project] { + switch place { + case .thisMac: projects + case .machine(let machineID): shownMachine(machineID)?.projects ?? [] + } + } + + /// A Key derived from `name` that no other Project of `place` uses. + func suggestedProjectKey(for name: String, excluding projectID: UUID? = nil, on place: Place = .thisMac) -> String { + Project.suggestedKey(for: name, among: projects(on: place), excluding: projectID).rawValue } /// A Key derived from `name` that no other Service of the Project uses. @@ -524,18 +538,43 @@ final class AppModel { // MARK: Editing - /// Suggestions for a folder being added as a Project. - func suggestions(forFolderAt path: String) async -> [ServiceSuggestion] { - await ProjectScanner().scan(projectAt: path) + /// Suggestions for a folder being added as a Project, scanned where it is. + func suggestions(forFolderAt path: String, on place: Place = .thisMac) async throws(LocalhostError) -> [ServiceSuggestion] { + guard case .machine(let machineID) = place else { return await ProjectScanner().scan(projectAt: path) } + return try await machines(for: machineID).scan(projectAt: path, on: machineID) } /// Suggestions for an existing Project, without what its Services cover. - func suggestions(for project: Project) async -> [ServiceSuggestion] { - await ProjectScanner().scan(project) + func suggestions(for project: Project, on place: Place = .thisMac) async throws(LocalhostError) -> [ServiceSuggestion] { + guard case .machine(let machineID) = place else { return await ProjectScanner().scan(project) } + return try await machines(for: machineID).scan(project: project.id, on: machineID) + } + + /// The virtual environment a new Service of the Project would run in, found where the Project is. + func pythonEnvironment( + in project: Project, workingDirectory: String, commandLine: String, on place: Place = .thisMac + ) async -> String? { + guard case .machine(let machineID) = place else { + return await ProjectScanner().pythonEnvironment( + projectPath: project.path, workingDirectory: workingDirectory, commandLine: commandLine + ) + } + return try? await machines(for: machineID).pythonEnvironment( + inProject: project.id, workingDirectory: workingDirectory, commandLine: commandLine, on: machineID + ) } + /// Adds the Project and selects it. Another Machine's arrives once it + /// reports the change. @discardableResult - func addProject(name: String, key: String, path: String, services: [NewService] = []) async throws(LocalhostError) -> Project { + func addProject( + name: String, key: String, path: String, services: [NewService] = [], on place: Place = .thisMac + ) async throws(LocalhostError) -> Project { + if case .machine(let machineID) = place { + let project = try await machines(for: machineID).addProject(name: name, key: Key(key), path: path, services: services, on: machineID) + sidebarSelection = .machineProject(project.id, machine: machineID) + return project + } guard let library = core?.library else { throw .ProjectNotFound(UUID()) } let project = try await library.addProject(name: name, key: Key(key), path: path, services: services, origin: .mainWindow) projects = library.projects() @@ -543,18 +582,36 @@ final class AppModel { return project } - func editProject(_ id: UUID, name: String, key: String, path: String) async throws(LocalhostError) { + func editProject(_ id: UUID, name: String, key: String, path: String, on place: Place = .thisMac) async throws(LocalhostError) { + if case .machine(let machineID) = place { + try await machines(for: machineID).editProject(id: id, name: name, key: Key(key), path: path, on: machineID) + return + } guard let library = core?.library else { throw .ProjectNotFound(id) } try await library.editProject(id: id, name: name, key: Key(key), path: path, origin: .mainWindow) } - func setFavorite(_ id: UUID, _ isFavorite: Bool) { + func setFavorite(_ id: UUID, _ isFavorite: Bool, on place: Place = .thisMac) { + if case .machine(let machineID) = place { + Task { + await report { () throws(LocalhostError) in + try await machines(for: machineID).editProject(id: id, isFavorite: isFavorite, on: machineID) + } + } + return + } guard let library = core?.library else { return } Task { await report { () throws(LocalhostError) in try await library.editProject(id: id, isFavorite: isFavorite, origin: .mainWindow) } } } - /// Stops the Project's Services, then removes it. - func removeProject(_ id: UUID) async { + /// Stops the Project's Services, then removes it. Another Machine does + /// both, and deletes their logs, there. + func removeProject(_ id: UUID, on place: Place = .thisMac) async { + if case .machine(let machineID) = place { + await report { () throws(LocalhostError) in try await machines(for: machineID).removeProject(id: id, on: machineID) } + if sidebarSelection == .machineProject(id, machine: machineID) { sidebarSelection = nil } + return + } guard let core, let project = project(id) else { return } await report { () throws(LocalhostError) in for service in project.services { @@ -570,8 +627,19 @@ final class AppModel { func addService( to projectID: UUID, name: String, key: String, workingDirectory: String, commandLine: String, variables: [VariableInput], dependencies: [UUID], isExcludedFromStartAll: Bool, - port: Int?, url: String?, portCanChange: Bool, pythonEnvironment: String?, runBefore: String? + port: Int?, url: String?, portCanChange: Bool, pythonEnvironment: String?, runBefore: String?, + on place: Place = .thisMac ) async throws(LocalhostError) -> Service { + if case .machine(let machineID) = place { + let service = try await machines(for: machineID).addService( + toProject: projectID, name: name, key: Key(key), workingDirectory: workingDirectory, + commandLine: commandLine, variables: variables, dependencies: dependencies, + isExcludedFromStartAll: isExcludedFromStartAll, port: port, url: url, portCanChange: portCanChange, + pythonEnvironment: pythonEnvironment, runBefore: runBefore, on: machineID + ) + selectedServiceID = service.id + return service + } guard let library = core?.library else { throw .ProjectNotFound(projectID) } let service = try await library.addService( toProject: projectID, name: name, key: Key(key), workingDirectory: workingDirectory, @@ -584,7 +652,12 @@ final class AppModel { return service } - func addServices(_ services: [NewService], to projectID: UUID) async throws(LocalhostError) { + func addServices(_ services: [NewService], to projectID: UUID, on place: Place = .thisMac) async throws(LocalhostError) { + if case .machine(let machineID) = place { + let added = try await machines(for: machineID).addServices(services, toProject: projectID, on: machineID) + if let first = added.first { selectedServiceID = first.id } + return + } guard let library = core?.library else { throw .ProjectNotFound(projectID) } let added = try await library.addServices(services, toProject: projectID, origin: .mainWindow) projects = library.projects() @@ -592,8 +665,18 @@ final class AppModel { } /// Saves a reviewed import. On Replace, Services the file no longer has - /// are stopped first, as when removing them. - func importProject(_ document: ProjectDocument, onKeyClash: ProjectLibrary.KeyClash?) async throws(LocalhostError) { + /// are stopped first, as when removing them. Another Machine imports + /// the file's text into the document's folder there. + func importProject( + _ document: ProjectDocument, onKeyClash: ProjectLibrary.KeyClash?, on place: Place = .thisMac + ) async throws(LocalhostError) { + if case .machine(let machineID) = place { + let project = try await machines(for: machineID).importProject( + text: document.yaml, path: document.path, onKeyClash: onKeyClash, on: machineID + ) + sidebarSelection = .machineProject(project.id, machine: machineID) + return + } guard let core else { throw .ProjectNotFound(UUID()) } if onKeyClash == .replace, let existing = projectClashing(with: document) { let keptKeys = Set(document.services.map(\.key)) @@ -613,8 +696,19 @@ final class AppModel { func editService( _ id: UUID, name: String, key: String, workingDirectory: String, commandLine: String, variables: [VariableInput], dependencies: [UUID], isExcludedFromStartAll: Bool, - port: Int?, url: String?, portCanChange: Bool, pythonEnvironment: String?, runBefore: String? + port: Int?, url: String?, portCanChange: Bool, pythonEnvironment: String?, runBefore: String?, + on place: Place = .thisMac ) async throws(LocalhostError) { + if case .machine(let machineID) = place { + try await machines(for: machineID).editService( + id: id, name: name, key: Key(key), workingDirectory: workingDirectory, + commandLine: commandLine, variables: variables, dependencies: dependencies, + isExcludedFromStartAll: isExcludedFromStartAll, port: .some(port), url: .some(url), + portCanChange: portCanChange, pythonEnvironment: .some(pythonEnvironment), runBefore: .some(runBefore), + on: machineID + ) + return + } guard let library = core?.library else { throw .ServiceNotFound(id) } try await library.editService( id: id, name: name, key: Key(key), workingDirectory: workingDirectory, @@ -636,16 +730,36 @@ final class AppModel { var variables: [VariableDraft] } - func setActiveProfile(_ profileID: UUID?, inProject projectID: UUID) { + func setActiveProfile(_ profileID: UUID?, inProject projectID: UUID, on place: Place = .thisMac) { + if case .machine(let machineID) = place { + Task { + await report { () throws(LocalhostError) in + try await machines(for: machineID).setActiveProfile(profileID, inProject: projectID, on: machineID) + } + } + return + } guard let library = core?.library else { return } Task { await report { () throws(LocalhostError) in try await library.setActiveProfile(profileID, inProject: projectID, origin: .mainWindow) } } } /// Saves the Environment sheet: the Project's variables, its Profiles - /// (added, edited, removed), then which one is active. + /// (added, edited, removed), then which one is active. Another Machine + /// saves it all at once. func saveEnvironment( - of projectID: UUID, variables: [VariableInput], profiles: [ProfileDraft], activeDraftID: UUID? + of projectID: UUID, variables: [VariableInput], profiles: [ProfileDraft], activeDraftID: UUID?, + on place: Place = .thisMac ) async throws(LocalhostError) { + if case .machine(let machineID) = place { + let inputs = profiles.map { draft in + ProfileInput(profileId: draft.profileID, name: draft.name, variables: draft.variables.compactMap(\.input)) + } + try await machines(for: machineID).saveEnvironment( + ofProject: projectID, variables: variables, profiles: inputs, + activeProfile: profiles.firstIndex { $0.id == activeDraftID }, on: machineID + ) + return + } guard let library = core?.library, let project = project(projectID) else { throw .ProjectNotFound(projectID) } try await library.editProject(id: projectID, variables: variables, origin: .mainWindow) let kept = Set(profiles.compactMap(\.profileID)) @@ -666,10 +780,14 @@ final class AppModel { try await library.setActiveProfile(activeProfileID, inProject: projectID, origin: .mainWindow) } - /// A Secret's stored value, to reveal it; `nil` if it has none. - func secretValue(named name: String, in layer: VariableLayer) async -> String? { - guard let library = core?.library else { return nil } + /// A Secret's stored value, to reveal it; `nil` if it has none. Another + /// Machine's is read there each time, never kept here. + func secretValue(named name: String, in layer: VariableLayer, on place: Place = .thisMac) async -> String? { do { + if case .machine(let machineID) = place { + return try await machines(for: machineID).secretValue(named: name, in: layer, on: machineID) + } + guard let library = core?.library else { return nil } return try await library.secretValue(named: name, in: layer) } catch { actionError = error @@ -677,8 +795,14 @@ final class AppModel { } } - /// Stops the Service, then removes it. - func removeService(_ id: UUID) async { + /// Stops the Service, then removes it. Another Machine does both, and + /// deletes its logs, there. + func removeService(_ id: UUID, on place: Place = .thisMac) async { + if case .machine(let machineID) = place { + await report { () throws(LocalhostError) in try await machines(for: machineID).removeService(id: id, on: machineID) } + if selectedServiceID == id { selectedServiceID = nil } + return + } guard let core else { return } await report { () throws(LocalhostError) in try await core.services.stop(id, origin: .mainWindow) @@ -819,7 +943,7 @@ final class AppModel { /// The welcome was finished or skipped: it never opens by itself again. func finishWelcome(addingProject: Bool) { updateOnboarding { $0.hasSeenWelcome = true } - presentedSheet = addingProject ? .addProject : nil + presentedSheet = addingProject ? .addProject() : nil } /// Help › Show Welcome…: the first run's welcome on request, Projects or not. diff --git a/apps/macos/App/CommandPalette.swift b/apps/macos/App/CommandPalette.swift index e6d5a3e..fbcb5b2 100644 --- a/apps/macos/App/CommandPalette.swift +++ b/apps/macos/App/CommandPalette.swift @@ -31,7 +31,7 @@ extension AppModel { /// Project. The rest (ids starting `other:`) are reachable by typing. func paletteItems() -> [PaletteItem] { var items: [PaletteItem] = [] - // Another Machine's Projects are controlled from the main window for now. + // Another Machine's Services are started from the main window for now; its changes are in `machineItems()`. let selected = selectedLocalProject if let service = selectedService, let selected { items += serviceActions(service, in: selected, isSelected: true) @@ -49,10 +49,11 @@ extension AppModel { }) if core != nil { items.append(PaletteItem(id: "new-project", title: "New Project…", icon: .symbol("folder.badge.plus"), - shortcut: "⌘N", keywords: "add") { [weak self] in - self?.presentedSheet = .addProject + shortcut: selectedPlace == .thisMac ? "⌘N" : nil, keywords: "add") { [weak self] in + self?.presentedSheet = .addProject() }) } + items += machineItems() items.append(PaletteItem(id: "keyboard-shortcuts", title: "Keyboard Shortcuts", icon: .symbol("keyboard"), shortcut: "⌘/", keywords: "help keys cheat sheet") { [weak self] in self?.presentedSheet = .keyboardShortcuts @@ -111,6 +112,54 @@ extension AppModel { // MARK: Items + /// Another Machine's: changes to the selected Project there, then a new + /// or imported Project on each Machine that can take changes. Its + /// Services are started and stopped from the main window for now. + private func machineItems() -> [PaletteItem] { + var items: [PaletteItem] = [] + if case .machine = selectedPlace, let project = selectedProject, canChange(selectedPlace) { + let place = selectedPlace + let keywords = "\(project.key) \(machineName(place) ?? "")" + items.append(PaletteItem(id: "machine-new-service:\(project.id)", title: "New Service in \(project.name)…", + icon: .symbol("plus"), shortcut: "⇧⌘N", keywords: "add \(keywords)", boost: 1) { [weak self] in + self?.presentedSheet = .addService(projectID: project.id, on: place) + }) + items.append(PaletteItem(id: "machine-detect:\(project.id)", title: "Detect Services in \(project.name)…", + icon: .symbol("sparkle.magnifyingglass"), keywords: "scan suggest \(keywords)", boost: 1) { [weak self] in + self?.presentedSheet = .detectServices(projectID: project.id, on: place) + }) + items.append(PaletteItem(id: "machine-edit:\(project.id)", title: "Edit \(project.name)…", + icon: .symbol("pencil"), keywords: "project \(keywords)", boost: 1) { [weak self] in + self?.presentedSheet = .editProject(project.id, on: place) + }) + items.append(PaletteItem(id: "machine-environment:\(project.id)", title: "Edit Environment of \(project.name)…", + icon: .symbol("square.3.layers.3d"), keywords: "variables profiles secrets \(keywords)", boost: 1) { [weak self] in + self?.presentedSheet = .projectEnvironment(project.id, on: place) + }) + items.append(PaletteItem(id: "machine-favorite:\(project.id)", + title: "\(project.isFavorite ? "Unfavorite" : "Favorite") \(project.name)", + icon: .symbol(project.isFavorite ? "star.slash" : "star"), keywords: keywords, boost: 1) { [weak self] in + self?.setFavorite(project.id, !project.isFavorite, on: place) + }) + } + for shown in shownMachines where canChange(.machine(shown.id)) { + let place = Place.machine(shown.id) + let prefix = selectedPlace == place ? "" : "other:" + let name = shown.machine.name + items.append(PaletteItem(id: "\(prefix)machine-new-project:\(shown.id)", title: "New Project on \(name)…", + icon: .symbol("folder.badge.plus"), shortcut: selectedPlace == place ? "⌘N" : nil, + keywords: "add machine \(shown.machine.destination)") { [weak self] in + self?.presentedSheet = .addProject(on: place) + }) + items.append(PaletteItem(id: "other:machine-import:\(shown.id)", title: "Import Project on \(name)…", + icon: .symbol("square.and.arrow.down"), + keywords: "project file yaml machine \(shown.machine.destination)") { [weak self] in + self?.chooseProjectFile(on: place) + }) + } + return items + } + private func projectJump(_ project: Project, index: Int) -> PaletteItem { PaletteItem( id: "project:\(project.id)", title: project.name, diff --git a/apps/macos/App/LocalhostApp.swift b/apps/macos/App/LocalhostApp.swift index 0977348..8e90b85 100644 --- a/apps/macos/App/LocalhostApp.swift +++ b/apps/macos/App/LocalhostApp.swift @@ -119,24 +119,29 @@ struct AppCommands: Commands { Divider() } CommandGroup(replacing: .newItem) { - Button("New Project…") { model.presentedSheet = .addProject } - .keyboardShortcut("n") - .disabled(model.core == nil) + // With another Machine's Project selected, they act on that Machine. + let place = model.selectedPlace + let project = model.selectedProject + Button(model.machineName(place).map { "New Project on \($0)…" } ?? "New Project…") { + model.presentedSheet = .addProject(on: place) + } + .keyboardShortcut("n") + .disabled(!model.canChange(place)) Button("New Service…") { - if let project = model.selectedLocalProject { model.presentedSheet = .addService(projectID: project.id) } + if let project { model.presentedSheet = .addService(projectID: project.id, on: place) } } .keyboardShortcut("n", modifiers: [.command, .shift]) - .disabled(model.selectedLocalProject == nil) + .disabled(project == nil || !model.canChange(place)) Button("Detect Services…") { - if let project = model.selectedLocalProject { model.presentedSheet = .detectServices(projectID: project.id) } + if let project { model.presentedSheet = .detectServices(projectID: project.id, on: place) } } - .disabled(model.selectedLocalProject == nil) + .disabled(project == nil || !model.canChange(place)) Divider() - Button("Import Project…") { + Button(model.machineName(place).map { "Import Project on \($0)…" } ?? "Import Project…") { openWindow(id: "main") - model.isChoosingImportFile = true + model.chooseProjectFile(on: place) } - .disabled(model.core == nil) + .disabled(!model.canChange(place)) Button("Export Project…") { openWindow(id: "main") if let project = model.selectedLocalProject { model.exportProject(project.id) } @@ -173,12 +178,11 @@ struct AppCommands: Commands { .keyboardShortcut("o", modifiers: [.command, .shift]) .disabled(!isLive || model.selectedService.flatMap { model.urlToOpen($0, on: place) } == nil || !model.isReachable(place)) Divider() - // Another Machine's Services are edited there. - let localService = place == .thisMac ? model.selectedService : nil - Button("Edit Service…") { localService.map { model.presentedSheet = .editService($0.id) } } - .disabled(localService == nil) - Button("Remove Service…") { localService.map { model.pendingRemoval = .service($0.id) } } - .disabled(localService == nil) + let editable = model.canChange(place) ? model.selectedService : nil + Button("Edit Service…") { editable.map { model.presentedSheet = .editService($0.id, on: place) } } + .disabled(editable == nil) + Button("Remove Service…") { editable.map { model.pendingRemoval = .service($0.id, on: place) } } + .disabled(editable == nil) } CommandMenu("Project") { let place = model.selectedPlace @@ -191,19 +195,19 @@ struct AppCommands: Commands { .disabled(!(shown.map { $0.services.contains { model.status(of: $0, on: place).state.isActive } } ?? false) || !model.isReachable(place)) Divider() - let project = model.selectedLocalProject - Button("Edit Project…") { project.map { model.presentedSheet = .editProject($0.id) } } + let project = model.canChange(place) ? shown : nil + Button("Edit Project…") { project.map { model.presentedSheet = .editProject($0.id, on: place) } } .disabled(project == nil) - Button("Edit Environment…") { project.map { model.presentedSheet = .projectEnvironment($0.id) } } + Button("Edit Environment…") { project.map { model.presentedSheet = .projectEnvironment($0.id, on: place) } } .disabled(project == nil) Button(project?.isFavorite == true ? "Unfavorite" : "Favorite") { - project.map { model.setFavorite($0.id, !$0.isFavorite) } + project.map { model.setFavorite($0.id, !$0.isFavorite, on: place) } } .disabled(project == nil) Divider() FolderActionCommands(model: model) Divider() - Button("Remove Project…") { project.map { model.pendingRemoval = .project($0.id) } } + Button("Remove Project…") { project.map { model.pendingRemoval = .project($0.id, on: place) } } .disabled(project == nil) } } diff --git a/apps/macos/App/Views/EnvironmentForm.swift b/apps/macos/App/Views/EnvironmentForm.swift index 9a0469d..4eac782 100644 --- a/apps/macos/App/Views/EnvironmentForm.swift +++ b/apps/macos/App/Views/EnvironmentForm.swift @@ -2,11 +2,12 @@ import LocalhostCore import SwiftUI /// Edits a Project's variables and its Environment Profiles, and which -/// Profile is active. +/// Profile is active. Another Machine's are saved there, Secrets included. struct EnvironmentForm: View { @Environment(AppModel.self) private var model @Environment(\.dismiss) private var dismiss let project: Project + var place: AppModel.Place = .thisMac @State private var variables: [VariableDraft] = [] @State private var profiles: [AppModel.ProfileDraft] = [] @@ -18,18 +19,18 @@ struct EnvironmentForm: View { FormSheet( systemImage: "square.3.layers.3d", title: "Environment", - subtitle: Text("for **\(project.name)**"), - hint: "Running services show “restart to apply” when their environment changes.", + subtitle: subtitle, + hint: model.reasonCantChange(place) ?? "Running services show “restart to apply” when their environment changes.", error: error, primaryTitle: "Save", - isPrimaryDisabled: isSaving, + isPrimaryDisabled: isSaving || !model.canChange(place), width: 600, cancel: { dismiss() }, primary: { Task { await save() } } ) { Field(title: "Project variables", note: "every service gets these", hint: "A service’s own variables override them.") { - VariableEditor(variables: $variables, layer: .project(project.id)) + VariableEditor(variables: $variables, layer: .project(project.id), place: place) } VStack(alignment: .leading, spacing: 10) { HStack { @@ -99,10 +100,15 @@ struct EnvironmentForm: View { .foregroundStyle(.secondary) .help("Remove this profile") } - VariableEditor(variables: binding.variables, layer: profile.profileID.map { .profile($0) }) + VariableEditor(variables: binding.variables, layer: profile.profileID.map { .profile($0) }, place: place) } } + private var subtitle: Text { + guard let machine = model.machineName(place) else { return Text("for **\(project.name)**") } + return Text("for **\(project.name)** on \(machine)") + } + private var suggestedProfileName: String { let names = Set(profiles.map(\.name)) return ["Development", "Testing", "Staging", "Production"].first { !names.contains($0) } ?? "Profile \(profiles.count + 1)" @@ -113,7 +119,8 @@ struct EnvironmentForm: View { defer { isSaving = false } do { try await model.saveEnvironment( - of: project.id, variables: variables.compactMap(\.input), profiles: profiles, activeDraftID: activeDraftID + of: project.id, variables: variables.compactMap(\.input), profiles: profiles, activeDraftID: activeDraftID, + on: place ) dismiss() } catch { diff --git a/apps/macos/App/Views/FormKit.swift b/apps/macos/App/Views/FormKit.swift index 387b040..3977e70 100644 --- a/apps/macos/App/Views/FormKit.swift +++ b/apps/macos/App/Views/FormKit.swift @@ -15,6 +15,9 @@ struct FormSheet: View { var error: String? let primaryTitle: String var isPrimaryDisabled = false + /// Whether ↩ triggers the primary action; off while ↩ means something + /// else, e.g. opening the selected folder. + var isPrimaryDefault = true var width: CGFloat = 560 let cancel: () -> Void let primary: () -> Void @@ -72,7 +75,7 @@ struct FormSheet: View { .keyboardShortcut(.cancelAction) Button(primaryTitle, action: primary) .buttonStyle(AccentButtonStyle()) - .keyboardShortcut(.defaultAction) + .keyboardShortcut(isPrimaryDefault ? KeyboardShortcut.defaultAction : nil) .disabled(isPrimaryDisabled) } .padding(.horizontal, 24) @@ -86,8 +89,10 @@ struct FormSheet: View { } /// A folder's path in a field box; choosing opens the folder picker. +/// Another Machine's paths are shown as they are: `~` there isn't this Mac's. struct FolderButton: View { let path: String + var isOnThisMac = true let choose: () -> Void var body: some View { @@ -95,7 +100,7 @@ struct FolderButton: View { HStack(spacing: 8) { Image(systemName: "folder") .foregroundStyle(.secondary) - Text(path.isEmpty ? "Choose a folder…" : (path as NSString).abbreviatingWithTildeInPath) + Text(path.isEmpty ? "Choose a folder…" : isOnThisMac ? (path as NSString).abbreviatingWithTildeInPath : path) .font(.system(size: 12.5, design: .monospaced)) .foregroundStyle(path.isEmpty ? .secondary : .primary) .lineLimit(1) diff --git a/apps/macos/App/Views/GetStartedView.swift b/apps/macos/App/Views/GetStartedView.swift index a8d8626..325355d 100644 --- a/apps/macos/App/Views/GetStartedView.swift +++ b/apps/macos/App/Views/GetStartedView.swift @@ -104,7 +104,7 @@ struct GetStartedView: View { let selected = model.projects.first { $0.id == model.selectedProjectID } switch item.step { case .project: - model.presentedSheet = .addProject + model.presentedSheet = .addProject() case .service: let target = selected?.services.isEmpty == true ? selected : model.projects.first { $0.services.isEmpty } if let target { model.presentedSheet = .detectServices(projectID: target.id) } diff --git a/apps/macos/App/Views/ImportProjectForm.swift b/apps/macos/App/Views/ImportProjectForm.swift index c449ea5..a980274 100644 --- a/apps/macos/App/Views/ImportProjectForm.swift +++ b/apps/macos/App/Views/ImportProjectForm.swift @@ -6,36 +6,43 @@ import UniformTypeIdentifiers /// Mac, what to do if its Key is taken, and what the file brings (Services, /// environment, and the Secrets that still need values). The file was /// validated when it was read; nothing is saved until Import or Replace. +/// On another Machine, the file and the folder are there, and so is the +/// Project it adds. struct ImportProjectForm: View { @Environment(AppModel.self) private var model @Environment(\.dismiss) private var dismiss let document: ProjectDocument let fileName: String + var place: AppModel.Place = .thisMac + /// On another Machine, whether the file's folder is there. + var remoteFolderExists = true @State private var path = "" @State private var choice: ProjectLibrary.KeyClash = .keepBoth @State private var freeKey: Key? @State private var isChoosingFolder = false + /// Another Machine's folder chosen in its picker, which only lists folders that are there. + @State private var isRemoteFolderChosen = false @State private var error: String? @State private var isSaving = false var body: some View { - let clash = model.projectClashing(with: document) + let clash = model.projectClashing(with: document, on: place) let isReplacing = clash != nil && choice == .replace FormSheet( systemImage: "square.and.arrow.down", title: "Import \(document.name)", - subtitle: Text("from ") + Text(fileName).monospaced(), - hint: !folderExists ? nil : isReplacing ? "Replaces “\(clash?.name ?? "")”" : "↩ to import", + subtitle: Text("from ") + Text(fileName).monospaced() + Text(model.machineName(place).map { " on \($0)" } ?? ""), + hint: model.reasonCantChange(place) ?? (!folderExists ? nil : isReplacing ? "Replaces “\(clash?.name ?? "")”" : "↩ to import"), error: error, primaryTitle: isReplacing ? "Replace" : "Import", - isPrimaryDisabled: !folderExists || isSaving, + isPrimaryDisabled: !folderExists || isSaving || !model.canChange(place), width: 600, cancel: { dismiss() }, primary: { Task { await save(onKeyClash: clash == nil ? nil : choice) } } ) { - Field(title: "Folder", hint: folderExists ? nil : "This folder isn’t on this Mac. Choose where the project is.") { - FolderButton(path: path) { isChoosingFolder = true } + Field(title: "Folder", hint: folderExists ? nil : missingFolderHint) { + FolderButton(path: path, isOnThisMac: place == .thisMac) { isChoosingFolder = true } } if let clash { Field(title: "Key", note: "“\(document.key)” is already used by \(clash.name)", @@ -92,14 +99,34 @@ struct ImportProjectForm: View { } } } - .fileImporter(isPresented: $isChoosingFolder, allowedContentTypes: [.folder]) { result in + .fileImporter(isPresented: Binding { isChoosingFolder && place == .thisMac } set: { isChoosingFolder = $0 }, + allowedContentTypes: [.folder]) { result in if case .success(let url) = result { path = url.path } } + .sheet(isPresented: Binding { isChoosingFolder && place != .thisMac } set: { isChoosingFolder = $0 }) { + if case .machine(let machineID) = place { + RemoteFolderPicker(machineID: machineID, startingAt: remoteStartingFolder) { folder in + path = folder + isRemoteFolderChosen = true + } + } + } .onAppear { path = document.path } - .task { freeKey = await model.freeProjectKey(basedOn: document.key) } + .task { freeKey = await model.freeProjectKey(basedOn: document.key, on: place) } + } + + private var missingFolderHint: String { + guard let machine = model.machineName(place) else { return "This folder isn’t on this Mac. Choose where the project is." } + return "This folder isn’t on \(machine). Choose where the project is." + } + + /// The file's folder if it is there, else the Machine's home folder. + private var remoteStartingFolder: String? { + folderExists && !path.isEmpty ? path : nil } private var folderExists: Bool { + if place != .thisMac { return isRemoteFolderChosen || remoteFolderExists } var isDirectory: ObjCBool = false return FileManager.default.fileExists(atPath: (path as NSString).expandingTildeInPath, isDirectory: &isDirectory) && isDirectory.boolValue @@ -110,7 +137,7 @@ struct ImportProjectForm: View { let keptKeys = Set(document.services.map(\.key)) let removed = existing.services.filter { !keptKeys.contains($0.key) } guard !removed.isEmpty else { return nil } - let names = removed.map { model.status(of: $0).state.isActive ? "\($0.name) (running, stopped first)" : $0.name } + let names = removed.map { model.status(of: $0, on: place).state.isActive ? "\($0.name) (running, stopped first)" : $0.name } return "Removes " + names.joined(separator: ", ") + ", which the file doesn’t have." } @@ -138,7 +165,7 @@ struct ImportProjectForm: View { isSaving = true defer { isSaving = false } do { - try await model.importProject(document, onKeyClash: onKeyClash) + try await model.importProject(document, onKeyClash: onKeyClash, on: place) dismiss() } catch { self.error = error.message diff --git a/apps/macos/App/Views/LogPane.swift b/apps/macos/App/Views/LogPane.swift index 4541e92..2fda83d 100644 --- a/apps/macos/App/Views/LogPane.swift +++ b/apps/macos/App/Views/LogPane.swift @@ -284,8 +284,8 @@ private struct FailedBanner: View { .buttonStyle(AccentButtonStyle(isCompact: true)) .help("Start (⌘R)") .disabled(!model.isReachable(model.selectedPlace)) - if model.selectedPlace == .thisMac { - Button("Edit Service…") { model.presentedSheet = .editService(service.id) } + if model.canChange(model.selectedPlace) { + Button("Edit Service…") { model.presentedSheet = .editService(service.id, on: model.selectedPlace) } .buttonStyle(PillButtonStyle(isCompact: true)) } Button("Hide", systemImage: "xmark") { dismiss() } diff --git a/apps/macos/App/Views/MainView.swift b/apps/macos/App/Views/MainView.swift index 36ebf06..1802b38 100644 --- a/apps/macos/App/Views/MainView.swift +++ b/apps/macos/App/Views/MainView.swift @@ -30,7 +30,7 @@ struct MainView: View { VStack(spacing: 12) { // One primary action; the rarer ones as links under it. if model.core != nil { - Button("Add Project…") { model.presentedSheet = .addProject } + Button("Add Project…") { model.presentedSheet = .addProject() } .buttonStyle(AccentButtonStyle()) } HStack(spacing: 14) { @@ -102,20 +102,26 @@ struct MainView: View { .background(ColumnNavigation(focusRequest: model.columnFocusRequest, isShowingPalette: model.isShowingPalette)) .sheet(item: $model.presentedSheet) { sheet in switch sheet { - case .addProject: - ProjectForm(editing: nil) - case .editProject(let id): - ProjectForm(editing: model.project(id)) - case .addService(let projectID): - if let project = model.project(projectID) { ServiceForm(project: project, editing: nil) } - case .detectServices(let projectID): - if let project = model.project(projectID) { DetectServicesForm(project: project) } - case .editService(let id): - if let (project, service) = model.service(id) { ServiceForm(project: project, editing: service) } - case .projectEnvironment(let id): - if let project = model.project(id) { EnvironmentForm(project: project) } - case .importProject(let document, let fileName): - ImportProjectForm(document: document, fileName: fileName) + case .addProject(let place): + ProjectForm(editing: nil, place: place) + case .editProject(let id, let place): + ProjectForm(editing: model.project(id, on: place), place: place) + case .addService(let projectID, let place): + if let project = model.project(projectID, on: place) { ServiceForm(project: project, editing: nil, place: place) } + case .detectServices(let projectID, let place): + if let project = model.project(projectID, on: place) { DetectServicesForm(project: project, place: place) } + case .editService(let id, let place): + if let (project, service) = model.service(id, on: place) { + ServiceForm(project: project, editing: service, place: place) + } + case .projectEnvironment(let id, let place): + if let project = model.project(id, on: place) { EnvironmentForm(project: project, place: place) } + case .importProject(let document, let fileName, let place, let folderExists): + ImportProjectForm(document: document, fileName: fileName, place: place, remoteFolderExists: folderExists) + case .chooseProjectFile(let machineID): + RemoteFolderPicker(machineID: machineID, mode: .projectFile) { path in + Task { await model.openProjectFile(at: path, on: machineID) } + } case .keyboardShortcuts: KeyboardShortcutsView() case .connectAgents: @@ -148,8 +154,8 @@ struct MainView: View { Button("Remove", role: .destructive) { Task { switch removal { - case .project(let id): await model.removeProject(id) - case .service(let id): await model.removeService(id) + case .project(let id, let place): await model.removeProject(id, on: place) + case .service(let id, let place): await model.removeService(id, on: place) } } } @@ -215,15 +221,15 @@ struct MainView: View { private var removalTitle: String { switch model.pendingRemoval { - case .project(let id): "Remove “\(model.project(id)?.name ?? "project")”?" - case .service(let id): "Remove “\(model.service(id)?.service.name ?? "service")”?" + case .project(let id, let place): "Remove “\(model.project(id, on: place)?.name ?? "project")”?" + case .service(let id, let place): "Remove “\(model.service(id, on: place)?.service.name ?? "service")”?" case nil: "" } } private func removalMessage(_ removal: AppModel.Removal) -> String { var message = "Running services are stopped first. Their configuration is deleted; the project folder is not touched." - if case .service(let id) = removal, let (project, _) = model.service(id) { + if case .service(let id, let place) = removal, let (project, _) = model.service(id, on: place) { let dependents = project.dependents(of: id).map { "“\($0.name)”" } if !dependents.isEmpty { message += "\n\n\(ListFormatter.localizedString(byJoining: dependents)) will no longer depend on it." diff --git a/apps/macos/App/Views/ProjectDetailView.swift b/apps/macos/App/Views/ProjectDetailView.swift index 55f90a4..e380ba8 100644 --- a/apps/macos/App/Views/ProjectDetailView.swift +++ b/apps/macos/App/Views/ProjectDetailView.swift @@ -2,7 +2,7 @@ import LocalhostCore import SwiftUI /// A Project's Services with their state and Start / Stop / Restart. Those -/// of another Machine look and act the same, but are edited there. +/// of another Machine look and act the same; their changes are made there. struct ProjectDetailView: View { @Environment(AppModel.self) private var model let project: Project @@ -31,24 +31,29 @@ struct ProjectDetailView: View { .contextMenu(forSelectionType: UUID.self) { ids in if let id = ids.first, id != AppModel.allServicesID, let (_, service) = model.service(id, on: place) { serviceStateButtons(service) + Divider() + Button("Edit Service…") { model.presentedSheet = .editService(id, on: place) } + .disabled(!model.canChange(place)) if place == .thisMac { - Divider() - Button("Edit Service…") { model.presentedSheet = .editService(id) } Divider() if let folder = model.folder(ofService: id) { FolderActionButtons(folder: folder) } - Divider() - Button("Remove Service…", role: .destructive) { model.pendingRemoval = .service(id) } } + Divider() + Button("Remove Service…", role: .destructive) { model.pendingRemoval = .service(id, on: place) } + .disabled(!model.canChange(place)) } } primaryAction: { ids in - if place == .thisMac, let id = ids.first, id != AppModel.allServicesID { model.presentedSheet = .editService(id) } + if model.canChange(place), let id = ids.first, id != AppModel.allServicesID { + model.presentedSheet = .editService(id, on: place) + } } .overlay { - if project.services.isEmpty, case .machine(let machineID) = place { + if project.services.isEmpty, let reason = model.reasonCantChange(place) { + // Another Machine that can't take changes now: why, rather than buttons that fail. ContentUnavailableView { Label("No Services", systemImage: "terminal") } description: { - Text("Add services to this project on \(model.shownMachine(machineID)?.machine.name ?? "its machine").") + Text(reason) } } else if project.services.isEmpty { ContentUnavailableView { @@ -56,15 +61,21 @@ struct ProjectDetailView: View { } description: { Text(Onboarding.serviceConcept) } actions: { - Button("Detect Services…") { model.presentedSheet = .detectServices(projectID: project.id) } + Button("Detect Services…") { model.presentedSheet = .detectServices(projectID: project.id, on: place) } .buttonStyle(AccentButtonStyle()) - Button("Add Service…") { model.presentedSheet = .addService(projectID: project.id) } + Button("Add Service…") { model.presentedSheet = .addService(projectID: project.id, on: place) } .buttonStyle(PillButtonStyle()) } } } .safeAreaInset(edge: .bottom, spacing: 0) { - if !project.services.isEmpty, place == .thisMac { addServiceRow } + if let note = model.needsUpdateNote(place), !project.services.isEmpty { + updateNote(note) + } else if !project.services.isEmpty { + addServiceRow + .disabled(!model.canChange(place)) + .help(model.reasonCantChange(place) ?? "") + } } .columnGlass() .navigationTitle(project.name) @@ -96,8 +107,18 @@ struct ProjectDetailView: View { .disabled(!model.isReachable(place)) } + /// Another Machine with an older localhost: its Projects are shown and run, not changed. + private func updateNote(_ note: String) -> some View { + Label(note, systemImage: "info.circle") + .font(.callout) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 16) + .padding(.vertical, 10) + } + private var addServiceRow: some View { - Button { model.presentedSheet = .addService(projectID: project.id) } label: { + Button { model.presentedSheet = .addService(projectID: project.id, on: place) } label: { HStack(spacing: 7) { Image(systemName: "plus") .font(.system(size: 11, weight: .semibold)) @@ -126,8 +147,7 @@ struct ProjectToolbar: ToolbarContent { var body: some ToolbarContent { ToolbarItemGroup(placement: .primaryAction) { - // Another Machine's Profiles, configuration and folder are changed there. - if !project.profiles.isEmpty, place == .thisMac { + if !project.profiles.isEmpty { profileMenu } Button("Start All", systemImage: "play.fill") { model.startAll(inProject: project.id, on: place) } @@ -140,10 +160,25 @@ struct ProjectToolbar: ToolbarContent { .disabled(!project.services.contains { model.status(of: $0, on: place).state.isActive } || !model.isReachable(place)) if place == .thisMac { moreMenu + } else { + machineMoreMenu } } } + /// Another Machine's: its configuration is changed there; its folder isn't on this Mac. + private var machineMoreMenu: some View { + MoreMenu(help: "More actions for this project") { + if let reason = model.reasonCantChange(place) { + Text(reason) + } + MachineProjectEditButtons(project: project, place: place) + Divider() + Button("Remove Project…", role: .destructive) { model.pendingRemoval = .project(project.id, on: place) } + .disabled(!model.canChange(place)) + } + } + private var moreMenu: some View { Group { MoreMenu(help: "More actions for this project") { @@ -176,15 +211,17 @@ struct ProjectToolbar: ToolbarContent { Menu { Picker("Environment Profile", selection: Binding { project.activeProfileID - } set: { model.setActiveProfile($0, inProject: project.id) }) { + } set: { model.setActiveProfile($0, inProject: project.id, on: place) }) { Text("No Profile").tag(UUID?.none) ForEach(project.profiles) { profile in Text(profile.name).tag(UUID?.some(profile.id)) } } .pickerStyle(.inline) + .disabled(!model.canChange(place)) Divider() - Button("Edit Environment…") { model.presentedSheet = .projectEnvironment(project.id) } + Button("Edit Environment…") { model.presentedSheet = .projectEnvironment(project.id, on: place) } + .disabled(!model.canChange(place)) } label: { Label(project.activeProfile?.name ?? "No Profile", systemImage: "square.3.layers.3d") .labelStyle(.titleAndIcon) @@ -350,8 +387,8 @@ struct ServiceAccessibilityActions: View { Button("Start") { model.start(service.id, on: place) } } } - if place == .thisMac { - Button("Edit Service") { model.presentedSheet = .editService(service.id) } + if model.canChange(place) { + Button("Edit Service") { model.presentedSheet = .editService(service.id, on: place) } } } } @@ -394,8 +431,8 @@ struct ServiceActions: View { Button("Start") { model.start(service.id, on: place) } .buttonStyle(PillButtonStyle(isProminent: true, isCompact: true)) .help("Start (⌘R)") - if place == .thisMac { - Button("Edit…") { model.presentedSheet = .editService(service.id) } + if place == .thisMac || model.canChange(place) { + Button("Edit…") { model.presentedSheet = .editService(service.id, on: place) } .buttonStyle(PillButtonStyle(isCompact: true)) .help("Edit Service") } diff --git a/apps/macos/App/Views/ProjectForm.swift b/apps/macos/App/Views/ProjectForm.swift index 071a445..548e607 100644 --- a/apps/macos/App/Views/ProjectForm.swift +++ b/apps/macos/App/Views/ProjectForm.swift @@ -5,10 +5,12 @@ import UniformTypeIdentifiers /// Adds a Project (folder, name, key derived from the name) or edits one. /// When adding, the folder is scanned as soon as it is chosen and the /// Suggestions are reviewed in the same sheet, then saved with the Project. +/// On another Machine, the folder is chosen and scanned there. struct ProjectForm: View { @Environment(AppModel.self) private var model @Environment(\.dismiss) private var dismiss let editing: Project? + var place: AppModel.Place = .thisMac @State private var path = "" @State private var name = "" @@ -27,18 +29,18 @@ struct ProjectForm: View { var body: some View { FormSheet( systemImage: "folder", - title: editing == nil ? "New Project" : "Edit \(editing?.name ?? "Project")", - subtitle: Text("A folder whose services localhost runs."), + title: title, + subtitle: subtitle, hint: hint, error: error, primaryTitle: editing == nil ? "Add Project" : "Save", - isPrimaryDisabled: path.isEmpty || name.isEmpty || key.isEmpty || isScanning || isSaving, + isPrimaryDisabled: path.isEmpty || name.isEmpty || key.isEmpty || isScanning || isSaving || !model.canChange(place), width: editing == nil && !path.isEmpty ? 640 : 500, cancel: { dismiss() }, primary: { Task { await save() } } ) { Field(title: "Folder") { - FolderButton(path: path) { isChoosingFolder = true } + FolderButton(path: path, isOnThisMac: place == .thisMac) { isChoosingFolder = true } } HStack(alignment: .top, spacing: 12) { Field(title: "Name") { @@ -50,20 +52,23 @@ struct ProjectForm: View { .frame(width: 160) } .onChange(of: name) { - if !isKeyEdited { key = model.suggestedProjectKey(for: name, excluding: editing?.id) } + if !isKeyEdited { key = model.suggestedProjectKey(for: name, excluding: editing?.id, on: place) } } if editing == nil, !path.isEmpty { SuggestionReview( - drafts: $drafts, isScanning: isScanning, projectPath: path, + drafts: $drafts, isScanning: isScanning, projectPath: path, place: place, emptyMessage: "Nothing recognised in this folder. Add the project, then add its services yourself." ) } } - .fileImporter(isPresented: $isChoosingFolder, allowedContentTypes: [.folder]) { result in + .fileImporter(isPresented: isChoosingFolderHere, allowedContentTypes: [.folder]) { result in guard case .success(let url) = result else { return } - path = url.path - if name.isEmpty { name = url.lastPathComponent } - if editing == nil { scan() } + choose(url.path) + } + .sheet(isPresented: isChoosingFolderThere) { + if case .machine(let machineID) = place { + RemoteFolderPicker(machineID: machineID, startingAt: path.isEmpty ? nil : path, choose: choose) + } } .onAppear { guard let editing else { return } @@ -74,6 +79,34 @@ struct ProjectForm: View { } } + private var title: String { + if let editing { return "Edit \(editing.name)" } + return model.machineName(place).map { "New Project on \($0)" } ?? "New Project" + } + + /// Another Machine's form says which it is, and for an edit, where the Project is there. + private var subtitle: Text { + guard let machine = model.machineName(place) else { return Text("A folder whose services localhost runs.") } + guard let editing else { return Text("A folder on \(machine) whose services localhost runs.") } + return Text("on \(machine) · ") + Text(editing.path).monospaced() + } + + /// This Mac's folders are chosen in the open panel, another Machine's in its own picker. + private var isChoosingFolderHere: Binding { + Binding { isChoosingFolder && place == .thisMac } set: { isChoosingFolder = $0 } + } + + private var isChoosingFolderThere: Binding { + Binding { isChoosingFolder && place != .thisMac } set: { isChoosingFolder = $0 } + } + + /// The folder's last component names the Project until the user does. + private func choose(_ folder: String) { + path = folder + if name.isEmpty { name = folder.split(separator: "/").last.map(String.init) ?? "" } + if editing == nil { scan() } + } + private var keyBinding: Binding { Binding { key } set: { newValue in key = newValue @@ -82,6 +115,7 @@ struct ProjectForm: View { } private var hint: String { + if let reason = model.reasonCantChange(place) { return reason } guard editing == nil else { return "↩ to save" } let count = drafts.filter(\.isChecked).count return count == 0 ? "↩ to add" : "↩ to add with \(count) service\(count == 1 ? "" : "s")" @@ -91,9 +125,17 @@ struct ProjectForm: View { let folder = path scannedPath = folder drafts = [] + error = nil isScanning = true Task { - let suggestions = await model.suggestions(forFolderAt: folder) + let suggestions: [ServiceSuggestion] + do throws(LocalhostError) { + suggestions = try await model.suggestions(forFolderAt: folder, on: place) + } catch { + guard scannedPath == folder else { return } + self.error = error.message + suggestions = [] + } guard scannedPath == folder else { return } drafts = suggestions.map(SuggestionDraft.init) isScanning = false @@ -112,9 +154,9 @@ struct ProjectForm: View { defer { isSaving = false } do { if let editing { - try await model.editProject(editing.id, name: name, key: key, path: path) + try await model.editProject(editing.id, name: name, key: key, path: path, on: place) } else { - try await model.addProject(name: name, key: key, path: path, services: services) + try await model.addProject(name: name, key: key, path: path, services: services, on: place) } dismiss() } catch { diff --git a/apps/macos/App/Views/ProjectSidebar.swift b/apps/macos/App/Views/ProjectSidebar.swift index f9f0024..c1dd5e9 100644 --- a/apps/macos/App/Views/ProjectSidebar.swift +++ b/apps/macos/App/Views/ProjectSidebar.swift @@ -37,6 +37,7 @@ struct ProjectSidebar: View { } header: { Text(shown.machine.name) .accessibilityLabel("Machine \(shown.machine.name)") + .contextMenu { MachineMenu(shown: shown) } } } } @@ -69,12 +70,58 @@ struct ProjectSidebar: View { Button("Stop All") { model.stopAll(inProject: id, on: place) } .disabled(!project.services.contains { model.status(of: $0, on: place).state.isActive } || !model.isReachable(place)) Divider() + MachineProjectEditButtons(project: project, place: place) + Divider() Button("Reconnect") { model.reconnectMachine(machineID) } + Divider() + Button("Remove Project…", role: .destructive) { model.pendingRemoval = .project(id, on: place) } + .disabled(!model.canChange(place)) } } } } +/// What a Machine's heading offers: a new Project there, one from a Project +/// file there, and Reconnect. While it can't take changes, why not. +struct MachineMenu: View { + @Environment(AppModel.self) private var model + let shown: MachinesStore.Shown + var includesReconnect = true + + var body: some View { + let place = AppModel.Place.machine(shown.id) + if let reason = model.reasonCantChange(place) { + Text(reason) + } + Button("New Project…") { model.presentedSheet = .addProject(on: place) } + .disabled(!model.canChange(place)) + Button("Import Project…") { model.chooseProjectFile(on: place) } + .disabled(!model.canChange(place)) + if includesReconnect { + Divider() + Button("Reconnect") { model.reconnectMachine(shown.id) } + } + } +} + +/// Edit Project, Edit Environment, Detect Services and Favorite for a +/// Project of another Machine, disabled while the Machine can't take changes. +struct MachineProjectEditButtons: View { + @Environment(AppModel.self) private var model + let project: Project + let place: AppModel.Place + + var body: some View { + Group { + Button("Edit Project…") { model.presentedSheet = .editProject(project.id, on: place) } + Button("Edit Environment…") { model.presentedSheet = .projectEnvironment(project.id, on: place) } + Button("Detect Services…") { model.presentedSheet = .detectServices(projectID: project.id, on: place) } + Button(project.isFavorite ? "Unfavorite" : "Favorite") { model.setFavorite(project.id, !project.isFavorite, on: place) } + } + .disabled(!model.canChange(place)) + } +} + /// A Project in the sidebar, on this Mac or another Machine: the state of /// its Services, its name, and whether it is a favourite. private struct ProjectRow: View { @@ -139,6 +186,10 @@ private struct MachineStateRow: View { Button("Reconnect") { model.reconnectMachine(shown.id) } .buttonStyle(PillButtonStyle(isCompact: true)) .accessibilityLabel("Reconnect \(shown.machine.name)") + } else if shown.projects.isEmpty, model.canChange(.machine(shown.id)) { + Button("New Project…") { model.presentedSheet = .addProject(on: .machine(shown.id)) } + .buttonStyle(PillButtonStyle(isCompact: true)) + .accessibilityLabel("New Project on \(shown.machine.name)") } } .padding(.vertical, 2) @@ -192,8 +243,17 @@ private struct SidebarHeader: View { .background(Color.primary.opacity(isSearchFocused ? 0.09 : 0.06), in: .rect(cornerRadius: 7)) // A new Project from a folder, or one from a Project file. Menu { - Button("New Project…") { model.presentedSheet = .addProject } + Button("New Project…") { model.presentedSheet = .addProject() } + .disabled(model.core == nil) Button("Import Project…") { model.isChoosingImportFile = true } + .disabled(model.core == nil) + // Each other Machine's, made there. + if !model.shownMachines.isEmpty { + Divider() + ForEach(model.shownMachines) { shown in + Menu("On \(shown.machine.name)") { MachineMenu(shown: shown, includesReconnect: false) } + } + } } label: { Image(systemName: "plus") } @@ -203,7 +263,7 @@ private struct SidebarHeader: View { .fixedSize() .accessibilityLabel("Add Project") .help("Add Project") - .disabled(model.core == nil) + .disabled(model.core == nil && model.shownMachines.isEmpty) } } .padding(.horizontal, 10) diff --git a/apps/macos/App/Views/RemoteFolderPicker.swift b/apps/macos/App/Views/RemoteFolderPicker.swift new file mode 100644 index 0000000..5849cf4 --- /dev/null +++ b/apps/macos/App/Views/RemoteFolderPicker.swift @@ -0,0 +1,287 @@ +import LocalhostCore +import SwiftUI + +/// Chooses a folder (or a Project file) on another Machine, which this Mac's +/// open panel can't browse: a path to type, the folders above it as a +/// breadcrumb, Up, and what the folder holds, listed by the Machine. Choose +/// picks the selected folder, else the one shown; for a Project file, the +/// selected file. Paths are the Machine's, shown as they are. +struct RemoteFolderPicker: View { + enum Mode { + case folder + /// Folders and Project files (`.yaml`, `.yml`); other files are hidden. + case projectFile + } + + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + let machineID: UUID + var mode: Mode = .folder + /// Where it opens; `nil` for the home folder there. + var startingAt: String? + let choose: (String) -> Void + + /// The folder shown, kept while another can't be opened. + @State private var listing: DirectoryListing? + @State private var typedPath = "" + /// The selected entry's name. + @State private var selection: String? + @State private var showsHidden = false + /// Why the folder asked for can't be shown, as the Machine says. + @State private var error: String? + @State private var isLoading = false + /// The latest request, so an answer to an earlier one is ignored. + @State private var request = UUID() + @FocusState private var isPathFocused: Bool + @FocusState private var isListFocused: Bool + + var body: some View { + let machine = model.machineName(.machine(machineID)) ?? "the Machine" + FormSheet( + systemImage: mode == .folder ? "folder" : "doc.text", + title: mode == .folder ? "Choose a Folder on \(machine)" : "Choose a Project File on \(machine)", + hint: mode == .folder ? "Double-click or ↩ opens a folder." : "Shows folders and Project files (.yaml, .yml).", + primaryTitle: "Choose", + isPrimaryDisabled: chosenPath == nil, + isPrimaryDefault: isChooseDefault, + width: 560, + cancel: { dismiss() }, + primary: { + if let path = chosenPath { pick(path) } + } + ) { + pathBar + if !crumbs.isEmpty { + breadcrumb + } + entryList + Toggle("Show hidden", isOn: $showsHidden) + .toggleStyle(.checkbox) + .font(.callout) + } + .task { await load(startingAt) } + .onChange(of: showsHidden) { + Task { await load(listing?.path ?? startingAt) } + } + } + + // MARK: Parts + + private var pathBar: some View { + HStack(spacing: 6) { + Button("Up", systemImage: "arrow.up") { + if let parent = listing?.parent { open(path: parent) } + } + .labelStyle(.iconOnly) + .buttonStyle(SquareIconButtonStyle()) + .keyboardShortcut(.upArrow, modifiers: .command) + .help("Up (⌘↑)") + .disabled(listing?.parent == nil) + TextField("Path", text: $typedPath, prompt: Text("/home/me/code")) + .labelsHidden() + .textFieldStyle(.plain) + .font(.system(size: 12.5, design: .monospaced)) + .focused($isPathFocused) + .onSubmit(go) + .padding(.horizontal, 10) + .frame(height: 30) + .fieldBox(isFocused: isPathFocused) + .accessibilityLabel("Path on \(model.machineName(.machine(machineID)) ?? "the Machine")") + Button("Go", action: go) + .buttonStyle(PillButtonStyle(isCompact: true)) + .disabled(typedPath.trimmingCharacters(in: .whitespaces).isEmpty) + } + } + + /// The folders from the root to the one shown; each opens it. + private var breadcrumb: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 3) { + ForEach(Array(crumbs.enumerated()), id: \.offset) { index, crumb in + if index > 0 { + Image(systemName: "chevron.right") + .font(.system(size: 8, weight: .semibold)) + .foregroundStyle(.tertiary) + .accessibilityHidden(true) + } + if index == crumbs.count - 1 { + Text(crumb.name) + .foregroundStyle(.primary) + } else { + Button(crumb.name) { open(path: crumb.path) } + .buttonStyle(.plain) + .foregroundStyle(.secondary) + .accessibilityLabel("Open \(crumb.path)") + } + } + } + .font(.system(size: 11.5, design: .monospaced)) + .lineLimit(1) + } + .defaultScrollAnchor(.trailing) + } + + private var entryList: some View { + List(selection: $selection) { + ForEach(error == nil ? entries : [], id: \.name) { entry in + EntryRow(entry: entry) { open(entry) } + .tag(entry.name) + } + } + .listStyle(.inset) + .scrollContentBackground(.hidden) + .focused($isListFocused) + .contextMenu(forSelectionType: String.self) { _ in + EmptyView() + } primaryAction: { names in + if let entry = names.first.flatMap(entry(named:)) { open(entry) } + } + .overlay { listOverlay } + .frame(height: 260) + .fieldBox(isFocused: false) + } + + @ViewBuilder private var listOverlay: some View { + if let error { + Label(error, systemImage: "exclamationmark.triangle.fill") + .font(.callout) + .foregroundStyle(Color(nsColor: Theme.failed)) + .multilineTextAlignment(.center) + .padding() + } else if isLoading && listing == nil { + ProgressView().controlSize(.small) + } else if listing != nil && entries.isEmpty { + Text(mode == .folder ? "No folders here." : "No folders or Project files here.") + .font(.callout) + .foregroundStyle(.secondary) + } + } + + // MARK: State + + /// What the folder holds that can be picked or opened. + private var entries: [DirectoryEntry] { + (listing?.entries ?? []).filter { $0.isDirectory || (mode == .projectFile && Self.isProjectFile($0.name)) } + } + + private func entry(named name: String) -> DirectoryEntry? { + entries.first { $0.name == name } + } + + private static func isProjectFile(_ name: String) -> Bool { + let name = name.lowercased() + return name.hasSuffix(".yaml") || name.hasSuffix(".yml") + } + + /// The selected folder, else the one shown; for a Project file, the selected file. + private var chosenPath: String? { + guard let listing, error == nil else { return nil } + let selected = selection.flatMap(entry(named:)) + switch mode { + case .folder: + return selected.map { Self.path(of: $0.name, in: listing.path) } ?? listing.path + case .projectFile: + return selected.flatMap { $0.isDirectory ? nil : Self.path(of: $0.name, in: listing.path) } + } + } + + /// ↩ opens a typed path, or what is selected in the list (a folder opens, + /// a Project file is chosen), rather than choosing here. + private var isChooseDefault: Bool { + if isPathFocused, typedPath != listing?.path { return false } + if isListFocused, selection != nil { return false } + return true + } + + /// The root, then each folder down to the one shown. + private var crumbs: [(name: String, path: String)] { + guard let path = listing?.path else { return [] } + guard path.hasPrefix("/") else { return [(path, path)] } + var crumbs = [(name: "/", path: "/")] + var current = "" + for part in path.split(separator: "/") { + current += "/\(part)" + crumbs.append((String(part), current)) + } + return crumbs + } + + private static func path(of name: String, in folder: String) -> String { + folder.hasSuffix("/") ? folder + name : "\(folder)/\(name)" + } + + // MARK: Actions + + private func go() { + let path = typedPath.trimmingCharacters(in: .whitespaces) + guard !path.isEmpty else { return } + open(path: path) + } + + private func open(_ entry: DirectoryEntry) { + guard let listing else { return } + let path = Self.path(of: entry.name, in: listing.path) + if entry.isDirectory { open(path: path) } else { pick(path) } + } + + private func open(path: String) { + Task { await load(path) } + } + + private func pick(_ path: String) { + choose(path) + dismiss() + } + + private func load(_ path: String?) async { + let current = UUID() + request = current + isLoading = true + do { + let result = try await model.listDirectory( + path, on: machineID, showHidden: showsHidden, includeFiles: mode == .projectFile + ) + guard request == current else { return } + listing = result + typedPath = result.path + error = nil + } catch { + guard request == current else { return } + self.error = error.message + if let path { typedPath = path } + } + selection = nil + isLoading = false + } +} + +/// A folder or Project file in the picker: one element, its name as label +/// and what it is as value. +private struct EntryRow: View { + let entry: DirectoryEntry + let open: () -> Void + + var body: some View { + HStack(spacing: 8) { + Image(systemName: entry.isDirectory ? "folder" : "doc.text") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .frame(width: 16) + Text(entry.name) + .font(.system(size: 12.5, design: .monospaced)) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 8) + if entry.isDirectory { + Image(systemName: "chevron.right") + .font(.system(size: 9, weight: .semibold)) + .foregroundStyle(.tertiary) + } + } + .padding(.vertical, 2) + .accessibilityElement(children: .ignore) + .accessibilityLabel(entry.name) + .accessibilityValue(entry.isDirectory ? "Folder" : "Project file") + .accessibilityAction(named: Text(entry.isDirectory ? "Open" : "Choose"), open) + } +} diff --git a/apps/macos/App/Views/ServiceForm.swift b/apps/macos/App/Views/ServiceForm.swift index 69321f9..35bcd32 100644 --- a/apps/macos/App/Views/ServiceForm.swift +++ b/apps/macos/App/Views/ServiceForm.swift @@ -13,6 +13,7 @@ struct ServiceForm: View { @Environment(\.dismiss) private var dismiss let project: Project let editing: Service? + var place: AppModel.Place = .thisMac @State private var name = "" @State private var key = "" @@ -38,11 +39,11 @@ struct ServiceForm: View { systemImage: "terminal", tint: Color(nsColor: serviceColor), title: editing == nil ? "New Service" : "Edit \(editing?.name ?? "Service")", - subtitle: Text("in **\(project.name)** · ") + Text((project.path as NSString).abbreviatingWithTildeInPath).monospaced(), - hint: "↩ to \(editing == nil ? "add" : "save")", + subtitle: Self.subtitle(of: project, on: model.machineName(place)), + hint: model.reasonCantChange(place) ?? "↩ to \(editing == nil ? "add" : "save")", error: error, primaryTitle: editing == nil ? "Add Service" : "Save", - isPrimaryDisabled: name.isEmpty || key.isEmpty || commandLine.isEmpty || isSaving, + isPrimaryDisabled: name.isEmpty || key.isEmpty || commandLine.isEmpty || isSaving || !model.canChange(place), width: 580, cancel: { dismiss() }, primary: { Task { await save() } } @@ -83,8 +84,8 @@ struct ServiceForm: View { .task(id: DetectionInput(workingDirectory: workingDirectory, commandLine: commandLine)) { try? await Task.sleep(for: .milliseconds(250)) guard !Task.isCancelled else { return } - let detected = await ProjectScanner().pythonEnvironment( - projectPath: project.path, workingDirectory: workingDirectory, commandLine: commandLine + let detected = await model.pythonEnvironment( + in: project, workingDirectory: workingDirectory, commandLine: commandLine, on: place ) guard !Task.isCancelled else { return } detectedEnvironment = detected @@ -111,7 +112,7 @@ struct ServiceForm: View { } } Field(title: "Environment", note: "overrides the project’s · applies on next start") { - VariableEditor(variables: $variables, layer: editing.map { .service($0.id) }) + VariableEditor(variables: $variables, layer: editing.map { .service($0.id) }, place: place) } if !otherServices.isEmpty { Field(title: "Starts after", note: "waits until they’re running", hint: dependencyHint) { @@ -124,10 +125,18 @@ struct ServiceForm: View { } SwitchRow(title: "Manual", detail: startFooter, isOn: $isExcludedFromStartAll) } - .fileImporter(isPresented: $isChoosingFolder, allowedContentTypes: [.folder]) { result in + .fileImporter(isPresented: Binding { isChoosingFolder && place == .thisMac } set: { isChoosingFolder = $0 }, + allowedContentTypes: [.folder]) { result in guard case .success(let url) = result else { return } workingDirectory = Self.relativePath(of: url.path, to: project.path) } + .sheet(isPresented: Binding { isChoosingFolder && place != .thisMac } set: { isChoosingFolder = $0 }) { + if case .machine(let machineID) = place { + RemoteFolderPicker(machineID: machineID, startingAt: project.path) { folder in + workingDirectory = Self.relativePath(of: folder, to: project.path) + } + } + } .onAppear { guard let editing else { return } name = editing.name @@ -254,14 +263,14 @@ struct ServiceForm: View { editing.id, name: name, key: key, workingDirectory: workingDirectory, commandLine: commandLine, variables: inputs, dependencies: dependencies, isExcludedFromStartAll: isExcludedFromStartAll, port: parsedPort, url: url, - portCanChange: portCanChange, pythonEnvironment: pythonEnvironment, runBefore: runBefore + portCanChange: portCanChange, pythonEnvironment: pythonEnvironment, runBefore: runBefore, on: place ) } else { try await model.addService( to: project.id, name: name, key: key, workingDirectory: workingDirectory, commandLine: commandLine, variables: inputs, dependencies: dependencies, isExcludedFromStartAll: isExcludedFromStartAll, port: parsedPort, url: url, - portCanChange: portCanChange, pythonEnvironment: pythonEnvironment, runBefore: runBefore + portCanChange: portCanChange, pythonEnvironment: pythonEnvironment, runBefore: runBefore, on: place ) } dismiss() @@ -270,7 +279,17 @@ struct ServiceForm: View { } } - /// `path` relative to `base`, e.g. "web" or "../shared"; "." for `base` itself. + /// "in **My SaaS** · ~/code/my-saas"; on another Machine, "in **My SaaS** + /// on devbox · /srv/my-saas", its path as it is there. + static func subtitle(of project: Project, on machine: String?) -> Text { + guard let machine else { + return Text("in **\(project.name)** · ") + Text((project.path as NSString).abbreviatingWithTildeInPath).monospaced() + } + return Text("in **\(project.name)** on \(machine) · ") + Text(project.path).monospaced() + } + + /// `path` relative to `base`, e.g. "web" or "../shared"; "." for `base` + /// itself. Also for another Machine's paths: both sides are standardized alike. static func relativePath(of path: String, to base: String) -> String { let target = URL(filePath: path).standardizedFileURL.pathComponents let root = URL(filePath: base).standardizedFileURL.pathComponents diff --git a/apps/macos/App/Views/SuggestionReview.swift b/apps/macos/App/Views/SuggestionReview.swift index 11dc1da..524e78e 100644 --- a/apps/macos/App/Views/SuggestionReview.swift +++ b/apps/macos/App/Views/SuggestionReview.swift @@ -204,6 +204,8 @@ struct SuggestionReview: View { let isScanning: Bool /// The Project folder, for choosing working directories. let projectPath: String + /// Where the folder is: another Machine's is browsed with its own picker. + var place: AppModel.Place = .thisMac /// The Services the Project already has: new ones get the colours they'll /// keep after them, and can start after them. var existingServices: [Service] = [] @@ -263,12 +265,22 @@ struct SuggestionReview: View { } } } - .fileImporter(isPresented: Binding { choosingFolderFor != nil } set: { if !$0 { choosingFolderFor = nil } }, + .fileImporter(isPresented: Binding { choosingFolderFor != nil && place == .thisMac } set: { if !$0 { choosingFolderFor = nil } }, allowedContentTypes: [.folder]) { result in - guard case .success(let url) = result, let id = choosingFolderFor, - let index = drafts.firstIndex(where: { $0.id == id }) else { return } - drafts[index].workingDirectory = ServiceForm.relativePath(of: url.path, to: projectPath) + guard case .success(let url) = result else { return } + setWorkingDirectory(url.path) } + .sheet(isPresented: Binding { choosingFolderFor != nil && place != .thisMac } set: { if !$0 { choosingFolderFor = nil } }) { + if case .machine(let machineID) = place { + RemoteFolderPicker(machineID: machineID, startingAt: projectPath, choose: setWorkingDirectory) + } + } + } + + /// The chosen folder, relative to the Project's, as the working directory of the draft it was chosen for. + private func setWorkingDirectory(_ folder: String) { + guard let id = choosingFolderFor, let index = drafts.firstIndex(where: { $0.id == id }) else { return } + drafts[index].workingDirectory = ServiceForm.relativePath(of: folder, to: projectPath) } private var selectionNote: String { @@ -577,6 +589,7 @@ struct DetectServicesForm: View { @Environment(AppModel.self) private var model @Environment(\.dismiss) private var dismiss let project: Project + var place: AppModel.Place = .thisMac @State private var drafts: [SuggestionDraft] = [] @State private var isScanning = true @@ -588,23 +601,27 @@ struct DetectServicesForm: View { FormSheet( systemImage: "sparkle.magnifyingglass", title: "Detect Services", - subtitle: Text("in **\(project.name)** · ") + Text((project.path as NSString).abbreviatingWithTildeInPath).monospaced(), - hint: count == 0 ? nil : "↩ to add", + subtitle: ServiceForm.subtitle(of: project, on: model.machineName(place)), + hint: model.reasonCantChange(place) ?? (count == 0 ? nil : "↩ to add"), error: error, primaryTitle: count == 0 ? "Add Services" : "Add \(count) Service\(count == 1 ? "" : "s")", - isPrimaryDisabled: count == 0 || isSaving, + isPrimaryDisabled: count == 0 || isSaving || !model.canChange(place), width: 640, cancel: { dismiss() }, primary: { Task { await save() } } ) { SuggestionReview( - drafts: $drafts, isScanning: isScanning, projectPath: project.path, + drafts: $drafts, isScanning: isScanning, projectPath: project.path, place: place, existingServices: project.services, emptyMessage: "Nothing new found. Services this project already runs aren’t suggested again." ) } .task { - drafts = await model.suggestions(for: project).map(SuggestionDraft.init) + do throws(LocalhostError) { + drafts = try await model.suggestions(for: project, on: place).map(SuggestionDraft.init) + } catch { + self.error = error.message + } isScanning = false } } @@ -617,7 +634,7 @@ struct DetectServicesForm: View { isSaving = true defer { isSaving = false } do { - try await model.addServices(services, to: project.id) + try await model.addServices(services, to: project.id, on: place) dismiss() } catch { self.error = error.message diff --git a/apps/macos/App/Views/VariableEditor.swift b/apps/macos/App/Views/VariableEditor.swift index ca5b74f..5f268fa 100644 --- a/apps/macos/App/Views/VariableEditor.swift +++ b/apps/macos/App/Views/VariableEditor.swift @@ -36,6 +36,9 @@ struct VariableEditor: View { @Binding var variables: [VariableDraft] /// Where stored Secrets are read from; `nil` while the layer is new. let layer: VariableLayer? + /// Where they are stored: another Machine's are read there to reveal + /// them, and what is typed is sent there, never kept on this Mac. + var place: AppModel.Place = .thisMac var body: some View { FormCard { @@ -61,9 +64,7 @@ struct VariableEditor: View { Task { await toggleSecret(binding) } } .foregroundStyle(variable.isSecret ? AnyShapeStyle(Theme.accentText) : AnyShapeStyle(.secondary)) - .help(variable.isSecret - ? "Secret: stored in your Keychain, never in the project file. Click to make it a plain variable." - : "Make it a secret") + .help(variable.isSecret ? secretHelp : "Make it a secret") Button("Remove Variable", systemImage: "minus.circle") { variables.removeAll { $0.id == variable.id } } @@ -92,6 +93,13 @@ struct VariableEditor: View { } } + private var secretHelp: String { + guard let machine = model.machineName(place) else { + return "Secret: stored in your Keychain, never in the project file. Click to make it a plain variable." + } + return "Secret: stored on \(machine), never on this Mac or in the project file. Click to make it a plain variable." + } + @ViewBuilder private func valueField(_ variable: Binding) -> some View { let text = Binding { @@ -131,7 +139,7 @@ struct VariableEditor: View { guard !variable.wrappedValue.isValueKnown, let layer, let name = variable.wrappedValue.storedSecretName else { return } - variable.wrappedValue.value = await model.secretValue(named: name, in: layer) ?? "" + variable.wrappedValue.value = await model.secretValue(named: name, in: layer, on: place) ?? "" variable.wrappedValue.isValueKnown = true } } diff --git a/apps/macos/LocalhostCoreFFI/Sources/LocalhostCore/Machines.swift b/apps/macos/LocalhostCoreFFI/Sources/LocalhostCore/Machines.swift index 2010147..455ca37 100644 --- a/apps/macos/LocalhostCoreFFI/Sources/LocalhostCore/Machines.swift +++ b/apps/macos/LocalhostCoreFFI/Sources/LocalhostCore/Machines.swift @@ -105,6 +105,223 @@ extension Machines { MachineLogs(machines: self, machineID: machineID) } + // MARK: Its Project Configuration + + // Changed there, as `Origin.machine`; the Projects come back through + // `subscribe()`. An older localhost there throws `.MachineNeedsUpdate`. + + /// A folder there, for a folder picker; `nil` is the home folder there. + /// Folders only, unless `includeFiles`. + public func listDirectory( + _ path: String?, + on machineID: UUID, + showHidden: Bool = false, + includeFiles: Bool = false + ) async throws(LocalhostError) -> DirectoryListing { + try await core { + try await ffiListDirectory(machineId: machineID, path: path, showHidden: showHidden, includeFiles: includeFiles) + } + } + + /// Suggestions for a folder there being added as a Project, scanned there. + public func scan(projectAt path: String, on machineID: UUID) async throws(LocalhostError) -> [ServiceSuggestion] { + try await core { try await ffiScanFolder(machineId: machineID, path: path) } + } + + /// Suggestions for an existing Project there, without what its Services cover. + public func scan(project projectID: UUID, on machineID: UUID) async throws(LocalhostError) -> [ServiceSuggestion] { + try await core { try await ffiScanProject(machineId: machineID, projectId: projectID) } + } + + /// The virtual environment a new Service of the Project would run in + /// there, when its command starts a Python program; `nil` otherwise. + public func pythonEnvironment( + inProject projectID: UUID, + workingDirectory: String, + commandLine: String, + on machineID: UUID + ) async throws(LocalhostError) -> String? { + try await core { + try await ffiDetectPythonEnvironment( + machineId: machineID, projectId: projectID, workingDirectory: workingDirectory, commandLine: commandLine + ) + } + } + + @discardableResult + public func addProject( + name: String, + key: Key, + path: String, + services: [NewService] = [], + on machineID: UUID + ) async throws(LocalhostError) -> Project { + try await core { try await ffiAddProject(machineId: machineID, name: name, key: key, path: path, services: services) } + } + + @discardableResult + public func editProject( + id: UUID, + name: String? = nil, + key: Key? = nil, + path: String? = nil, + isFavorite: Bool? = nil, + variables: [VariableInput]? = nil, + on machineID: UUID + ) async throws(LocalhostError) -> Project { + let changes = ProjectChanges(name: name, key: key, path: path, isFavorite: isFavorite, variables: variables) + return try await core { try await ffiEditProject(machineId: machineID, projectId: id, changes: changes) } + } + + /// Stops its Services there first, then removes it and their logs. + public func removeProject(id: UUID, on machineID: UUID) async throws(LocalhostError) { + try await core { try await ffiRemoveProject(machineId: machineID, projectId: id) } + } + + @discardableResult + public func addService( + toProject projectID: UUID, + name: String, + key: Key, + workingDirectory: String = ".", + commandLine: String, + variables: [VariableInput] = [], + dependencies: [UUID] = [], + isExcludedFromStartAll: Bool = false, + port: Int? = nil, + url: String? = nil, + portCanChange: Bool = true, + pythonEnvironment: String? = nil, + runBefore: String? = nil, + on machineID: UUID + ) async throws(LocalhostError) -> Service { + let service = NewService( + name: name, + key: key, + workingDirectory: workingDirectory, + commandLine: commandLine, + port: port, + url: url, + portCanChange: portCanChange, + isExcludedFromStartAll: isExcludedFromStartAll, + pythonEnvironment: pythonEnvironment, + runBefore: runBefore + ) + return try await core { + try await ffiAddService( + machineId: machineID, + projectId: projectID, + service: service, + variables: variables, + dependencies: dependencies + ) + } + } + + @discardableResult + public func addServices( + _ services: [NewService], + toProject projectID: UUID, + on machineID: UUID + ) async throws(LocalhostError) -> [Service] { + try await core { try await ffiAddServices(machineId: machineID, projectId: projectID, services: services) } + } + + /// Changes what is given; `port: .some(nil)` clears the port, and the + /// same for `url`, `pythonEnvironment` and `runBefore`. + @discardableResult + public func editService( + id: UUID, + name: String? = nil, + key: Key? = nil, + workingDirectory: String? = nil, + commandLine: String? = nil, + variables: [VariableInput]? = nil, + dependencies: [UUID]? = nil, + isExcludedFromStartAll: Bool? = nil, + port: Int?? = nil, + url: String?? = nil, + portCanChange: Bool? = nil, + pythonEnvironment: String?? = nil, + runBefore: String?? = nil, + on machineID: UUID + ) async throws(LocalhostError) -> Service { + let changes = ServiceChanges( + name: name, + key: key, + workingDirectory: workingDirectory, + commandLine: commandLine, + variables: variables, + dependencies: dependencies, + isExcludedFromStartAll: isExcludedFromStartAll, + port: port.map { $0.map(Int64.init) }, + url: url, + portCanChange: portCanChange, + pythonEnvironment: pythonEnvironment, + runBefore: runBefore + ) + return try await core { try await ffiEditService(machineId: machineID, serviceId: id, changes: changes) } + } + + /// Stops the Service there first, then removes it and its logs. + public func removeService(id: UUID, on machineID: UUID) async throws(LocalhostError) { + try await core { try await ffiRemoveService(machineId: machineID, serviceId: id) } + } + + /// Saves the Environment editor at once: the Project's variables, its + /// Profiles (those without an id are added, those missing removed), and + /// which one is active, an index into `profiles`. + public func saveEnvironment( + ofProject projectID: UUID, + variables: [VariableInput], + profiles: [ProfileInput], + activeProfile: Int?, + on machineID: UUID + ) async throws(LocalhostError) { + let active = activeProfile.map { UInt32($0) } + try await core { + try await ffiSaveEnvironment( + machineId: machineID, projectId: projectID, variables: variables, profiles: profiles, active: active + ) + } + } + + /// Makes `profileID` the Project's active profile; `nil` for none. + public func setActiveProfile( + _ profileID: UUID?, + inProject projectID: UUID, + on machineID: UUID + ) async throws(LocalhostError) { + try await core { try await ffiSetActiveProfile(machineId: machineID, projectId: projectID, profileId: profileID) } + } + + /// A Secret's value there, to reveal it. Never stored here. + public func secretValue( + named name: String, + in layer: VariableLayer, + on machineID: UUID + ) async throws(LocalhostError) -> String? { + try await core { try await ffiSecretValue(machineId: machineID, name: name, layer: layer) } + } + + /// A Project file there, and whether the folder it names is there. + public func readProjectFile(at path: String, on machineID: UUID) async throws(LocalhostError) -> ProjectFileText { + try await core { try await ffiReadProjectFile(machineId: machineID, path: path) } + } + + /// Adds the Project a Project file's `text` describes, in the folder + /// `path` there. If another Project there has its Key, nothing changes + /// unless `onKeyClash` says what to do. + @discardableResult + public func importProject( + text: String, + path: String, + onKeyClash: ProjectLibrary.KeyClash? = nil, + on machineID: UUID + ) async throws(LocalhostError) -> Project { + try await core { try await ffiImportProject(machineId: machineID, text: text, path: path, onKeyClash: onKeyClash) } + } + /// The hosts named in `~/.ssh/config` (following `Include`, without /// patterns), to suggest as a destination. Only read. public static func sshConfigHosts() async -> [String] { @@ -195,6 +412,12 @@ public final class MachinesStore { if case .connected = state { true } else { false } } + /// Whether its Projects can be changed from here now: connected, to a + /// localhost new enough to take the changes. + public var managesProjects: Bool { + if case .connected(_, let managesProjects) = state { managesProjects } else { false } + } + public func status(of serviceID: UUID) -> ServiceStatus { statuses[serviceID] ?? .neverRun(serviceID) } diff --git a/apps/macos/LocalhostCoreFFI/Sources/LocalhostCore/Model.swift b/apps/macos/LocalhostCoreFFI/Sources/LocalhostCore/Model.swift index 925b333..8706f9e 100644 --- a/apps/macos/LocalhostCoreFFI/Sources/LocalhostCore/Model.swift +++ b/apps/macos/LocalhostCoreFFI/Sources/LocalhostCore/Model.swift @@ -46,6 +46,11 @@ extension Project: Identifiable { projectSuggestedServiceKey(project: self, name: name, excluding: serviceID) } + /// `key` if none of `projects` uses it, else the Key "Keep both" imports under. + public static func freeKey(basedOn key: Key, among projects: [Project]) -> Key { + freeProjectKey(projects: projects, key: key) + } + /// A Key derived from `name` that none of `projects` uses but the one being edited. public static func suggestedKey(for name: String, among projects: [Project], excluding projectID: UUID? = nil) -> Key { suggestedProjectKey(projects: projects, name: name, excluding: projectID) diff --git a/apps/macos/LocalhostCoreFFI/Tests/LocalhostCoreTests/LayerTests.swift b/apps/macos/LocalhostCoreFFI/Tests/LocalhostCoreTests/LayerTests.swift index 530816e..309635e 100644 --- a/apps/macos/LocalhostCoreFFI/Tests/LocalhostCoreTests/LayerTests.swift +++ b/apps/macos/LocalhostCoreFFI/Tests/LocalhostCoreTests/LayerTests.swift @@ -310,7 +310,8 @@ private final class TemporaryRoot { #expect(MachineProblem.hostKeyNotTrusted.message(machine: "devbox").contains("ssh devbox")) let error = LocalhostError.MachineUnavailable(machine: "devbox", problem: .notInstalled) #expect(error.message.contains("isn’t installed on devbox")) - #expect(MachineState.connected(version: "0.5.0").summary(machine: "devbox") == "Connected · localhost 0.5.0") + #expect(MachineState.connected(version: "0.5.0", managesProjects: true).summary(machine: "devbox") == "Connected · localhost 0.5.0") + #expect(LocalhostError.MachineNeedsUpdate(machine: "devbox").message == "Update localhost on devbox to manage its Projects.") #expect(MachineState.unavailable(problem: .hostKeyChanged, isRetrying: false).needsUser) } } diff --git a/core/localhost-cli/tests/machines_ssh.rs b/core/localhost-cli/tests/machines_ssh.rs index f0e7ee6..e2b01a0 100644 --- a/core/localhost-cli/tests/machines_ssh.rs +++ b/core/localhost-cli/tests/machines_ssh.rs @@ -390,3 +390,66 @@ async fn until_event( }; tokio::time::timeout(PATIENCE, wait).await.unwrap_or_else(|_| panic!("never {what}")); } + +/// What the apps do to manage a Machine's Projects: pick a folder there, +/// add it with what scanning there suggests, edit the Project and a +/// Service, then remove it. All of it is saved there; this computer keeps +/// only its list of Machines. +#[tokio::test(flavor = "multi_thread")] +async fn adds_and_edits_a_project_on_another_machine() { + let Some(other) = OtherMachine::start() else { return }; + let folder = other.path().join("shop"); + std::fs::create_dir_all(folder.join("web")).unwrap(); + std::fs::write(folder.join("package.json"), r#"{"scripts": {"dev": "vite"}}"#).unwrap(); + + let app_root = other.path().join("app-storage"); + let machines = Machines::open(&app_root, &other.ssh()).unwrap(); + let (_, mut events) = machines.subscribe(); + let devbox = tokio::time::timeout(PATIENCE, machines.add(None, "devbox")).await.expect("ssh hung").unwrap(); + until_event(&mut events, "connected", |event| { + matches!( + event, + MachinesEvent::StateChanged { state: MachineState::Connected { manages_projects: true, .. }, .. } + ) + }) + .await; + + let listing = + machines.list_directory(devbox.id, Some(other.path().display().to_string()), false, false).await.unwrap(); + assert!(listing.entries.iter().any(|entry| entry.name == "shop" && entry.is_directory)); + let path = folder.display().to_string(); + let suggestions = machines.scan_folder(devbox.id, path.clone()).await.unwrap(); + let services = + suggestions.into_iter().filter(|suggestion| suggestion.is_recommended).map(NewService::from).collect(); + let project = + machines.add_project(devbox.id, "Shop".into(), Key::new("shop").unwrap(), path, services).await.unwrap(); + assert!(!project.services.is_empty(), "nothing suggested"); + until_event(&mut events, "showed the new Project", |event| { + matches!(event, MachinesEvent::ProjectsChanged { projects, .. } if projects.iter().any(|shown| shown.id == project.id)) + }) + .await; + + let changes = localhost_core::ProjectChanges { + name: Some("Shop 2".into()), + is_favorite: Some(true), + variables: Some(vec![localhost_core::VariableInput::plain("MODE", "dev")]), + ..Default::default() + }; + machines.edit_project(devbox.id, project.id, changes).await.unwrap(); + let changes = localhost_core::ServiceChanges { port: Some(Some(4321)), ..Default::default() }; + machines.edit_service(devbox.id, project.services[0].id, changes).await.unwrap(); + until_event(&mut events, "showed the edits", |event| { + matches!(event, MachinesEvent::ProjectsChanged { projects, .. } + if projects.iter().any(|shown| shown.name == "Shop 2" && shown.services[0].port == Some(4321))) + }) + .await; + + // Saved on the Machine, as its own app would have. + let saved = other.library().project(project.id).unwrap(); + assert_eq!((saved.name.as_str(), saved.is_favorite, saved.services[0].port), ("Shop 2", true, Some(4321))); + assert_eq!(saved.variables.values.get("MODE").map(String::as_str), Some("dev")); + assert!(!app_root.join("projects").exists(), "a Project of the Machine was saved here"); + + machines.remove_project(devbox.id, project.id).await.unwrap(); + assert!(other.library().projects().is_empty()); +} diff --git a/core/localhost-core/examples/machine.rs b/core/localhost-core/examples/machine.rs index 2047d8f..0fe9b80 100644 --- a/core/localhost-core/examples/machine.rs +++ b/core/localhost-core/examples/machine.rs @@ -75,7 +75,7 @@ async fn run(destination: &str) -> Result<(), LocalhostError> { } Some(event) = machine_events.recv() => match event { MachinesEvent::StateChanged { state, .. } => match state { - MachineState::Connected { version } => println!("Connected: localhost {version} there."), + MachineState::Connected { version, .. } => println!("Connected: localhost {version} there."), MachineState::Unavailable { problem, is_retrying } => { println!("{}{}", problem.message(&machine.name), if is_retrying { " Trying again…" } else { "" }); } diff --git a/core/localhost-core/src/editing.rs b/core/localhost-core/src/editing.rs new file mode 100644 index 0000000..308d6b7 --- /dev/null +++ b/core/localhost-core/src/editing.rs @@ -0,0 +1,331 @@ +//! The editors' changes that take more than one library call: removing a +//! Project or Service (stopped first, logs removed after), moving a Project +//! to another Execution Target, importing a Project file over another, and +//! saving the whole Environment editor. The apps make them on this +//! computer, and `machine::relay` makes them on another Machine for its app, +//! so both behave the same. +//! +//! Also what a folder picker shows of a folder (`list_directory`), for a +//! Machine whose folders no system dialog here can browse. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::paths::{expand_tilde, home_directory}; +use crate::{ + Id, Key, KeyClash, LocalhostError, Origin, ProfileChanges, Project, ProjectChanges, ProjectDocument, + ProjectLibrary, Service, Targets, VariableInput, +}; + +/// One Environment Profile as the Environment editor saves it; `profile_id` +/// is `None` for a new one. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(feature = "ffi", derive(uniffi::Record))] +pub struct ProfileInput { + pub profile_id: Option, + pub name: String, + pub variables: Vec, +} + +/// Edits the Project. One moved to another Execution Target has its +/// Services stopped first, and their logs on the old one removed after. +pub async fn edit_project( + library: &ProjectLibrary, + targets: &Targets, + project_id: Id, + changes: ProjectChanges, + origin: Origin, +) -> Result { + let project = library.project(project_id)?; + let moves = changes.execution_target.as_ref().is_some_and(|target| *target != project.execution_target); + if moves { + for service in &project.services { + targets.stop(service.id, origin).await?; + } + } + let edited = library.edit_project(project_id, changes, origin)?; + if moves { + for service in &project.services { + targets.remove_logs(&project.execution_target, service.id).await?; + } + } + Ok(edited) +} + +/// Stops the Project's Services, then removes it and their logs. The +/// folder is not touched. +pub async fn remove_project( + library: &ProjectLibrary, + targets: &Targets, + project_id: Id, + origin: Origin, +) -> Result<(), LocalhostError> { + let project = library.project(project_id)?; + for service in &project.services { + targets.stop(service.id, origin).await?; + } + library.remove_project(project_id, origin)?; + for service in &project.services { + targets.remove_logs(&project.execution_target, service.id).await?; + } + Ok(()) +} + +/// Stops the Service, then removes it and its logs. +pub async fn remove_service( + library: &ProjectLibrary, + targets: &Targets, + service_id: Id, + origin: Origin, +) -> Result<(), LocalhostError> { + let (project, _) = library.service(service_id)?; + targets.stop(service_id, origin).await?; + library.remove_service(service_id, origin)?; + targets.remove_logs(&project.execution_target, service_id).await?; + Ok(()) +} + +/// Imports the Project file. On Replace, Services the file no longer has +/// are stopped first, and their logs removed after; all of them if the +/// Project moves to another Execution Target. +pub async fn import_project( + library: &ProjectLibrary, + targets: &Targets, + document: &ProjectDocument, + on_key_clash: Option, + origin: Origin, +) -> Result { + let replaced = match on_key_clash { + Some(KeyClash::Replace) => clashing(&library.projects(), document), + _ => None, + }; + let moves = |existing: &Project| existing.execution_target != *document.execution_target(); + if let Some(existing) = &replaced { + let stopped: Vec<&Service> = + if moves(existing) { existing.services.iter().collect() } else { removed_by(existing, document).collect() }; + for service in stopped { + targets.stop(service.id, origin).await?; + } + } + let project = library.import_project(document, on_key_clash, origin)?; + if let Some(existing) = &replaced { + let gone = |service: &&Service| moves(existing) || project.service(service.id).is_none(); + for service in existing.services.iter().filter(gone) { + targets.remove_logs(&existing.execution_target, service.id).await?; + } + } + Ok(project) +} + +/// The Project among `projects` that has the document's Key, which an +/// import would replace or keep beside it. +pub fn clashing(projects: &[Project], document: &ProjectDocument) -> Option { + projects.iter().find(|project| project.key == *document.key()).cloned() +} + +/// The existing Project's Services that the file doesn't have: Replace +/// removes them. +pub fn removed_by<'a>(existing: &'a Project, document: &ProjectDocument) -> impl Iterator { + let kept: HashSet = document.services().iter().map(|service| service.key.clone()).collect(); + existing.services.iter().filter(move |service| !kept.contains(&service.key)) +} + +/// Saves the Environment editor: the Project's variables, its Profiles +/// (added, edited, removed), then which one is active (an index into +/// `profiles`, or none). +pub fn save_environment( + library: &ProjectLibrary, + project_id: Id, + variables: Vec, + profiles: Vec, + active: Option, + origin: Origin, +) -> Result<(), LocalhostError> { + let project = library.project(project_id)?; + let changes = ProjectChanges { variables: Some(variables), ..Default::default() }; + library.edit_project(project_id, changes, origin)?; + let kept: HashSet = profiles.iter().filter_map(|profile| profile.profile_id).collect(); + for profile in project.profiles.iter().filter(|profile| !kept.contains(&profile.id)) { + library.remove_profile(profile.id, origin)?; + } + let mut active_id = None; + for (index, edit) in profiles.into_iter().enumerate() { + let id = match edit.profile_id { + Some(id) => { + let changes = ProfileChanges { name: Some(edit.name), variables: Some(edit.variables) }; + library.edit_profile(id, changes, origin)?.id + } + None => library.add_profile(project_id, &edit.name, edit.variables, origin)?.id, + }; + if active == Some(index as u32) { + active_id = Some(id); + } + } + library.set_active_profile(active_id, project_id, origin) +} + +// MARK: Folders + +/// A folder as a picker shows it: where it is, its parent, and what it holds. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(feature = "ffi", derive(uniffi::Record))] +#[cfg_attr(feature = "specta", derive(specta::Type))] +pub struct DirectoryListing { + /// Absolute and standardized. + pub path: String, + /// `None` at the root. + pub parent: Option, + /// The user's home folder, where a picker starts. + pub home: String, + /// Folders first, then files; each sorted by name, ignoring case. + pub entries: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(feature = "ffi", derive(uniffi::Record))] +#[cfg_attr(feature = "specta", derive(specta::Type))] +pub struct DirectoryEntry { + pub name: String, + pub is_directory: bool, +} + +/// What the folder at `path` (the home folder when `None`; `~` is expanded) +/// holds: its folders, and with `include_files` its files too. Names +/// starting with a dot are left out unless `show_hidden`. +pub fn list_directory( + path: Option<&str>, + show_hidden: bool, + include_files: bool, +) -> Result { + let home = home_directory(); + let raw = path.map(str::trim).filter(|path| !path.is_empty()); + let folder = match raw { + Some(raw) => PathBuf::from(expand_tilde(raw)), + None => home.clone(), + }; + let shown = folder.display().to_string(); + if !folder.is_absolute() { + return Err(LocalhostError::InvalidProjectPath(raw.unwrap_or_default().to_string())); + } + let folder = crate::paths::standardize(&folder); + let unreadable = |error: std::io::Error| match error.kind() { + std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory => { + LocalhostError::ProjectFolderMissing(shown.clone()) + } + _ => LocalhostError::FolderUnreadable { path: shown.clone(), reason: reason(&error) }, + }; + if !folder.is_dir() { + return Err(LocalhostError::ProjectFolderMissing(shown)); + } + let mut entries: Vec = std::fs::read_dir(&folder) + .map_err(unreadable)? + .filter_map(Result::ok) + .filter_map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + if !show_hidden && name.starts_with('.') { + return None; + } + // A link to a folder is one to open. + let is_directory = entry.path().is_dir(); + (is_directory || include_files).then_some(DirectoryEntry { name, is_directory }) + }) + .collect(); + entries.sort_by(|a, b| { + b.is_directory.cmp(&a.is_directory).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) + }); + Ok(DirectoryListing { + path: folder.display().to_string(), + parent: folder.parent().map(|parent| parent.display().to_string()), + home: home.display().to_string(), + entries, + }) +} + +/// The system's reason, without Rust's "(os error 13)". +fn reason(error: &std::io::Error) -> String { + let text = error.to_string(); + match text.find(" (os error") { + Some(end) => text[..end].to_string(), + None => text, + } +} + +/// A Project file's text, read for an import's review. Larger than any +/// Project file is refused rather than read. +pub fn read_project_file(path: &str) -> Result { + const LIMIT: u64 = 1024 * 1024; + let path = expand_tilde(path.trim()); + let failure = |reason: String| LocalhostError::PersistenceFailed { path: path.clone(), reason }; + let size = std::fs::metadata(&path).map_err(|error| failure(reason(&error)))?.len(); + if size > LIMIT { + return Err(failure("it is too large to be a Project file".into())); + } + std::fs::read_to_string(&path).map_err(|error| failure(reason(&error))) +} + +/// Whether `path` is a folder: an imported Project's may not be on this one. +pub fn folder_exists(path: &str) -> bool { + Path::new(&expand_tilde(path)).is_dir() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lists_folders_first_and_hides_dot_names() { + let root = tempfile::tempdir().unwrap(); + for folder in ["web", "Api", ".git"] { + std::fs::create_dir(root.path().join(folder)).unwrap(); + } + std::fs::write(root.path().join("shop.yaml"), "localhost: 1\n").unwrap(); + let path = root.path().to_str().unwrap(); + + let names = |listing: DirectoryListing| listing.entries.into_iter().map(|entry| entry.name).collect::>(); + assert_eq!(names(list_directory(Some(path), false, false).unwrap()), ["Api", "web"]); + assert_eq!(names(list_directory(Some(path), true, true).unwrap()), [".git", "Api", "web", "shop.yaml"]); + + let listing = list_directory(Some(&format!("{path}/web/..")), false, false).unwrap(); + assert_eq!(listing.path, crate::paths::standardize(root.path()).display().to_string()); + assert!(listing.parent.is_some()); + } + + #[test] + fn says_why_a_folder_cant_be_listed() { + let root = tempfile::tempdir().unwrap(); + let missing = root.path().join("gone"); + assert!(matches!(list_directory(missing.to_str(), false, false), Err(LocalhostError::ProjectFolderMissing(_)))); + assert!(matches!( + list_directory(Some("relative/path"), false, false), + Err(LocalhostError::InvalidProjectPath(_)) + )); + assert!(list_directory(None, false, false).is_ok(), "starts at home"); + + #[cfg(unix)] + if !is_root() { + use std::os::unix::fs::PermissionsExt; + let locked = root.path().join("locked"); + std::fs::create_dir(&locked).unwrap(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + let error = list_directory(locked.to_str(), false, false).unwrap_err(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!( + matches!(&error, LocalhostError::FolderUnreadable { reason, .. } if reason == "Permission denied"), + "{error:?}" + ); + } + } + + #[cfg(unix)] + fn is_root() -> bool { + std::process::Command::new("id") + .arg("-u") + .output() + .is_ok_and(|output| String::from_utf8_lossy(&output.stdout).trim() == "0") + } +} diff --git a/core/localhost-core/src/error.rs b/core/localhost-core/src/error.rs index 88337c2..dc576f7 100644 --- a/core/localhost-core/src/error.rs +++ b/core/localhost-core/src/error.rs @@ -148,6 +148,16 @@ pub enum LocalhostError { }, /// The other end runs an older localhost, which can't do this. Unsupported, + /// The Machine (by name) runs a localhost too old to change its + /// Projects from here; they can still be viewed and run. + MachineNeedsUpdate { + machine: String, + }, + /// A folder exists but can't be listed: the system's reason. + FolderUnreadable { + path: String, + reason: String, + }, } impl LocalhostError { @@ -236,6 +246,8 @@ impl LocalhostError { MachineUnavailable { machine, problem } => problem.message(machine), ForwardFailed { port, reason } => format!("Port {port} couldn’t be forwarded: {reason}."), Unsupported => "The other Machine runs an older localhost that can’t do this. Update localhost there.".into(), + MachineNeedsUpdate { machine } => format!("Update localhost on {machine} to manage its Projects."), + FolderUnreadable { path, reason } => format!("{path} can’t be opened: {reason}."), InvalidProjectFile { problem, field, line } => { let line = line.map(|line| format!("Line {line}")); let field = (!field.is_empty()).then(|| field.join(" › ")); diff --git a/core/localhost-core/src/ffi/functions.rs b/core/localhost-core/src/ffi/functions.rs index 42dc5cb..f6d4d79 100644 --- a/core/localhost-core/src/ffi/functions.rs +++ b/core/localhost-core/src/ffi/functions.rs @@ -73,6 +73,13 @@ pub fn suggested_project_key(projects: Vec, name: &str, excluding: Opti crate::suggested_project_key(&projects, name, excluding) } +/// `key` if none of `projects` uses it, else the first free `key-2`, …: the +/// Key "Keep both" imports under, e.g. among another Machine's Projects. +#[uniffi::export] +pub fn free_project_key(projects: Vec, key: Key) -> Key { + crate::free_project_key(&projects, &key) +} + #[uniffi::export] pub fn project_suggested_service_key(project: &Project, name: &str, excluding: Option) -> Key { project.suggested_service_key(name, excluding) diff --git a/core/localhost-core/src/ffi/objects.rs b/core/localhost-core/src/ffi/objects.rs index c6eaf57..6a05adb 100644 --- a/core/localhost-core/src/ffi/objects.rs +++ b/core/localhost-core/src/ffi/objects.rs @@ -12,14 +12,15 @@ use super::runtime::{blocking, on_runtime}; use super::subscriptions::{ FoundOrphansEvents, LibraryEvents, MachinesEvents, OutputLines, ServiceEvents, ServiceOutputLines, }; -use crate::machine::{Forward, MachineSnapshot, Machines}; +use crate::machine::{Forward, MachineSnapshot, Machines, ProjectFileText}; use crate::remote::{Client, shared}; use crate::{ - AgentClient, AgentSetup, AgentStatus, CommandLineStatus, EnvironmentProfile, ExecutionTarget, Id, Key, KeyClash, - Link, Listener, LocalhostError, LogStore, Machine, NewService, Origin, Orphan, OutputLine, ProfileChanges, Project, - ProjectChanges, ProjectDocument, ProjectLibrary, RunRegistry, RunStats, Service, ServiceChanges, ServiceManager, - ServiceManagerOptions, ServiceOutputLine, ServiceStatus, StopPolicy, SystemSecretStore, Targets, Telemetry, - UnreadableProjectFile, VariableInput, VariableLayer, + AgentClient, AgentSetup, AgentStatus, CommandLineStatus, DirectoryListing, EnvironmentProfile, ExecutionTarget, Id, + Key, KeyClash, Link, Listener, LocalhostError, LogStore, Machine, NewService, Origin, Orphan, OutputLine, + ProfileChanges, ProfileInput, Project, ProjectChanges, ProjectDocument, ProjectLibrary, RunRegistry, RunStats, + Service, ServiceChanges, ServiceManager, ServiceManagerOptions, ServiceOutputLine, ServiceStatus, + ServiceSuggestion, StopPolicy, SystemSecretStore, Targets, Telemetry, UnreadableProjectFile, VariableInput, + VariableLayer, }; // MARK: ProjectLibrary @@ -733,6 +734,177 @@ impl Machines { pub fn ffi_forwards(&self, machine_id: Id) -> Vec { self.forwards(machine_id) } + + // Its Project Configuration, changed there. An older localhost there + // refuses with `MachineNeedsUpdate`. + + /// A folder there, for the folder picker; `None` is the home folder there. + #[uniffi::method] + pub async fn ffi_list_directory( + self: Arc, + machine_id: Id, + path: Option, + show_hidden: bool, + include_files: bool, + ) -> Result { + on_runtime(async move { self.list_directory(machine_id, path, show_hidden, include_files).await }).await + } + + #[uniffi::method] + pub async fn ffi_scan_folder( + self: Arc, + machine_id: Id, + path: String, + ) -> Result, LocalhostError> { + on_runtime(async move { self.scan_folder(machine_id, path).await }).await + } + + #[uniffi::method] + pub async fn ffi_scan_project( + self: Arc, + machine_id: Id, + project_id: Id, + ) -> Result, LocalhostError> { + on_runtime(async move { self.scan_project(machine_id, project_id).await }).await + } + + #[uniffi::method] + pub async fn ffi_detect_python_environment( + self: Arc, + machine_id: Id, + project_id: Id, + working_directory: String, + command_line: String, + ) -> Result, LocalhostError> { + on_runtime(async move { + self.detect_python_environment(machine_id, project_id, working_directory, command_line).await + }) + .await + } + + #[uniffi::method] + pub async fn ffi_add_project( + self: Arc, + machine_id: Id, + name: String, + key: Key, + path: String, + services: Vec, + ) -> Result { + on_runtime(async move { self.add_project(machine_id, name, key, path, services).await }).await + } + + #[uniffi::method] + pub async fn ffi_edit_project( + self: Arc, + machine_id: Id, + project_id: Id, + changes: ProjectChanges, + ) -> Result { + on_runtime(async move { self.edit_project(machine_id, project_id, changes).await }).await + } + + /// Stops its Services there first, then removes it and their logs. + #[uniffi::method] + pub async fn ffi_remove_project(self: Arc, machine_id: Id, project_id: Id) -> Result<(), LocalhostError> { + on_runtime(async move { self.remove_project(machine_id, project_id).await }).await + } + + #[uniffi::method] + pub async fn ffi_add_service( + self: Arc, + machine_id: Id, + project_id: Id, + service: NewService, + variables: Vec, + dependencies: Vec, + ) -> Result { + on_runtime(async move { self.add_service(machine_id, project_id, service, variables, dependencies).await }) + .await + } + + #[uniffi::method] + pub async fn ffi_add_services( + self: Arc, + machine_id: Id, + project_id: Id, + services: Vec, + ) -> Result, LocalhostError> { + on_runtime(async move { self.add_services(machine_id, project_id, services).await }).await + } + + #[uniffi::method] + pub async fn ffi_edit_service( + self: Arc, + machine_id: Id, + service_id: Id, + changes: ServiceChanges, + ) -> Result { + on_runtime(async move { self.edit_service(machine_id, service_id, changes).await }).await + } + + /// Stops the Service there first, then removes it and its logs. + #[uniffi::method] + pub async fn ffi_remove_service(self: Arc, machine_id: Id, service_id: Id) -> Result<(), LocalhostError> { + on_runtime(async move { self.remove_service(machine_id, service_id).await }).await + } + + /// The Environment editor: the Project's variables, its Profiles, and + /// which one is active (an index into `profiles`). + #[uniffi::method] + pub async fn ffi_save_environment( + self: Arc, + machine_id: Id, + project_id: Id, + variables: Vec, + profiles: Vec, + active: Option, + ) -> Result<(), LocalhostError> { + on_runtime(async move { self.save_environment(machine_id, project_id, variables, profiles, active).await }) + .await + } + + #[uniffi::method] + pub async fn ffi_set_active_profile( + self: Arc, + machine_id: Id, + project_id: Id, + profile_id: Option, + ) -> Result<(), LocalhostError> { + on_runtime(async move { self.set_active_profile(machine_id, project_id, profile_id).await }).await + } + + /// A Secret's value there, to reveal it. Never stored here. + #[uniffi::method] + pub async fn ffi_secret_value( + self: Arc, + machine_id: Id, + name: String, + layer: VariableLayer, + ) -> Result, LocalhostError> { + on_runtime(async move { self.secret_value(machine_id, name, layer).await }).await + } + + #[uniffi::method] + pub async fn ffi_read_project_file( + self: Arc, + machine_id: Id, + path: String, + ) -> Result { + on_runtime(async move { self.read_project_file(machine_id, path).await }).await + } + + /// Imports a Project file's `text` into the folder `path` there. + #[uniffi::method] + pub async fn ffi_import_project( + self: Arc, + machine_id: Id, + text: String, + path: String, + on_key_clash: Option, + ) -> Result { + on_runtime(async move { self.import_project(machine_id, text, path, on_key_clash).await }).await + } } // MARK: ProjectDocument diff --git a/core/localhost-core/src/lib.rs b/core/localhost-core/src/lib.rs index fcea216..2b011f2 100644 --- a/core/localhost-core/src/lib.rs +++ b/core/localhost-core/src/lib.rs @@ -12,6 +12,7 @@ mod agents; mod ansi; mod dependencies; mod detection; +pub mod editing; mod error; #[cfg(feature = "ffi")] mod ffi; @@ -54,6 +55,7 @@ pub use detection::{ PythonDetector, ScannedDirectory, ServiceDetector, ServiceSuggestion, detect_python_environment, merge_suggestions, runs_in_python_environment, }; +pub use editing::{DirectoryEntry, DirectoryListing, ProfileInput}; pub use error::LocalhostError; pub use fuzzy::FuzzyMatch; pub use id::Id; @@ -65,7 +67,7 @@ pub use logs::{LogBuffer, LogStore}; pub use machine::{Machine, MachineProblem}; pub use model::{ EnvironmentProfile, ExecutionTarget, NewService, Project, Service, VariableInput, VariableLayer, VariableValue, - Variables, service_label, suggested_project_key, + Variables, free_project_key, service_label, suggested_project_key, }; pub use origin::Origin; pub use output::{OutputChannel, OutputLine, ServiceOutputLine}; diff --git a/core/localhost-core/src/library.rs b/core/localhost-core/src/library.rs index 5e07bdb..9ad5f47 100644 --- a/core/localhost-core/src/library.rs +++ b/core/localhost-core/src/library.rs @@ -2,7 +2,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::Path; use std::sync::{Arc, Mutex, MutexGuard}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use tokio::sync::mpsc; use crate::model::VariableValue; @@ -35,7 +35,8 @@ pub enum ProjectLibraryEvent { } /// What to do when an imported Project's Key is already used. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] #[cfg_attr(feature = "ffi", derive(uniffi::Enum))] pub enum KeyClash { /// Swap the imported Configuration into the Project with that Key, @@ -46,7 +47,8 @@ pub enum KeyClash { } /// The fields of a Project to change; `None` leaves a field as it is. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] #[cfg_attr(feature = "ffi", derive(uniffi::Record))] pub struct ProjectChanges { pub name: Option, @@ -62,7 +64,8 @@ pub struct ProjectChanges { /// The fields of a Service to change; `None` leaves a field as it is. For /// `port`, `url`, `python_environment` and `run_before`, `Some(None)` /// removes the value. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] #[cfg_attr(feature = "ffi", derive(uniffi::Record))] pub struct ServiceChanges { pub name: Option, @@ -72,17 +75,41 @@ pub struct ServiceChanges { pub variables: Option>, pub dependencies: Option>, pub is_excluded_from_start_all: Option, + #[serde(with = "double_option", skip_serializing_if = "Option::is_none")] pub port: Option>, + #[serde(with = "double_option", skip_serializing_if = "Option::is_none")] pub url: Option>, pub port_can_change: Option, + #[serde(with = "double_option", skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "ffi", uniffi(default = None))] pub python_environment: Option>, + #[serde(with = "double_option", skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "ffi", uniffi(default = None))] pub run_before: Option>, } +/// `Option>` as a field that is absent (`None`), `null` +/// (`Some(None)`), or a value, so "leave it" and "remove it" stay apart. +mod double_option { + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + pub fn serialize(value: &Option>, serializer: S) -> Result { + match value { + Some(inner) => inner.serialize(serializer), + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, T: Deserialize<'de>, D: Deserializer<'de>>( + deserializer: D, + ) -> Result>, D::Error> { + Option::::deserialize(deserializer).map(Some) + } +} + /// The fields of an Environment Profile to change; `None` leaves a field as it is. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] #[cfg_attr(feature = "ffi", derive(uniffi::Record))] pub struct ProfileChanges { pub name: Option, @@ -745,7 +772,12 @@ fn broadcast(state: &mut State, event: ProjectLibraryEvent) { } fn free_project_key(state: &State, key: &Key) -> Key { - let taken: HashSet<&str> = state.projects.values().map(|project| project.key.as_str()).collect(); + free_key_among(state.projects.values(), key) +} + +/// `key` if none of `projects` uses it, else the first free `key-2`, `key-3`, …. +pub(crate) fn free_key_among<'a>(projects: impl IntoIterator, key: &Key) -> Key { + let taken: HashSet<&str> = projects.into_iter().map(|project| project.key.as_str()).collect(); let base: String = key.as_str().chars().take(Key::MAX_LENGTH - 4).collect(); let mut candidate = key.as_str().to_string(); let mut suffix = 2; diff --git a/core/localhost-core/src/machine/connection.rs b/core/localhost-core/src/machine/connection.rs index 493da57..13ae8c0 100644 --- a/core/localhost-core/src/machine/connection.rs +++ b/core/localhost-core/src/machine/connection.rs @@ -11,8 +11,12 @@ use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader use tokio::sync::{mpsc, oneshot, watch}; use super::MachineProblem; -use super::protocol::{MachineCall, MachineHello, MachineMessage, MachineRequest}; -use crate::{Id, LocalhostError, OutputLine, Project, ServiceEvent, ServiceOutputLine, ServiceStatus}; +use super::protocol::{MANAGES_PROJECTS, MachineCall, MachineHello, MachineMessage, MachineRequest, ProjectFileText}; +use crate::{ + DirectoryListing, Id, Key, KeyClash, LocalhostError, NewService, OutputLine, ProfileInput, Project, ProjectChanges, + Service, ServiceChanges, ServiceEvent, ServiceOutputLine, ServiceStatus, ServiceSuggestion, VariableInput, + VariableLayer, +}; /// How often the app tells the other end it is still there, well within /// `relay::SILENCE_TIMEOUT`, and how long an answer may take before the @@ -218,8 +222,133 @@ impl MachineConnection { Ok((lines, receiver)) } + // MARK: Its Project Configuration + + /// Whether the other end changes its Projects for this app: an older + /// localhost only shows and runs them. + pub fn manages_projects(&self) -> bool { + self.inner.hello.machine_protocol >= MANAGES_PROJECTS + } + + /// A folder there, for a folder picker; `None` is the home folder there. + pub async fn list_directory( + &self, + path: Option, + show_hidden: bool, + include_files: bool, + ) -> Result { + self.manage(MachineRequest::ListDirectory { path, show_hidden, include_files }).await + } + + pub async fn scan_folder(&self, path: String) -> Result, LocalhostError> { + self.manage(MachineRequest::ScanFolder { path }).await + } + + pub async fn scan_project(&self, project_id: Id) -> Result, LocalhostError> { + self.manage(MachineRequest::ScanProject { project_id }).await + } + + pub async fn detect_python_environment( + &self, + project_id: Id, + working_directory: String, + command_line: String, + ) -> Result, LocalhostError> { + self.manage(MachineRequest::DetectPythonEnvironment { project_id, working_directory, command_line }).await + } + + pub async fn add_project( + &self, + name: String, + key: Key, + path: String, + services: Vec, + ) -> Result { + self.manage(MachineRequest::AddProject { name, key, path, services }).await + } + + pub async fn edit_project(&self, project_id: Id, changes: ProjectChanges) -> Result { + self.manage(MachineRequest::EditProject { project_id, changes }).await + } + + pub async fn remove_project(&self, project_id: Id) -> Result<(), LocalhostError> { + self.manage(MachineRequest::RemoveProject { project_id }).await + } + + pub async fn add_service( + &self, + project_id: Id, + service: NewService, + variables: Vec, + dependencies: Vec, + ) -> Result { + self.manage(MachineRequest::AddService { project_id, service, variables, dependencies }).await + } + + pub async fn add_services( + &self, + project_id: Id, + services: Vec, + ) -> Result, LocalhostError> { + self.manage(MachineRequest::AddServices { project_id, services }).await + } + + pub async fn edit_service(&self, service_id: Id, changes: ServiceChanges) -> Result { + self.manage(MachineRequest::EditService { service_id, changes }).await + } + + pub async fn remove_service(&self, service_id: Id) -> Result<(), LocalhostError> { + self.manage(MachineRequest::RemoveService { service_id }).await + } + + pub async fn save_environment( + &self, + project_id: Id, + variables: Vec, + profiles: Vec, + active: Option, + ) -> Result<(), LocalhostError> { + self.manage(MachineRequest::SaveEnvironment { project_id, variables, profiles, active }).await + } + + pub async fn set_active_profile(&self, project_id: Id, profile_id: Option) -> Result<(), LocalhostError> { + self.manage(MachineRequest::SetActiveProfile { project_id, profile_id }).await + } + + /// A Secret's value there, to reveal it. It is only shown, never kept. + pub async fn secret_value(&self, name: String, layer: VariableLayer) -> Result, LocalhostError> { + self.manage(MachineRequest::SecretValue { name, layer }).await + } + + pub async fn read_project_file(&self, path: String) -> Result { + self.manage(MachineRequest::ReadProjectFile { path }).await + } + + /// Imports the Project file's `text` into the folder `path` there. + pub async fn import_project( + &self, + text: String, + path: String, + on_key_clash: Option, + ) -> Result { + self.manage(MachineRequest::ImportProject { text, path, on_key_clash }).await + } + // MARK: Plumbing + /// A request an older localhost can't answer: refused here when its + /// hello says so, and its `Unsupported` worded the same way. + async fn manage(&self, request: MachineRequest) -> Result { + let needs_update = || LocalhostError::MachineNeedsUpdate { machine: self.inner.machine.clone() }; + if !self.manages_projects() { + return Err(needs_update()); + } + self.call(request).await.map_err(|error| match error { + LocalhostError::Unsupported => needs_update(), + error => error, + }) + } + fn state(&self) -> MutexGuard<'_, State> { self.inner.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } diff --git a/core/localhost-core/src/machine/machines.rs b/core/localhost-core/src/machine/machines.rs index 2966583..7322bac 100644 --- a/core/localhost-core/src/machine/machines.rs +++ b/core/localhost-core/src/machine/machines.rs @@ -22,8 +22,12 @@ use serde::{Deserialize, Serialize}; use tokio::sync::{Notify, mpsc}; use tokio::task::JoinHandle; -use super::{Forward, Machine, MachineConnection, MachineProblem, SshLink}; -use crate::{Id, LocalhostError, OutputLine, Project, ServiceEvent, ServiceOutputLine, ServiceStatus}; +use super::{Forward, Machine, MachineConnection, MachineProblem, ProjectFileText, SshLink}; +use crate::{ + DirectoryListing, Id, Key, KeyClash, LocalhostError, NewService, OutputLine, ProfileInput, Project, ProjectChanges, + Service, ServiceChanges, ServiceEvent, ServiceOutputLine, ServiceStatus, ServiceSuggestion, VariableInput, + VariableLayer, +}; const FILE_NAME: &str = "machines.json"; const SCHEMA_VERSION: i64 = 1; @@ -45,9 +49,14 @@ const RETRY_DELAYS: [Duration; 5] = [ pub enum MachineState { NotConnected, Connecting, - /// Connected to the localhost of this version there. + /// Connected to the localhost of this version there. Without + /// `manages_projects`, it is too old for its Projects to be changed from + /// here: they are shown and run only. + #[serde(rename_all = "camelCase")] Connected { version: String, + #[serde(default)] + manages_projects: bool, }, /// Not connected, for this reason. `is_retrying`: another attempt comes /// on its own. @@ -65,7 +74,7 @@ impl MachineState { match self { MachineState::NotConnected => "Not connected".into(), MachineState::Connecting => "Connecting…".into(), - MachineState::Connected { version } => format!("Connected · localhost {version}"), + MachineState::Connected { version, .. } => format!("Connected · localhost {version}"), MachineState::Unavailable { problem, is_retrying: true } => { format!("{} Trying again…", problem.message(machine)) } @@ -386,6 +395,155 @@ impl Machines { self.connection(machine_id)?.subscribe_to_services(service_ids).await } + // MARK: Its Project Configuration + // + // Made there, as `Origin::Machine`; what changed comes back with its + // Projects. A Machine with an older localhost refuses with + // `MachineNeedsUpdate`. + + /// Its Projects, as last read: for a Key no other Project there has. + pub fn projects(&self, machine_id: Id) -> Result, LocalhostError> { + let state = self.inner.state(); + state.machine(machine_id)?; + Ok(state.slots.get(&machine_id).map(|slot| slot.projects.clone()).unwrap_or_default()) + } + + /// A folder there, for a folder picker; `None` is the home folder there. + pub async fn list_directory( + &self, + machine_id: Id, + path: Option, + show_hidden: bool, + include_files: bool, + ) -> Result { + self.connection(machine_id)?.list_directory(path, show_hidden, include_files).await + } + + /// Suggestions for a folder there, scanned there. + pub async fn scan_folder(&self, machine_id: Id, path: String) -> Result, LocalhostError> { + self.connection(machine_id)?.scan_folder(path).await + } + + pub async fn scan_project(&self, machine_id: Id, project_id: Id) -> Result, LocalhostError> { + self.connection(machine_id)?.scan_project(project_id).await + } + + pub async fn detect_python_environment( + &self, + machine_id: Id, + project_id: Id, + working_directory: String, + command_line: String, + ) -> Result, LocalhostError> { + self.connection(machine_id)?.detect_python_environment(project_id, working_directory, command_line).await + } + + pub async fn add_project( + &self, + machine_id: Id, + name: String, + key: Key, + path: String, + services: Vec, + ) -> Result { + self.connection(machine_id)?.add_project(name, key, path, services).await + } + + pub async fn edit_project( + &self, + machine_id: Id, + project_id: Id, + changes: ProjectChanges, + ) -> Result { + self.connection(machine_id)?.edit_project(project_id, changes).await + } + + /// Stops its Services there, then removes it and their logs. Its folder + /// is not touched. + pub async fn remove_project(&self, machine_id: Id, project_id: Id) -> Result<(), LocalhostError> { + self.connection(machine_id)?.remove_project(project_id).await + } + + pub async fn add_service( + &self, + machine_id: Id, + project_id: Id, + service: NewService, + variables: Vec, + dependencies: Vec, + ) -> Result { + self.connection(machine_id)?.add_service(project_id, service, variables, dependencies).await + } + + pub async fn add_services( + &self, + machine_id: Id, + project_id: Id, + services: Vec, + ) -> Result, LocalhostError> { + self.connection(machine_id)?.add_services(project_id, services).await + } + + pub async fn edit_service( + &self, + machine_id: Id, + service_id: Id, + changes: ServiceChanges, + ) -> Result { + self.connection(machine_id)?.edit_service(service_id, changes).await + } + + /// Stops the Service there, then removes it and its logs. + pub async fn remove_service(&self, machine_id: Id, service_id: Id) -> Result<(), LocalhostError> { + self.connection(machine_id)?.remove_service(service_id).await + } + + pub async fn save_environment( + &self, + machine_id: Id, + project_id: Id, + variables: Vec, + profiles: Vec, + active: Option, + ) -> Result<(), LocalhostError> { + self.connection(machine_id)?.save_environment(project_id, variables, profiles, active).await + } + + pub async fn set_active_profile( + &self, + machine_id: Id, + project_id: Id, + profile_id: Option, + ) -> Result<(), LocalhostError> { + self.connection(machine_id)?.set_active_profile(project_id, profile_id).await + } + + /// A Secret's value there, to reveal it. Never kept here. + pub async fn secret_value( + &self, + machine_id: Id, + name: String, + layer: VariableLayer, + ) -> Result, LocalhostError> { + self.connection(machine_id)?.secret_value(name, layer).await + } + + /// A Project file there, for the import's review. + pub async fn read_project_file(&self, machine_id: Id, path: String) -> Result { + self.connection(machine_id)?.read_project_file(path).await + } + + /// Imports a Project file's `text` into the folder `path` there. + pub async fn import_project( + &self, + machine_id: Id, + text: String, + path: String, + on_key_clash: Option, + ) -> Result { + self.connection(machine_id)?.import_project(text, path, on_key_clash).await + } + /// The URL to open for a Service of the Machine on this computer, as /// for a Service here (`Service::url_to_open`), its Port forwarded to the /// same port here first. `None` when it has nothing to open. A URL that @@ -655,7 +813,8 @@ async fn follow(inner: &Weak, machine_id: Id, link: Arc, connect state.publish(MachinesEvent::ProjectsChanged { machine_id, projects }); state.publish(MachinesEvent::StatusesChanged { machine_id, statuses }); let version = connection.hello().version.clone(); - state.set(machine_id, MachineState::Connected { version }); + let manages_projects = connection.manages_projects(); + state.set(machine_id, MachineState::Connected { version, manages_projects }); } loop { tokio::select! { @@ -859,7 +1018,7 @@ mod tests { let untrusted = MachineState::Unavailable { problem: MachineProblem::HostKeyNotTrusted, is_retrying: false }; assert!(untrusted.needs_user()); assert_eq!( - MachineState::Connected { version: "0.5.0".into() }.summary("devbox"), + MachineState::Connected { version: "0.5.0".into(), manages_projects: true }.summary("devbox"), "Connected · localhost 0.5.0" ); assert!(MachineState::NotConnected.needs_user()); diff --git a/core/localhost-core/src/machine/mod.rs b/core/localhost-core/src/machine/mod.rs index 8345536..4deffb5 100644 --- a/core/localhost-core/src/machine/mod.rs +++ b/core/localhost-core/src/machine/mod.rs @@ -1,8 +1,9 @@ //! Machines: other computers whose localhost this app shows, reached over //! SSH as the user already reaches them (`~/.ssh/config`, keys, the agent, //! Tailscale or any other network). Each Machine keeps its own Project -//! Configuration, Secrets, shared core and Runs; this app only views and -//! controls them. +//! Configuration, Secrets, shared core and Runs; this app views, controls +//! and edits them there. A Secret typed here is sent to the Machine that +//! keeps it, and never stored here. //! //! The app runs `ssh localhost remote --stdio` (`ssh`), which //! serves the other Machine's Projects, statuses and logs over the Machine @@ -23,7 +24,7 @@ use serde::{Deserialize, Serialize}; pub use connection::MachineConnection; pub use machines::{MachineSnapshot, MachineState, Machines, MachinesEvent}; -pub use protocol::{MACHINE_PROTOCOL_VERSION, MachineHello}; +pub use protocol::{MACHINE_PROTOCOL_VERSION, MANAGES_PROJECTS, MachineHello, ProjectFileText}; pub use ssh::{Forward, SshLink}; pub use ssh_config::ssh_config_hosts; diff --git a/core/localhost-core/src/machine/protocol.rs b/core/localhost-core/src/machine/protocol.rs index cf4f31f..542316d 100644 --- a/core/localhost-core/src/machine/protocol.rs +++ b/core/localhost-core/src/machine/protocol.rs @@ -10,10 +10,18 @@ use std::collections::HashSet; use serde::{Deserialize, Serialize}; -use crate::{Id, LocalhostError, OutputLine, Project, ServiceEvent, ServiceOutputLine}; +use crate::{ + Id, KeyClash, LocalhostError, NewService, OutputLine, ProfileInput, Project, ProjectChanges, ServiceChanges, + ServiceEvent, ServiceOutputLine, VariableInput, VariableLayer, +}; /// Grows by one whenever a request or message is added. Never reset. -pub const MACHINE_PROTOCOL_VERSION: u32 = 1; +/// +/// 2: the Project Configuration is changed from the app (`MANAGES_PROJECTS`). +pub const MACHINE_PROTOCOL_VERSION: u32 = 2; + +/// The first version whose Projects the app can add, edit and remove. +pub const MANAGES_PROJECTS: u32 = 2; /// The first line `localhost remote --stdio` writes. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -101,11 +109,97 @@ pub(crate) enum MachineRequest { CloseLog { stream: u64, }, + + // Since `MANAGES_PROJECTS`: changes to the Project Configuration there, + // validated and saved there, as its own app makes them. + /// Replies with a `DirectoryListing`; `None` is the home folder. + ListDirectory { + path: Option, + show_hidden: bool, + include_files: bool, + }, + /// Replies with the Suggestions for a folder there, once it exists. + ScanFolder { + path: String, + }, + ScanProject { + project_id: Id, + }, + DetectPythonEnvironment { + project_id: Id, + working_directory: String, + command_line: String, + }, + AddProject { + name: String, + key: crate::Key, + path: String, + services: Vec, + }, + EditProject { + project_id: Id, + changes: ProjectChanges, + }, + RemoveProject { + project_id: Id, + }, + AddService { + project_id: Id, + service: NewService, + variables: Vec, + dependencies: Vec, + }, + AddServices { + project_id: Id, + services: Vec, + }, + EditService { + service_id: Id, + changes: ServiceChanges, + }, + RemoveService { + service_id: Id, + }, + SaveEnvironment { + project_id: Id, + variables: Vec, + profiles: Vec, + active: Option, + }, + SetActiveProfile { + project_id: Id, + profile_id: Option, + }, + /// Replies with a stored Secret's value, to reveal it in the editor. + SecretValue { + name: String, + layer: VariableLayer, + }, + /// Replies with a `ProjectFileText`. + ReadProjectFile { + path: String, + }, + /// Imports the Project file's `text` into the folder `path` there. + ImportProject { + text: String, + path: String, + on_key_clash: Option, + }, /// A request from a newer app. #[serde(other)] Unsupported, } +/// A Project file on the Machine, for the import's review. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(feature = "ffi", derive(uniffi::Record))] +pub struct ProjectFileText { + pub text: String, + /// Whether the folder the file names is there. + pub folder_exists: bool, +} + /// What `localhost remote --stdio` writes. #[derive(Debug, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] diff --git a/core/localhost-core/src/machine/relay.rs b/core/localhost-core/src/machine/relay.rs index eb6968c..cf5925a 100644 --- a/core/localhost-core/src/machine/relay.rs +++ b/core/localhost-core/src/machine/relay.rs @@ -2,7 +2,10 @@ //! over SSH. It is one more client of this Machine's shared core, as //! `localhost mcp` is, with this Machine's own `ProjectLibrary` and secret //! store: the app sees the Projects saved here, and a start reads the -//! Secret values here. No Secret value is ever written to the app. +//! Secret values here. Changes the app makes to the Project Configuration +//! are made here, by the same calls this Machine's own app makes, then +//! announced to the shared core so an app open here shows them. A Secret +//! value is written to the app only to reveal it in an editor. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -13,9 +16,12 @@ use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader use tokio::sync::mpsc; use tokio::task::JoinHandle; -use super::protocol::{MachineCall, MachineHello, MachineMessage, MachineRequest}; +use super::protocol::{MachineCall, MachineHello, MachineMessage, MachineRequest, ProjectFileText}; use crate::remote::forward_batches; -use crate::{LocalhostError, Origin, ProjectLibrary, Targets}; +use crate::{ + CommandSyntax, ExecutionTarget, LocalhostError, Origin, ProjectDocument, ProjectLibrary, Targets, editing, + existing_project_folder, +}; /// How long the app may stay silent before the connection counts as lost. /// The app pings far more often; a laptop that went to sleep never closes @@ -153,9 +159,106 @@ impl Relay { done() } MachineRequest::Unsupported => Err(LocalhostError::Unsupported), + request => self.manage(request).await, } } + /// The Project Configuration's requests: folders and Suggestions read + /// here, then changes saved here and announced. + async fn manage(&self, request: MachineRequest) -> Result { + let (library, targets) = (&*self.library, &self.targets); + let result = match request { + MachineRequest::ListDirectory { path, show_hidden, include_files } => { + return value( + blocking(move || editing::list_directory(path.as_deref(), show_hidden, include_files)).await?, + ); + } + MachineRequest::ScanFolder { path } => { + let path = existing_project_folder(&path)?; + return value(targets.scan_folder(&ExecutionTarget::ThisMachine, &path).await?); + } + MachineRequest::ScanProject { project_id } => { + return value(targets.scan_project(&library.project(project_id)?).await?); + } + MachineRequest::DetectPythonEnvironment { project_id, working_directory, command_line } => { + let project = library.project(project_id)?; + if !project.execution_target.is_this_machine() { + return value(None::); + } + return value( + blocking(move || { + Ok(crate::detect_python_environment( + &project.path, + &working_directory, + &command_line, + CommandSyntax::HERE, + )) + }) + .await?, + ); + } + MachineRequest::SecretValue { name, layer } => { + let library = self.library.clone(); + return value(blocking(move || library.secret_value(&name, layer)).await?); + } + MachineRequest::ReadProjectFile { path } => { + let text = blocking(move || editing::read_project_file(&path)).await?; + let document = ProjectDocument::from_yaml(&text)?; + let folder_exists = editing::folder_exists(document.path()); + return value(ProjectFileText { text, folder_exists }); + } + + MachineRequest::AddProject { name, key, path, services } => { + let path = existing_project_folder(&path)?; + value(library.add_project(&name, key, &path, services, ORIGIN)?) + } + MachineRequest::EditProject { project_id, mut changes } => { + if let Some(path) = &changes.path + && library.project(project_id)?.execution_target.is_this_machine() + { + changes.path = Some(existing_project_folder(path)?); + } + value(editing::edit_project(library, targets, project_id, changes, ORIGIN).await?) + } + MachineRequest::RemoveProject { project_id } => { + editing::remove_project(library, targets, project_id, ORIGIN).await?; + done() + } + MachineRequest::AddService { project_id, service, variables, dependencies } => { + value(library.add_service(project_id, service, variables, dependencies, ORIGIN)?) + } + MachineRequest::AddServices { project_id, services } => { + value(library.add_services(services, project_id, ORIGIN)?) + } + MachineRequest::EditService { service_id, changes } => { + value(library.edit_service(service_id, changes, ORIGIN)?) + } + MachineRequest::RemoveService { service_id } => { + editing::remove_service(library, targets, service_id, ORIGIN).await?; + done() + } + MachineRequest::SaveEnvironment { project_id, variables, profiles, active } => { + editing::save_environment(library, project_id, variables, profiles, active, ORIGIN)?; + done() + } + MachineRequest::SetActiveProfile { project_id, profile_id } => { + library.set_active_profile(profile_id, project_id, ORIGIN)?; + done() + } + MachineRequest::ImportProject { text, path, on_key_clash } => { + let mut document = ProjectDocument::from_yaml(&text)?; + document.set_path(existing_project_folder(&path)?); + document.set_execution_target(ExecutionTarget::ThisMachine); + value(editing::import_project(library, targets, &document, on_key_clash, ORIGIN).await?) + } + _ => unreachable!("answered by `handle`"), + }; + // An app open here reads the change again; one that misses it reads + // it at its next launch. + let _ = targets.announce_projects_saved(ORIGIN).await; + result + } + /// Replies with the Projects, then sends them again after every change: /// an edit here, or one another client of the shared core announced. fn forward_projects(self: &Arc, id: u64) -> JoinHandle<()> { @@ -201,6 +304,13 @@ impl Relay { } } +/// Runs file system and secret store work off the runtime's threads. +async fn blocking( + work: impl FnOnce() -> Result + Send + 'static, +) -> Result { + tokio::task::spawn_blocking(work).await.unwrap_or_else(|_| Err(LocalhostError::Unsupported)) +} + async fn write_messages(mut receiver: mpsc::UnboundedReceiver, mut output: W) { while let Some(message) = receiver.recv().await { let mut line = serde_json::to_vec(&message).expect("a message always encodes"); diff --git a/core/localhost-core/src/model.rs b/core/localhost-core/src/model.rs index 47a6cd9..a4e60ed 100644 --- a/core/localhost-core/src/model.rs +++ b/core/localhost-core/src/model.rs @@ -142,6 +142,13 @@ pub fn suggested_project_key(projects: &[Project], name: &str, excluding: Option }) } +/// `key` if no Project among `projects` uses it, else the first free +/// `key-2`, `key-3`, …: the Key an import kept beside another gets, e.g. +/// among another Machine's Projects. +pub fn free_project_key(projects: &[Project], key: &Key) -> Key { + crate::library::free_key_among(projects, key) +} + /// How a Service is named outside its Project, e.g. "My SaaS › API". /// `None` if no Project has it. pub fn service_label(projects: &[Project], service_id: Id) -> Option { @@ -229,7 +236,8 @@ impl Service { /// A Service to add together with others in one save, e.g. a reviewed /// Suggestion. It has no variables yet. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] #[cfg_attr(feature = "ffi", derive(uniffi::Record))] pub struct NewService { pub name: String, @@ -244,9 +252,12 @@ pub struct NewService { /// The Keys of the Services it starts after: others added in the same /// save, or ones the Project already has. Keys, since Services added /// together have no ids yet; they are saved as ids like any Dependency. + #[serde(default)] pub dependency_keys: Vec, + #[serde(default)] #[cfg_attr(feature = "ffi", uniffi(default = None))] pub python_environment: Option, + #[serde(default)] #[cfg_attr(feature = "ffi", uniffi(default = None))] pub run_before: Option, } @@ -297,15 +308,17 @@ impl Variables { } /// One variable as set from an editor. A Secret's value is written to the -/// `SecretStore`; it is never kept in the Project Configuration. -#[derive(Clone, Debug, PartialEq, Eq)] +/// `SecretStore`; it is never kept in the Project Configuration. It crosses +/// the Machine protocol to the Machine whose Secret it is, and no further. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "ffi", derive(uniffi::Record))] pub struct VariableInput { pub name: String, pub value: VariableValue, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "value", rename_all = "camelCase", rename_all_fields = "camelCase")] #[cfg_attr(feature = "ffi", derive(uniffi::Enum))] pub enum VariableValue { Plain(String), diff --git a/core/localhost-core/tests/machines.rs b/core/localhost-core/tests/machines.rs index 1e850f4..7ec9ddd 100644 --- a/core/localhost-core/tests/machines.rs +++ b/core/localhost-core/tests/machines.rs @@ -8,11 +8,11 @@ mod common; use std::sync::Arc; use std::time::Duration; -use common::{Fixture, PATIENCE, key, test_options}; +use common::{Fixture, PATIENCE, free_port, key, test_options}; use localhost_core::machine::{MachineConnection, relay}; use localhost_core::{ - Link, LocalhostError, MachineProblem, NewService, Origin, Project, ProjectLibrary, ServiceEvent, ServiceState, - Targets, + KeyClash, Link, LocalhostError, MachineProblem, NewService, Origin, ProfileInput, Project, ProjectChanges, + ProjectDocument, ProjectLibrary, ServiceChanges, ServiceEvent, ServiceState, Targets, VariableInput, VariableLayer, }; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::sync::mpsc::UnboundedReceiver; @@ -176,3 +176,165 @@ async fn says_why_the_other_machine_cant_serve() { ); assert!(error.message().starts_with("localhost on devbox couldn’t start: localhost 0.4.0 is still running")); } + +// MARK: Its Project Configuration + +#[tokio::test(flavor = "multi_thread")] +async fn adds_a_project_there_from_a_folder_scanned_there() { + let (other, connection) = connect(relay::SILENCE_TIMEOUT).await; + assert!(connection.manages_projects()); + let (_, mut changes) = connection.projects().await.unwrap(); + let home = other._fixture.path().join("shop"); + std::fs::create_dir_all(home.join("web")).unwrap(); + std::fs::write(home.join("package.json"), r#"{"scripts": {"dev": "vite"}}"#).unwrap(); + let path = home.to_str().unwrap().to_string(); + + // The picker sees the Machine's folders. + let listing = connection.list_directory(Some(path.clone()), false, false).await.unwrap(); + assert_eq!(listing.entries.iter().map(|entry| entry.name.as_str()).collect::>(), ["web"]); + let listing = connection.list_directory(Some(path.clone()), false, true).await.unwrap(); + assert!(listing.entries.iter().any(|entry| entry.name == "package.json" && !entry.is_directory)); + + let suggestions = connection.scan_folder(path.clone()).await.unwrap(); + let dev = suggestions.iter().find(|suggestion| suggestion.command_line.contains("dev")).expect("no dev script"); + let services = vec![NewService::from(dev.clone())]; + let project = connection.add_project("Shop".into(), key("shop"), path.clone(), services).await.unwrap(); + assert_eq!(other.library.project(project.id).unwrap().services.len(), 1); + until(&mut changes, |projects| projects.iter().any(|shown| shown.id == project.id)).await; + + // Path errors are the Machine's. + let missing = other._fixture.path().join("gone").to_str().unwrap().to_string(); + let error = connection.add_project("Gone".into(), key("gone"), missing.clone(), vec![]).await.unwrap_err(); + assert_eq!(error, LocalhostError::ProjectFolderMissing(missing.clone())); + assert_eq!(connection.scan_folder(missing).await.unwrap_err(), error); +} + +#[tokio::test(flavor = "multi_thread")] +async fn edits_projects_and_services_there_keeping_secrets_there() { + let (other, connection) = connect(relay::SILENCE_TIMEOUT).await; + let project_id = other.project.id; + let changes = ProjectChanges { + name: Some("App 2".into()), + is_favorite: Some(true), + variables: Some(vec![VariableInput::plain("MODE", "dev"), VariableInput::secret("TOKEN", "s3cret")]), + ..Default::default() + }; + let project = connection.edit_project(project_id, changes).await.unwrap(); + assert!((project.name.as_str(), project.is_favorite) == ("App 2", true)); + assert_eq!(project.variables.secret_names, ["TOKEN"]); + // The value is in the Machine's secret store, and revealed on request. + let layer = VariableLayer::Project(project_id); + assert_eq!(other.library.secret_value("TOKEN", layer).unwrap().as_deref(), Some("s3cret")); + assert_eq!(connection.secret_value("TOKEN".into(), layer).await.unwrap().as_deref(), Some("s3cret")); + + let port = free_port(); + let web = NewService { port: Some(port.into()), ..NewService::new("Web", key("web"), "exec sleep 60") }; + let web = connection.add_service(project_id, web, vec![], vec![]).await.unwrap(); + let worker = NewService::new("Worker", key("worker"), "exec sleep 60"); + let added = connection.add_services(project_id, vec![worker]).await.unwrap(); + // `Some(None)` removes the Port; leaving a field out keeps it. + let changes = ServiceChanges { + port: Some(None), + dependencies: Some(vec![web.id]), + run_before: Some(Some("true".into())), + ..Default::default() + }; + let worker = connection.edit_service(added[0].id, changes).await.unwrap(); + assert_eq!( + (worker.port, worker.dependencies.clone(), worker.run_before.as_deref()), + (None, vec![web.id], Some("true")) + ); + let changes = ServiceChanges { name: Some("Web app".into()), ..Default::default() }; + assert_eq!(connection.edit_service(web.id, changes).await.unwrap().port, Some(port)); + + let profiles = vec![ProfileInput { + profile_id: None, + name: "Testing".into(), + variables: vec![VariableInput::plain("MODE", "test")], + }]; + connection + .save_environment(project_id, vec![VariableInput::existing_secret("TOKEN")], profiles, Some(0)) + .await + .unwrap(); + let project = other.library.project(project_id).unwrap(); + assert_eq!(project.active_profile().map(|profile| profile.name.as_str()), Some("Testing")); + assert_eq!(project.variables.secret_names, ["TOKEN"]); + assert_eq!(other.library.secret_value("TOKEN", layer).unwrap().as_deref(), Some("s3cret")); + + // Removing a running Service stops it first, there. + let (_, mut events) = connection.subscribe().await.unwrap(); + connection.start(web.id, None).await.unwrap(); + until(&mut events, reached(ServiceState::Starting)).await; + connection.remove_service(web.id).await.unwrap(); + let project = other.library.project(project_id).unwrap(); + assert!(project.service(web.id).is_none()); + assert!(project.services[0].dependencies.is_empty()); + + connection.remove_project(project_id).await.unwrap(); + assert!(other.library.projects().is_empty()); + assert_eq!(connection.remove_project(project_id).await.unwrap_err(), LocalhostError::ProjectNotFound(project_id)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn imports_a_project_file_that_is_there() { + let (other, connection) = connect(relay::SILENCE_TIMEOUT).await; + let folder = other._fixture.path().join("api"); + std::fs::create_dir_all(&folder).unwrap(); + let file = other._fixture.path().join("api.yaml"); + let mut document = ProjectDocument::from(&other.library.project(other.project.id).unwrap()); + document.set_path(folder.to_str().unwrap()); + std::fs::write(&file, document.to_yaml()).unwrap(); + + let read = connection.read_project_file(file.to_str().unwrap().into()).await.unwrap(); + assert!(read.folder_exists); + let error = connection.import_project(read.text.clone(), folder.to_str().unwrap().into(), None).await.unwrap_err(); + assert_eq!(error, LocalhostError::DuplicateProjectKey(key("app"))); + let imported = + connection.import_project(read.text, folder.to_str().unwrap().into(), Some(KeyClash::KeepBoth)).await.unwrap(); + assert_eq!((imported.key.as_str(), imported.path.as_str()), ("app-2", folder.to_str().unwrap())); + assert_eq!(other.library.projects().len(), 2); + + let missing = other._fixture.path().join("none.yaml"); + assert!(matches!( + connection.read_project_file(missing.to_str().unwrap().into()).await, + Err(LocalhostError::PersistenceFailed { .. }) + )); +} + +/// A Machine with a localhost from before Projects could be changed from +/// another Machine: its Projects are shown and run, and every change says +/// to update localhost there, without a request it can't answer. +#[tokio::test(flavor = "multi_thread")] +async fn says_to_update_an_older_machine_to_manage_its_projects() { + let (app, older) = tokio::io::duplex(1 << 16); + let (older_reader, mut older_writer) = tokio::io::split(older); + tokio::spawn(async move { + older_writer + .write_all(b"{\"kind\":\"hello\",\"machineProtocol\":1,\"version\":\"0.5.6\",\"hostName\":\"devbox\"}\n") + .await + .unwrap(); + // It answers what it knows and calls the rest unsupported, as 0.5.6 does. + let mut lines = BufReader::new(older_reader).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let call: serde_json::Value = serde_json::from_str(&line).unwrap(); + let result = match call["request"].as_str() { + Some("projects") => serde_json::json!({ "Ok": [] }), + _ => serde_json::json!({ "Err": { "kind": "unsupported" } }), + }; + let reply = serde_json::json!({ "kind": "reply", "id": call["id"], "result": result }); + older_writer.write_all(format!("{reply}\n").as_bytes()).await.unwrap(); + } + }); + let (reader, writer) = tokio::io::split(app); + let connection = MachineConnection::connect("devbox", reader, writer).await.unwrap(); + assert!(!connection.manages_projects()); + assert!(connection.projects().await.unwrap().0.is_empty()); + + let needs_update = LocalhostError::MachineNeedsUpdate { machine: "devbox".into() }; + assert_eq!( + connection.add_project("Shop".into(), key("shop"), "/srv/shop".into(), vec![]).await.unwrap_err(), + needs_update + ); + assert_eq!(connection.list_directory(None, false, false).await.unwrap_err(), needs_update); + assert_eq!(needs_update.message(), "Update localhost on devbox to manage its Projects."); +} diff --git a/site/src/content/docs/machines.md b/site/src/content/docs/machines.md index 39b3777..2cc0f85 100644 --- a/site/src/content/docs/machines.md +++ b/site/src/content/docs/machines.md @@ -1,6 +1,6 @@ -A **Machine** is another computer whose localhost this app shows and controls: a dev box under the desk, a home server, a cloud VM. localhost reaches it with your system's `ssh`, as you already do from a terminal. Its Projects show in the sidebar below this computer's, and you start, stop and watch them from here. +A **Machine** is another computer whose localhost this app shows and controls: a dev box under the desk, a home server, a cloud VM. localhost reaches it with your system's `ssh`, as you already do from a terminal. Its Projects show in the sidebar below this computer's, and you add, edit, start, stop and watch them from here. -Everything stays on the Machine: its Project Configuration, its Secrets and its Runs. Its Services run there, in its login shell, with its files, and read its Secrets from its own secret store; no Secret value ever reaches this computer. Projects on a Machine are edited on that Machine. +Everything stays on the Machine: its Project Configuration, its Secrets and its Runs. Its Services run there, in its login shell, with its files, and read its Secrets from its own secret store. A Secret you type here is sent to the Machine and stored there only; nothing of a Machine's Projects is saved on this computer. ## Add a Machine @@ -45,7 +45,22 @@ If that port is taken on this computer, Open in Browser says so and names who ho ## In the sidebar -Each Machine has its own section below this computer's Projects, under its name. Its Projects look and act like local ones: Start, Stop, Restart, Start All, Stop All, logs and Open in Browser. While the Machine isn't connected, its Projects are dimmed and show what they showed last; the section says why, with **Reconnect** when it waits for you. A connected Machine with no Projects says so. +Each Machine has its own section below this computer's Projects, under its name, with a `+` to add a Project there. Its Projects look and act like local ones: Start, Stop, Restart, Start All, Stop All, logs, Open in Browser, and [their edits](#manage-its-projects). While the Machine isn't connected, its Projects are dimmed and show what they showed last; the section says why, with **Reconnect** when it waits for you. A connected Machine with no Projects says so. + +## Manage its Projects + +A connected Machine's Projects are managed from here as this computer's are, with the same sheets, menus, command palette entries and shortcuts. Each change is made on the Machine, by its localhost, and shows at once in an app open there. + +- **Add a Project**: the `+` next to the Machine's name in the sidebar, then **New Project on devbox…**. With one of its Projects selected, the usual shortcut adds there too. Its folder is picked on the Machine, scanned there, and the Suggestions are reviewed as for a local folder. +- **Import a Project** from a [Project file](/docs/configuration) on the Machine: **Import Project on devbox…**. +- **Edit** a Project, its Environment and Profiles, its Services (add, edit, remove, Detect Services), and **Favorite** it, from its context menu, its `⋯` menu, the Services column or the command palette. +- **Remove** a Project or Service: as here, its running Services are stopped first, on the Machine, and their logs there are deleted. The Project's folder is not touched. + +Folders of a Machine are picked in localhost's own folder picker, since the system's can't browse another computer: a path you can type, its folders in a list, a **Show hidden** switch, and **Choose**. It starts in the Machine's home folder. Paths are checked on the Machine: a folder that isn't there, or that you can't open, says so. + +A Secret's value is set from here like any variable, and stored only in the Machine's secret store. **Reveal** reads it from the Machine to show it, without keeping it here. + +These need a connection: while the Machine isn't connected, they are disabled and say why; nothing is queued for later. A Machine running a localhost from before this was possible shows its Projects and runs them, and says **Update localhost on devbox to manage its Projects.** ## Connections, sleep and quitting diff --git a/site/src/content/guides/remote-dev-box.md b/site/src/content/guides/remote-dev-box.md index aa6f883..19d6ee9 100644 --- a/site/src/content/guides/remote-dev-box.md +++ b/site/src/content/guides/remote-dev-box.md @@ -45,7 +45,7 @@ If the key has a passphrase, `ssh-add` keeps it in the SSH agent. The first `ssh [localhost](/) is a free, open-source desktop app that remembers how each Project runs. A dev box you reach with `ssh` can be one of its [Machines](/docs/machines): its Projects show in the window on your laptop, below the laptop's own, and you start and stop them there. -1. [Install localhost](/docs/install) on both computers, and add your Projects on the dev box, in its app as on any computer ([Quick start](/docs/quick-start)), or through a coding agent there with [`localhost mcp`](/docs/mcp). Projects on the dev box are edited on the dev box; the app there doesn't have to stay open. +1. [Install localhost](/docs/install) on both computers, and add your Projects on the dev box: from the laptop once it is connected (the `+` next to its name in the sidebar picks a folder on the dev box and scans it there), in its own app ([Quick start](/docs/quick-start)), or through a coding agent there with [`localhost mcp`](/docs/mcp). However they are added, they are saved on the dev box; the app there doesn't have to stay open. 2. Check that the laptop's `ssh` finds it. A command run over SSH doesn't read your interactive profile, so with zsh, set `PATH` in `~/.zshenv`, not `~/.zshrc`: ```sh @@ -56,6 +56,6 @@ If the key has a passphrase, `ssh-add` keeps it in the SSH agent. The first `ssh 4. The dev box's Projects show in the sidebar under its name. **Start All**, Stop, Restart and logs work as for a Project on the laptop, and the state of each Service is there at a glance. 5. **Open in Browser** forwards the Service's Port to the same port on your laptop, through the same SSH connection, then opens it: `http://localhost:5173` there is `http://localhost:5173` here, so OAuth callbacks and cookies keep working. -The Services run on the dev box, with its shell, its files and its Secrets; no Secret value reaches the laptop. Nothing new listens on either computer's network: Forwards are bound to the laptop's loopback only. If the connection drops, localhost makes it again on its own, without starting or stopping anything. Services you started from the laptop stop when the connection ends, unless localhost is open on the dev box. +The Services run on the dev box, with its shell, its files and its Secrets; a Secret set from the laptop is stored on the dev box only. Nothing new listens on either computer's network: Forwards are bound to the laptop's loopback only. If the connection drops, localhost makes it again on its own, without starting or stopping anything. Services you started from the laptop stop when the connection ends, unless localhost is open on the dev box. When something doesn't connect, [Machines](/docs/machines#when-it-cant-connect) lists every message localhost shows and what to do.