From 3f64b36ff4736f371b2ea60223fbbac25f5d30cd Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Wed, 25 Nov 2026 03:20:40 +0700 Subject: [PATCH] fix: remove panics and unblock flows --- .github/workflows/rust.yml | 3 + CHANGELOG.md | 24 +++ Cargo.lock | 1 + crates/metadata/src/lib.rs | 2 +- crates/metadata/src/profile.rs | 7 + crates/paths/Cargo.toml | 1 + crates/paths/src/lib.rs | 146 ++++++++-------- crates/settings/src/settings.rs | 11 +- crates/settings/src/store.rs | 118 +++++-------- crates/signed_app/src/app/mod.rs | 4 +- crates/signed_app/src/identity/import.rs | 6 +- crates/signed_app/src/identity/onboarding.rs | 3 + crates/signed_app/src/inbox/helpers.rs | 2 +- crates/signed_app/src/lib.rs | 2 +- crates/signed_app/src/pull_requests/mod.rs | 10 +- crates/signed_app/src/pull_requests/new.rs | 13 +- crates/signed_app/src/repo/commit_diff.rs | 20 +-- crates/signed_app/src/repo/dialogs/create.rs | 5 + crates/signed_app/src/repo/dialogs/init.rs | 3 + crates/signed_app/src/repo/dialogs/reset.rs | 59 +++++-- crates/signed_app/src/repo/files.rs | 28 +++- crates/signed_app/src/repo/helpers.rs | 2 +- crates/signed_app/src/repo/history.rs | 13 +- crates/signed_app/src/repo/mod.rs | 82 +++++---- crates/signed_app/src/repo/refs.rs | 2 +- crates/signed_app/src/settings/helpers.rs | 2 - crates/signed_app/src/settings/mod.rs | 13 ++ crates/signed_app/src/shared/mod.rs | 3 +- crates/signed_core/src/addr.rs | 4 - crates/signed_core/src/git_event.rs | 37 ----- crates/signed_core/src/inbox/group.rs | 2 +- crates/signed_git/src/cache.rs | 19 ++- crates/signed_git/src/diff.rs | 11 +- crates/signed_git/src/history.rs | 3 +- crates/signed_git/src/patch.rs | 8 +- crates/signed_git/src/repo.rs | 94 ++++++----- crates/signed_git/src/scan.rs | 5 + crates/signed_git/src/sync.rs | 5 - crates/signed_nostr/src/signer.rs | 18 +- crates/signed_state/src/backend.rs | 165 ++++++++++++++----- crates/signed_state/src/checkouts.rs | 24 +-- crates/signed_state/src/inbox.rs | 5 +- crates/signed_state/src/lib.rs | 55 ++++++- crates/signed_state/src/local_repos.rs | 106 +++--------- crates/signed_state/src/repo.rs | 82 ++++++--- crates/signed_state/src/repos.rs | 23 ++- crates/signed_state/src/state.rs | 12 +- crates/signed_state/src/sync_status.rs | 20 ++- crates/ui/src/components/combobox.rs | 18 ++ crates/utils/src/repo_url.rs | 3 +- crates/utils/src/time.rs | 2 +- desktop/src/main.rs | 14 +- 52 files changed, 753 insertions(+), 567 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 852433d..0532bfa 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -28,5 +28,8 @@ jobs: - name: Build run: cargo build --verbose + - name: Lint + run: cargo clippy --workspace --all-targets -- -D warnings + - name: Run tests run: cargo test --verbose diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ba56ac..b9c3d66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## Unreleased + +### Changed + +- Opening a repository no longer runs a forced checkout of its worktree +- Deleting a repository now waits until its deletion events are accepted by a relay + +### Fixed + +- Fix opening a local repository or switching its branch discarding uncommitted changes, a checkout now refuses to overwrite uncommitted edits or untracked files and leaves the branch untouched when it fails +- Fix viewing a commit diff crashing when the repository configures an external diff driver +- Fix an unreadable `settings.json` being replaced by defaults on the next settings change, the file is now left untouched and the error is shown in Settings +- Fix the app panicking at startup when the nostr database or a platform directory cannot be opened, a damaged database now falls back to a temporary cache and startup failures quit cleanly +- Fix a pending session restore replacing an identity that was just imported, or signing back in after signing out +- Fix the New pull request panel closing as if the pull request was published when the patch or the pull request event failed to publish +- Fix push and clone actions staying blocked with "already in progress" after their view closed mid-operation +- Fix the reset remote dialog reporting no deleted refs while a grasp server was unreachable, the reset is now blocked until every server can be listed +- Fix exported commit patches turning a file without a trailing newline into one with a newline +- Fix each patch event of a multi-commit series repeating every later commit's patch, and series with CRLF line endings being split at the wrong offsets +- Fix mirror cache directories colliding for repository identifiers that differ only in characters removed by sanitization +- Fix profiles staying stuck after a failed database query, and a repository view showing "Cloning repository" forever when no announcement is found +- Fix commit patch downloads failing silently and dismissed pull request alerts staying on screen +- Fix busy dialogs being dismissed by Escape or a backdrop click while their task was still running + ## v0.2.0 - 2026/10/21 ### Added diff --git a/Cargo.lock b/Cargo.lock index 3c2c6a0..9c893f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5626,6 +5626,7 @@ name = "paths" version = "0.2.0" dependencies = [ "dirs", + "log", ] [[package]] diff --git a/crates/metadata/src/lib.rs b/crates/metadata/src/lib.rs index 3d72102..f4673c7 100644 --- a/crates/metadata/src/lib.rs +++ b/crates/metadata/src/lib.rs @@ -1,7 +1,7 @@ mod profile; use gpui::{App, AppContext}; -pub use profile::{Profile, ProfileDirectory, ProfileEvent, ProfileStore}; +pub use profile::{Profile, ProfileDirectory, ProfileStore}; /// Initialize the global profile store. pub fn init(cx: &mut App) { diff --git a/crates/metadata/src/profile.rs b/crates/metadata/src/profile.rs index 94b389a..1be06f8 100644 --- a/crates/metadata/src/profile.rs +++ b/crates/metadata/src/profile.rs @@ -320,6 +320,7 @@ impl ProfileDirectory { Ok::<_, anyhow::Error>(Profile::latest_profiles(events)) }); + self.tasks.retain(|task| !task.is_ready()); self.tasks.push(cx.spawn(async move |this, cx| { let loaded = work.await; @@ -335,6 +336,12 @@ impl ProfileDirectory { } Err(e) => { log::warn!("failed to load profiles from the database: {e}"); + // A failed query must not pin these keys forever. + this.with_pending(|pending| { + for key in &keys { + pending.remove(key); + } + }); keys } }; diff --git a/crates/paths/Cargo.toml b/crates/paths/Cargo.toml index d0c2a55..7105685 100644 --- a/crates/paths/Cargo.toml +++ b/crates/paths/Cargo.toml @@ -6,6 +6,7 @@ publish.workspace = true [dependencies] dirs = "6" +log.workspace = true [lints] workspace = true diff --git a/crates/paths/src/lib.rs b/crates/paths/src/lib.rs index b3f82f4..5d58186 100644 --- a/crates/paths/src/lib.rs +++ b/crates/paths/src/lib.rs @@ -1,105 +1,95 @@ -use std::path::PathBuf; -use std::sync::OnceLock; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; -/// The application name. -/// -/// It derives the platform-specific data, config and cache directory paths. +/// The application name, which derives the platform-specific directory paths. pub const APP_NAME: &str = "Signed"; -/// Lowercased form of [`APP_NAME`]. -/// -/// Used in XDG-style paths on Linux and FreeBSD, and the macOS `~/.config` fallback. +/// Lowercased [`APP_NAME`], used in XDG paths and the macOS `~/.config` fallback. pub const APP_NAME_LOWERCASE: &str = "signed"; -/// The resolved data directory. -/// On macOS, this is `~/Library/Application Support/Signed`. -/// On Linux/FreeBSD, this is `$XDG_DATA_HOME/signed`. -/// On Windows, this is `%LOCALAPPDATA%\Signed`. -static CURRENT_DATA_DIR: OnceLock = OnceLock::new(); +/// The resolved config directory, under the platform's standard config location. +static CONFIG_DIR: LazyLock = LazyLock::new(|| { + if cfg!(target_os = "windows") { + resolve_dir(dirs::config_dir(), "RoamingAppData").join(APP_NAME) + } else if cfg!(any(target_os = "linux", target_os = "freebsd")) { + if let Ok(flatpak_xdg_config) = std::env::var("FLATPAK_XDG_CONFIG_HOME") { + flatpak_xdg_config.into() + } else { + resolve_dir(dirs::config_dir(), "XDG_CONFIG_HOME") + } + .join(APP_NAME_LOWERCASE) + } else { + home_dir().join(".config").join(APP_NAME_LOWERCASE) + } +}); -/// The resolved config directory. -/// On macOS, this is `~/.config/signed`. -/// On Linux/FreeBSD, this is `$XDG_CONFIG_HOME/signed`. -/// On Windows, this is `%APPDATA%\Signed`. -static CONFIG_DIR: OnceLock = OnceLock::new(); +/// The resolved data directory, under the platform's standard data location. +static CURRENT_DATA_DIR: LazyLock = LazyLock::new(|| { + if cfg!(target_os = "macos") { + home_dir() + .join("Library/Application Support") + .join(APP_NAME) + } else if cfg!(any(target_os = "linux", target_os = "freebsd")) { + if let Ok(flatpak_xdg_data) = std::env::var("FLATPAK_XDG_DATA_HOME") { + flatpak_xdg_data.into() + } else { + resolve_dir(dirs::data_local_dir(), "XDG_DATA_HOME") + } + .join(APP_NAME_LOWERCASE) + } else if cfg!(target_os = "windows") { + resolve_dir(dirs::data_local_dir(), "LocalAppData").join(APP_NAME) + } else { + config_dir().to_path_buf() + } +}); -fn home_dir() -> PathBuf { - dirs::home_dir().expect("failed to determine home directory") +static NOSTR_DIR: LazyLock = LazyLock::new(|| data_dir().join("nostr")); + +static REPOS_DIR: LazyLock = + LazyLock::new(|| std::env::temp_dir().join(APP_NAME_LOWERCASE).join("repos")); + +static SETTINGS_FILE: LazyLock = LazyLock::new(|| config_dir().join("settings.json")); + +/// Returns `dir`, or the temp directory when the platform could not resolve it. +fn resolve_dir(dir: Option, name: &str) -> PathBuf { + dir.unwrap_or_else(|| { + log::warn!("failed to determine the {name} directory; falling back to the temp directory"); + std::env::temp_dir() + }) } -/// Returns the current user's Desktop folder. -/// -/// Falls back to the home directory or an empty path when it cannot be determined. +fn home_dir() -> PathBuf { + resolve_dir(dirs::home_dir(), "home") +} + +/// Returns the user's Desktop folder, falling back to home and then to an empty path. pub fn desktop_dir() -> PathBuf { dirs::desktop_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_default()) } -/// Returns the current user's Documents folder. -/// -/// Falls back to the home directory or an empty path when it cannot be determined. +/// Returns the user's Documents folder, falling back to home and then to an empty path. pub fn documents_dir() -> PathBuf { dirs::document_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_default()) } -fn config_dir() -> &'static PathBuf { - CONFIG_DIR.get_or_init(|| { - if cfg!(target_os = "windows") { - dirs::config_dir() - .expect("failed to determine RoamingAppData directory") - .join(APP_NAME) - } else if cfg!(any(target_os = "linux", target_os = "freebsd")) { - if let Ok(flatpak_xdg_config) = std::env::var("FLATPAK_XDG_CONFIG_HOME") { - flatpak_xdg_config.into() - } else { - dirs::config_dir().expect("failed to determine XDG_CONFIG_HOME directory") - } - .join(APP_NAME_LOWERCASE) - } else { - home_dir().join(".config").join(APP_NAME_LOWERCASE) - } - }) +fn config_dir() -> &'static Path { + CONFIG_DIR.as_path() } -fn data_dir() -> &'static PathBuf { - CURRENT_DATA_DIR.get_or_init(|| { - if cfg!(target_os = "macos") { - home_dir() - .join("Library/Application Support") - .join(APP_NAME) - } else if cfg!(any(target_os = "linux", target_os = "freebsd")) { - if let Ok(flatpak_xdg_data) = std::env::var("FLATPAK_XDG_DATA_HOME") { - flatpak_xdg_data.into() - } else { - dirs::data_local_dir().expect("failed to determine XDG_DATA_HOME directory") - } - .join(APP_NAME_LOWERCASE) - } else if cfg!(target_os = "windows") { - dirs::data_local_dir() - .expect("failed to determine LocalAppData directory") - .join(APP_NAME) - } else { - config_dir().clone() - } - }) +fn data_dir() -> &'static Path { + CURRENT_DATA_DIR.as_path() } /// Returns the path to the nostr database directory, LMDB. -pub fn nostr_dir() -> &'static PathBuf { - static NOSTR_DIR: OnceLock = OnceLock::new(); - NOSTR_DIR.get_or_init(|| data_dir().join("nostr")) +pub fn nostr_dir() -> &'static Path { + NOSTR_DIR.as_path() } -/// Returns the path to the local git clone cache, the grasp mirrors. -/// -/// The mirrors are disposable and re-cloned from their grasp server on -/// demand, so the cache lives in the OS temp directory for the system to -/// reclaim. -pub fn repos_dir() -> &'static PathBuf { - static REPOS_DIR: OnceLock = OnceLock::new(); - REPOS_DIR.get_or_init(|| std::env::temp_dir().join(APP_NAME_LOWERCASE).join("repos")) +/// The grasp mirror cache, disposable and re-cloned on demand, so it lives in the temp directory. +pub fn repos_dir() -> &'static Path { + REPOS_DIR.as_path() } -pub fn settings_file() -> &'static PathBuf { - static SETTINGS_FILE: OnceLock = OnceLock::new(); - SETTINGS_FILE.get_or_init(|| config_dir().join("settings.json")) +pub fn settings_file() -> &'static Path { + SETTINGS_FILE.as_path() } diff --git a/crates/settings/src/settings.rs b/crates/settings/src/settings.rs index 199b3f7..addacc3 100644 --- a/crates/settings/src/settings.rs +++ b/crates/settings/src/settings.rs @@ -49,11 +49,7 @@ impl Default for GraspServersSettings { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct LocalReposSettings { - /// The directories scanned for local git repositories, - /// Defaults: - /// - /// - `~/Desktop` - /// - `~/Documents` + /// Directories scanned for local git repositories. `~/Desktop` and `~/Documents` by default. pub scan_paths: Vec, } @@ -65,10 +61,7 @@ impl Default for LocalReposSettings { } } -/// A remembered association between a local checkout folder and an announced repository, -/// recorded when the user clones a repository or picks a folder in the New PR panel. -/// -/// The panel can then prefill the folder later without asking again. +/// A checkout folder paired with its announced repository, so the New PR panel can prefill it. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] #[serde(default)] pub struct CheckoutRecord { diff --git a/crates/settings/src/store.rs b/crates/settings/src/store.rs index 690fbc6..9a74cd7 100644 --- a/crates/settings/src/store.rs +++ b/crates/settings/src/store.rs @@ -1,6 +1,6 @@ use std::path::{Path, PathBuf}; -use anyhow::Result; +use anyhow::{Result, bail}; use gpui::{App, Context, Entity, Global}; use crate::Settings; @@ -9,13 +9,14 @@ struct GlobalSettingsStore(Entity); impl Global for GlobalSettingsStore {} -/// The application settings, -/// loaded from disk at startup and saved whenever they change. -/// -/// Installed as a global by the app so any part of the UI can read and edit them. +/// The application settings, loaded from disk and saved on change; installed as a global. pub struct SettingsStore { path: PathBuf, settings: Settings, + /// Why the on-disk file was not loaded; such a file is never overwritten. + unreadable: Option, + /// Why the settings are currently not persisted. + pub error: Option, } impl SettingsStore { @@ -34,15 +35,14 @@ impl SettingsStore { cx.set_global(GlobalSettingsStore(entity)); } - /// Load the settings from `path`, - /// falls back to defaults when the file is missing or unreadable. - /// - /// Missing keys merge with the defaults, - /// older settings files keep working as new settings are added. - pub fn new(path: impl AsRef, _cx: &mut Context) -> Self { + /// Loads the settings from `path`, with defaults for a missing or unreadable file. + pub fn new(path: impl AsRef) -> Self { + let (settings, error) = Self::load(path.as_ref()); Self { path: path.as_ref().to_path_buf(), - settings: Self::load(path.as_ref()), + settings, + unreadable: error.clone(), + error, } } @@ -54,103 +54,59 @@ impl SettingsStore { /// Mutate the settings, persist them to disk, and notify observers. pub fn edit(&mut self, f: impl FnOnce(&mut Settings), cx: &mut Context) { f(&mut self.settings); - if let Err(err) = self.save() { - log::error!( - "failed to save settings to {}: {err:#}", - self.path.display() - ); + match self.save() { + Ok(()) => self.error = None, + Err(err) => { + log::error!( + "failed to save settings to {}: {err:#}", + self.path.display() + ); + self.error = Some(format!("{err:#}")); + } } cx.notify(); } /// Read the settings file, merging any missing fields with the defaults. - fn load(path: &Path) -> Settings { + fn load(path: &Path) -> (Settings, Option) { match std::fs::read_to_string(path) { Ok(contents) => match serde_json::from_str::(&contents) { - Ok(settings) => settings, + Ok(settings) => (settings, None), Err(err) => { - log::error!( - "failed to parse settings file {}: {err}; using defaults", - path.display() - ); - Settings::default() + let error = format!("failed to parse settings file {}: {err}", path.display()); + log::error!("{error}; using defaults"); + (Settings::default(), Some(error)) } }, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Settings::default(), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => (Settings::default(), None), Err(err) => { - log::error!( - "failed to read settings file {}: {err}; using defaults", - path.display() - ); - Settings::default() + let error = format!("failed to read settings file {}: {err}", path.display()); + log::error!("{error}; using defaults"); + (Settings::default(), Some(error)) } } } /// Write the settings to disk, replacing the file atomically. fn save(&self) -> Result<()> { + if let Some(reason) = &self.unreadable { + bail!("settings file was not loaded and is left untouched: {reason}"); + } + if let Some(parent) = self.path.parent() { std::fs::create_dir_all(parent)?; } + let json = serde_json::to_string_pretty(&self.settings)?; let tmp = self.path.with_extension("json.tmp"); std::fs::write(&tmp, json)?; + // `rename` cannot replace an existing file on Windows. if cfg!(target_os = "windows") && self.path.exists() { std::fs::remove_file(&self.path)?; } + std::fs::rename(&tmp, &self.path)?; Ok(()) } } - -#[cfg(test)] -mod tests { - use std::sync::atomic::{AtomicUsize, Ordering}; - - use super::*; - - static TEST_FILE_COUNTER: AtomicUsize = AtomicUsize::new(0); - - /// A unique, temporary settings path for one test. - fn temp_settings_path() -> PathBuf { - let n = TEST_FILE_COUNTER.fetch_add(1, Ordering::SeqCst); - std::env::temp_dir().join(format!( - "signed-settings-test-{}-{n}.json", - std::process::id() - )) - } - - fn cleanup(path: &Path) { - let _ = std::fs::remove_file(path); - let _ = std::fs::remove_file(path.with_extension("json.tmp")); - } - - #[test] - fn missing_file_loads_defaults() { - let path = temp_settings_path(); - cleanup(&path); - - let settings = SettingsStore::load(&path); - assert_eq!(settings, Settings::default()); - cleanup(&path); - } - - #[test] - fn save_and_load_roundtrip() { - let path = temp_settings_path(); - cleanup(&path); - - let mut expected = Settings::default(); - expected.create_repository.default_folder = Some(PathBuf::from("/tmp/repos")); - - let store = SettingsStore { - path: path.clone(), - settings: expected.clone(), - }; - store.save().unwrap(); - - assert_eq!(SettingsStore::load(&path), expected); - cleanup(&path); - } -} diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index e5b387e..b8e3f47 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -81,12 +81,10 @@ impl AppRoot { Self::reset_to_explore(&app, window, cx); }); - let appearance = settings.read(cx).settings().appearance; - Self { panels, titlebar, - appearance, + appearance: settings.read(cx).settings().appearance, _subscriptions: subscriptions, } } diff --git a/crates/signed_app/src/identity/import.rs b/crates/signed_app/src/identity/import.rs index 1e6f287..8ae60b5 100644 --- a/crates/signed_app/src/identity/import.rs +++ b/crates/signed_app/src/identity/import.rs @@ -108,7 +108,7 @@ impl ImportDialog { } impl Render for ImportDialog { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let state = self.state.clone(); let secret_input = self.secret_input.clone(); @@ -122,8 +122,12 @@ impl Render for ImportDialog { let action_repass = repass_input.clone(); let action_close = self.handle.clone(); + let busy = state.read(cx).progress.busy; + Dialog::new("import-dialog") .handle(self.handle.clone()) + .close_on_escape(!busy) + .close_on_backdrop(!busy) .min_width(px(520.)) .title("Import identity") .content(move |_window, cx| { diff --git a/crates/signed_app/src/identity/onboarding.rs b/crates/signed_app/src/identity/onboarding.rs index b2e356b..e987da9 100644 --- a/crates/signed_app/src/identity/onboarding.rs +++ b/crates/signed_app/src/identity/onboarding.rs @@ -72,9 +72,12 @@ impl Render for OnboardingDialog { let state = self.state.clone(); let action_state = state.clone(); let this = cx.entity().downgrade(); + let busy = state.read(cx).busy; Dialog::new("onboarding-dialog") .handle(self.handle.clone()) + .close_on_escape(!busy) + .close_on_backdrop(!busy) .min_width(px(520.)) .title("Create identity") .content(move |_window, cx| { diff --git a/crates/signed_app/src/inbox/helpers.rs b/crates/signed_app/src/inbox/helpers.rs index 478e9da..9c2887b 100644 --- a/crates/signed_app/src/inbox/helpers.rs +++ b/crates/signed_app/src/inbox/helpers.rs @@ -45,7 +45,7 @@ pub fn empty_section_row(cx: &App) -> AnyElement { .into_any_element() } -#[allow(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "one per column")] pub fn thread( prefix: &'static str, ix: usize, diff --git a/crates/signed_app/src/lib.rs b/crates/signed_app/src/lib.rs index 43c1ae1..6df52ba 100644 --- a/crates/signed_app/src/lib.rs +++ b/crates/signed_app/src/lib.rs @@ -1,7 +1,7 @@ mod app; mod explore; mod identity; -#[allow(dead_code)] // temporarily unlinked while the shell migrates +#[expect(dead_code, reason = "unlinked while the shell migrates")] mod inbox; mod issues; mod pull_requests; diff --git a/crates/signed_app/src/pull_requests/mod.rs b/crates/signed_app/src/pull_requests/mod.rs index b7ebe00..424994d 100644 --- a/crates/signed_app/src/pull_requests/mod.rs +++ b/crates/signed_app/src/pull_requests/mod.rs @@ -353,7 +353,10 @@ impl Render for PullRequestsView { .title("Pull request warning") .message(warning) .on_dismiss(move |cx| { - dismiss_warning_store.update(cx, |store, _| store.last_warning = None); + dismiss_warning_store.update(cx, |store, cx| { + store.last_warning = None; + cx.notify(); + }); }), ) }) @@ -364,7 +367,10 @@ impl Render for PullRequestsView { .title("Pull request error") .message(error) .on_dismiss(move |cx| { - dismiss_error_store.update(cx, |store, _| store.last_error = None); + dismiss_error_store.update(cx, |store, cx| { + store.last_error = None; + cx.notify(); + }); }), ) }) diff --git a/crates/signed_app/src/pull_requests/new.rs b/crates/signed_app/src/pull_requests/new.rs index 7827be1..bed66a9 100644 --- a/crates/signed_app/src/pull_requests/new.rs +++ b/crates/signed_app/src/pull_requests/new.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, - ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription, + ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, UniformListScrollHandle, WeakEntity, Window, div, px, }; use nostr::prelude::Url; @@ -56,7 +56,6 @@ pub struct NewPullRequestView { scroll_handle: UniformListScrollHandle, pub(super) tasks: Vec>>, source_open: bool, - _subscriptions: Vec, } impl NewPullRequestView { @@ -159,7 +158,6 @@ impl NewPullRequestView { scroll_handle: UniformListScrollHandle::new(), tasks: Vec::new(), source_open: false, - _subscriptions: Vec::new(), } } @@ -511,7 +509,9 @@ impl NewPullRequestView { window: &mut Window, cx: &mut Context, ) { + self.compare_generation = self.compare_generation.wrapping_add(1); self.fork = None; + let Some((branches, current)) = info else { self.error = Some("The chosen folder is not a git repository".into()); self.repo_path = None; @@ -522,6 +522,7 @@ impl NewPullRequestView { cx.notify(); return; }; + if branches.is_empty() { self.error = Some("The repository has no branches yet".into()); self.repo_path = None; @@ -682,6 +683,8 @@ impl NewPullRequestView { cx: &mut Context, ) { self.loading = false; + self.compare_generation = self.compare_generation.wrapping_add(1); + let (base_branches, compare_branches) = match result { Ok(branches) => branches, Err(error) => { @@ -690,11 +693,13 @@ impl NewPullRequestView { return; } }; + if compare_branches.is_empty() { self.error = Some("The fork has no branches to compare".into()); cx.notify(); return; } + if base_branches.is_empty() { self.error = Some("Could not list the target repository's branches.".into()); cx.notify(); @@ -733,7 +738,7 @@ impl NewPullRequestView { self.loading = true; self.error = None; - self.compare_generation += 1; + self.compare_generation = self.compare_generation.wrapping_add(1); let generation = self.compare_generation; cx.notify(); diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/repo/commit_diff.rs index 1fca3dd..26b2319 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/repo/commit_diff.rs @@ -728,22 +728,20 @@ impl CommitDiffView { Err(_) => return Ok(()), }; - let patch = cx + let saved = cx .background_spawn(async move { - Repo::open(&worktree).and_then(|repo| repo.commit_patch(&id)) + let patch = Repo::open(&worktree).and_then(|repo| repo.commit_patch(&id))?; + std::fs::write(&destination, patch)?; + Ok::<(), anyhow::Error>(()) }) .await; - match patch { - Ok(patch) => { - if let Err(error) = std::fs::write(&destination, patch) { - log::warn!("failed to write commit patch: {error}"); - } - } - Err(error) => log::warn!("failed to build commit patch: {error}"), + if let Err(error) = saved { + this.update(cx, |this, cx| { + this.error = Some(format!("{error:#}").into()); + cx.notify(); + })?; } - - this.update(cx, |_, cx| cx.notify())?; Ok(()) }); diff --git a/crates/signed_app/src/repo/dialogs/create.rs b/crates/signed_app/src/repo/dialogs/create.rs index 611c2d3..99059fd 100644 --- a/crates/signed_app/src/repo/dialogs/create.rs +++ b/crates/signed_app/src/repo/dialogs/create.rs @@ -167,13 +167,18 @@ impl Render for CreateRepoDialog { let desc_input = self.desc_input.clone(); let folder_input = self.folder_input.clone(); let relay_input = self.relay_input.clone(); + let state = self.state.clone(); + let busy = state.read(cx).busy; + let grasp_state = self.grasp_state.clone(); let action_state = state.clone(); let this = cx.entity().downgrade(); Dialog::new("create-repo-dialog") .handle(self.handle.clone()) + .close_on_escape(!busy) + .close_on_backdrop(!busy) .min_width(px(520.)) .title("Create Repository") .content(move |_window, cx| { diff --git a/crates/signed_app/src/repo/dialogs/init.rs b/crates/signed_app/src/repo/dialogs/init.rs index 5aa19c3..fbe6100 100644 --- a/crates/signed_app/src/repo/dialogs/init.rs +++ b/crates/signed_app/src/repo/dialogs/init.rs @@ -179,9 +179,12 @@ impl Render for InitRepoDialog { let folder = self.local_path.display().to_string(); let branches = self.branches.clone(); let selected_branch = self.selected_branch.clone(); + let busy = state.read(cx).busy; Dialog::new("init-repo-dialog") .handle(self.handle.clone()) + .close_on_escape(!busy) + .close_on_backdrop(!busy) .min_width(px(520.)) .title("Initialize repository") .content(move |_, cx| { diff --git a/crates/signed_app/src/repo/dialogs/reset.rs b/crates/signed_app/src/repo/dialogs/reset.rs index f1d53bf..867567e 100644 --- a/crates/signed_app/src/repo/dialogs/reset.rs +++ b/crates/signed_app/src/repo/dialogs/reset.rs @@ -1,7 +1,7 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, - Styled as _, Window, div, px, + App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, + Window, div, px, }; use signed_state::RepoStore; use ui::button::{Button, ButtonVariant}; @@ -15,32 +15,48 @@ pub struct ResetRemoteDialog { handle: DialogHandle, store: Entity, deleted: Vec, + /// Servers that could not be listed, so their refs are missing from `deleted`. + unreachable: Vec, state: Entity, } impl ResetRemoteDialog { - pub fn new(store: Entity, deleted: Vec, cx: &mut App) -> Entity { + pub fn new( + store: Entity, + deleted: Vec, + unreachable: Vec, + cx: &mut App, + ) -> Entity { let state = cx.new(|_| DialogProgress::default()); cx.new(|_| Self { handle: DialogHandle::new(true), store, deleted, + unreachable, state, }) } } impl Render for ResetRemoteDialog { - fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + const WARNING: &str = "Grasp servers are overwritten to match the local mirror. Refs that do not exist locally are deleted from the servers. This cannot be undone."; + const ERROR: &str = "Could not reach some grasp servers, their refs are not listed:"; + let deleted = self.deleted.clone(); + let unreachable = self.unreachable.clone(); + let action_unreachable = unreachable.clone(); let store = self.store.clone(); let cancel_close = self.handle.clone(); let confirm_close = self.handle.clone(); let content_state = self.state.clone(); let action_state = self.state.clone(); + let busy = self.state.read(cx).busy; Dialog::new("reset-remote-dialog") .handle(self.handle.clone()) + .close_on_escape(!busy) + .close_on_backdrop(!busy) .min_width(px(480.)) .title("Reset remote to local") .content(move |_, cx| { @@ -49,14 +65,28 @@ impl Render for ResetRemoteDialog { v_flex() .gap_2() .child( - div().text_base() + div() + .text_base() .text_color(cx.theme().colors.muted_foreground) - .child( - "Grasp servers are overwritten to match the local mirror. Refs that do not exist locally are deleted from the servers. This cannot be undone.", - ), + .child(WARNING), ) + .when(!unreachable.is_empty(), |this| { + this.child( + div() + .text_base() + .text_color(cx.theme().ramps.destructive.base) + .child(ERROR), + ) + .children(unreachable.iter().map(|url| { + div() + .text_base() + .font_family(cx.theme().mono_font) + .child(url.clone()) + })) + }) .child(if deleted.is_empty() { - div().text_base() + div() + .text_base() .text_color(cx.theme().colors.muted_foreground) .child("No server refs will be deleted.") .into_any_element() @@ -64,7 +94,8 @@ impl Render for ResetRemoteDialog { v_flex() .gap_1() .children(deleted.iter().map(|name| { - div().text_base() + div() + .text_base() .font_family(cx.theme().mono_font) .child(name.clone()) })) @@ -80,22 +111,24 @@ impl Render for ResetRemoteDialog { let confirm_close = confirm_close.clone(); let confirm_state = action_state.clone(); - let cancel: AnyElement = Button::new("cancel-reset-remote") + let cancel = Button::new("cancel-reset-remote") .label("Cancel") .variant(ButtonVariant::Secondary) + .disabled(busy) .on_click(move |_, _, cx| cancel_close.close(cx)) .into_any_element(); - let confirm: AnyElement = Button::new("confirm-reset-remote") + let confirm = Button::new("confirm-reset-remote") .label("Reset remote") .variant(ButtonVariant::Destructive) .loading(busy) - .disabled(busy) + .disabled(busy || !action_unreachable.is_empty()) .on_click(move |_, window, cx| { let task = store.update(cx, |store, cx| store.reset_repository(cx)); let state = confirm_state.clone(); let close = confirm_close.clone(); let handle = window.window_handle(); + cx.spawn(async move |cx| match task.await { Ok(()) => { cx.update_window(handle, |_, _, cx| close.close(cx)) diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index 4311ead..2dbfccd 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -71,6 +71,8 @@ pub struct RepoFilesView { pending_commits: Vec, loading_commits: bool, tasks: Vec>>, + /// Bumped when the previews are cleared, so loads started before it are dropped. + generation: u64, } impl EventEmitter for RepoFilesView {} @@ -96,6 +98,7 @@ impl RepoFilesView { pending_commits: Vec::new(), loading_commits: false, tasks: Vec::new(), + generation: 0, } } @@ -173,6 +176,7 @@ impl RepoFilesView { self.md = None; self.code = None; self.readme_name = None; + self.generation = self.generation.wrapping_add(1); } /// Refresh after the mirror caught up with the remote. @@ -523,8 +527,7 @@ impl RepoFilesView { return; }; - // Tree paths originate from git, so symlink escapes are accepted; only - // crafted components are rejected, and visibly. + // Tree paths originate from git, so symlink escapes are accepted. if unsafe_path { self.files.insert( path.to_string(), @@ -539,6 +542,8 @@ impl RepoFilesView { self.load_commit(&path, cx); + let generation = self.generation; + let task: Task> = cx.spawn_in(window, async move |this, cx| { let path_for_read = path.clone(); let content = cx @@ -567,6 +572,9 @@ impl RepoFilesView { .await; this.update_in(cx, |this, _window, cx| { + if generation != this.generation { + return; + } this.loading_files.remove(&path); match content { @@ -677,7 +685,9 @@ impl RepoFilesView { }; self.loading_commits = true; + let paths = std::mem::take(&mut self.pending_commits); + let generation = self.generation; let task: Task> = cx.spawn(async move |this, cx| { let rels: Vec = paths.iter().map(PathBuf::from).collect(); @@ -688,13 +698,19 @@ impl RepoFilesView { .await; this.update(cx, |this, cx| { + if generation != this.generation { + return; + } this.loading_commits = false; - if let Ok(found) = result { - for (path, commit) in found { - this.commits - .insert(path.to_string_lossy().into_owned(), commit); + match result { + Ok(found) => { + for (path, commit) in found { + this.commits + .insert(path.to_string_lossy().into_owned(), commit); + } } + Err(error) => log::warn!("failed to load the last commits: {error}"), } if !this.pending_commits.is_empty() { diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index 1fd53bd..7e8c99e 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -443,7 +443,7 @@ pub(super) fn sync_selector( if let Some(value) = selected && (items_changed || selection_changed) { - state.set_selected(Some(value), window, cx); + state.set_selected_silent(Some(value), window, cx); } }); *cached = items; diff --git a/crates/signed_app/src/repo/history.rs b/crates/signed_app/src/repo/history.rs index 362fa5d..a1a3ac4 100644 --- a/crates/signed_app/src/repo/history.rs +++ b/crates/signed_app/src/repo/history.rs @@ -37,7 +37,8 @@ pub struct RepoHistoryView { /// The last load failure, shown instead of the empty list. error: Option, scroll_handle: UniformListScrollHandle, - tasks: Vec>>, + /// The latest walk, assigning it cancels the previous one. + load_task: Option>>, } impl RepoHistoryView { @@ -58,7 +59,7 @@ impl RepoHistoryView { commits: Arc::new(Vec::new()), error: None, scroll_handle: UniformListScrollHandle::new(), - tasks: Vec::new(), + load_task: None, } } @@ -82,12 +83,6 @@ impl RepoHistoryView { self.load(cx); } - /// Reaps finished tasks, then queues another. - fn push_task(&mut self, task: Task>) { - self.tasks.retain(|task| !task.is_ready()); - self.tasks.push(task); - } - fn load(&mut self, cx: &mut Context) { if self.loading_all_commits || self.all_commits.is_some() { return; @@ -122,7 +117,7 @@ impl RepoHistoryView { Ok(()) }); - self.push_task(task); + self.load_task = Some(task); } pub fn open_commit_diff( diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index c5957c4..29620b6 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -264,6 +264,14 @@ impl RepoDetailView { this.track_sync_status(cx); if !this.repo_started && store.read(cx).announcement.is_some() { this.load_repo(window, cx); + } else if this.loading + && store.read(cx).loaded + && store.read(cx).announcement.is_none() + && store.read(cx).path.is_none() + { + // The store finished loading with nothing to clone from. + this.loading = false; + this.error = Some("Repository announcement not found".into()); } cx.notify(); })); @@ -623,21 +631,24 @@ impl RepoDetailView { let Some(worktree) = self.worktree.clone() else { return; }; - let name = name.into(); - let previous_branch = self.refs.branch_select.read(cx).selected().cloned(); - let previous_tag = self.refs.tag_select.read(cx).selected().cloned(); + + // Restored if the checkout fails while HEAD stays detached. + let previous_tag = match kind { + RefKind::Branch => self.refs.tag_select.read(cx).selected().cloned(), + RefKind::Tag => None, + }; match kind { RefKind::Branch => { self.refs .tag_select - .update(cx, |state, cx| state.set_selected(None, window, cx)); + .update(cx, |state, cx| state.set_selected_silent(None, window, cx)); } RefKind::Tag => { self.refs .branch_select - .update(cx, |state, cx| state.set_selected(None, window, cx)); + .update(cx, |state, cx| state.set_selected_silent(None, window, cx)); } } @@ -646,36 +657,42 @@ impl RepoDetailView { let checkout_name = name.clone(); let task: Task> = cx.spawn_in(window, async move |this, cx| { - let result = cx + let outcome = cx .background_spawn(async move { let repo = Repo::open(&worktree); - match kind { + // A failed checkout leaves HEAD alone; report the branch it is still on. + let current = repo.as_ref().ok().and_then(|repo| repo.current_branch()); + let checkout = match kind { RefKind::Branch => { repo.and_then(|repo| repo.checkout_branch(&checkout_name)) } RefKind::Tag => repo.and_then(|repo| repo.checkout_tag(&checkout_name)), + }; + match checkout { + Ok(()) => Ok(current), + Err(error) => Err((error, current)), } }) .await; this.update_in(cx, |this, window, cx| { - match result { - Ok(()) => this.reload_worktree(cx), - Err(error) => { + match outcome { + Ok(_) => this.reload_worktree(cx), + Err((error, current)) => { this.error = Some(format!("Failed to check out {name}: {error}").into()); this.refs.switching_ref = false; + + let detached = current.is_none(); this.refs.restore_selection( &this.refs.branch_select, - &previous_branch, - window, - cx, - ); - this.refs.restore_selection( - &this.refs.tag_select, - &previous_tag, + ¤t.map(Into::into), window, cx, ); + + let tag = if detached { previous_tag } else { None }; + this.refs + .restore_selection(&this.refs.tag_select, &tag, window, cx); } } cx.notify(); @@ -890,6 +907,8 @@ impl RepoDetailView { let probe = cx.background_spawn(async move { let mut deleted: Vec = Vec::new(); + // A server that cannot be listed may still hold refs the reset deletes. + let mut unreachable: Vec = Vec::new(); let repo = Repo::open(&mirror)?; let local: HashSet = repo @@ -900,26 +919,33 @@ impl RepoDetailView { .collect(); for url in &urls { - let Ok(remote_refs) = repo.ls_remote(url) else { - continue; - }; - for (name, _) in remote_refs { - if !local.contains(&name) && !deleted.contains(&name) { - deleted.push(name); + match repo.ls_remote(url) { + Ok(remote_refs) => { + for (name, _) in remote_refs { + if !local.contains(&name) && !deleted.contains(&name) { + deleted.push(name); + } + } } + Err(_) => unreachable.push(url.clone()), } } deleted.sort(); - Ok::<_, Error>(deleted) + Ok::<_, Error>((deleted, unreachable)) }); cx.spawn_in(window, async move |this, cx| { - let deleted = probe.await; + let probe = probe.await; - this.update_in(cx, |this, _window, cx| match deleted { - Ok(deleted) => { - this.reset = Some(dialogs::reset::ResetRemoteDialog::new(store, deleted, cx)); + this.update_in(cx, |this, _window, cx| match probe { + Ok((deleted, unreachable)) => { + this.reset = Some(dialogs::reset::ResetRemoteDialog::new( + store, + deleted, + unreachable, + cx, + )); cx.notify(); } Err(error) => { diff --git a/crates/signed_app/src/repo/refs.rs b/crates/signed_app/src/repo/refs.rs index 2b7a9f2..fd60ca3 100644 --- a/crates/signed_app/src/repo/refs.rs +++ b/crates/signed_app/src/repo/refs.rs @@ -97,7 +97,7 @@ impl RefSwitcher { cx: &mut App, ) { select.update(cx, |state, cx| { - state.set_selected(previous.clone(), window, cx) + state.set_selected_silent(previous.clone(), window, cx) }); } } diff --git a/crates/signed_app/src/settings/helpers.rs b/crates/signed_app/src/settings/helpers.rs index 17e30f2..66ffa79 100644 --- a/crates/signed_app/src/settings/helpers.rs +++ b/crates/signed_app/src/settings/helpers.rs @@ -13,7 +13,6 @@ use ui::select::{Select, SelectOption}; use ui::theme::ActiveTheme as _; use ui::tooltip::Tooltip; -use crate::apply_appearance_mode; use crate::repo::dialogs::grasp_servers::{normalize_server, server_host}; /// The title and description a settings row or block opens with. @@ -80,7 +79,6 @@ pub fn appearance_select(cx: &App) -> Select { SettingsStore::global(cx).update(cx, |store, cx| { store.edit(|settings| settings.appearance = mode, cx); }); - apply_appearance_mode(mode, cx); }) } diff --git a/crates/signed_app/src/settings/mod.rs b/crates/signed_app/src/settings/mod.rs index cdf1e69..95fbb7f 100644 --- a/crates/signed_app/src/settings/mod.rs +++ b/crates/signed_app/src/settings/mod.rs @@ -1,5 +1,6 @@ mod helpers; +use gpui::prelude::FluentBuilder as _; use gpui::{ App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, px, @@ -9,6 +10,7 @@ use helpers::{ scan_paths_editor, setting_block, setting_row, }; use settings::SettingsStore; +use ui::alert::{Alert, AlertSeverity}; use ui::common::v_flex; use ui::dialog::{Dialog, DialogHandle}; use ui::input::InputState; @@ -64,8 +66,19 @@ impl Render for SettingsDialog { .height(px(560.)) .title("Settings") .content(move |_, cx| { + let error = SettingsStore::global(cx).read(cx).error.clone(); + v_flex() .gap_4() + .when_some(error, |this, error| { + this.child( + Alert::new("settings-error") + .severity(AlertSeverity::Danger) + .style(ui::alert::AlertStyle::Inline) + .title("Settings are not saved") + .message(error), + ) + }) .child(setting_row( cx, "Appearance", diff --git a/crates/signed_app/src/shared/mod.rs b/crates/signed_app/src/shared/mod.rs index c520504..52ad0e7 100644 --- a/crates/signed_app/src/shared/mod.rs +++ b/crates/signed_app/src/shared/mod.rs @@ -21,8 +21,7 @@ pub fn log_dropped(result: Result) { } } -/// Tracks a detail view's author, commenters, and repository owner for -/// profile prefetch. +/// Tracks a detail view's author, commenters, and owner for profile prefetch. pub fn track_event_participants( author: Option, owner: Option, diff --git a/crates/signed_core/src/addr.rs b/crates/signed_core/src/addr.rs index 3f63a16..b17e85a 100644 --- a/crates/signed_core/src/addr.rs +++ b/crates/signed_core/src/addr.rs @@ -25,10 +25,6 @@ impl RepoAddr { .collect() } - pub fn kind(&self) -> Kind { - self.0.kind - } - pub fn public_key(&self) -> PublicKey { self.0.public_key } diff --git a/crates/signed_core/src/git_event.rs b/crates/signed_core/src/git_event.rs index 8d5faa3..03f3774 100644 --- a/crates/signed_core/src/git_event.rs +++ b/crates/signed_core/src/git_event.rs @@ -106,40 +106,3 @@ impl GitEvent for Event { .any(|tag| matches!(tag.kind(), "e" | "E") && tag.content() == Some(root.as_str())) } } - -impl GitEvent for &T { - /// Delegates to the referenced event. - fn activity_subject(&self) -> String { - (*self).activity_subject() - } - - /// Delegates to the referenced event. - fn current_commit(&self) -> Option { - (*self).current_commit() - } - - /// Delegates to the referenced event. - fn merge_base(&self) -> Option { - (*self).merge_base() - } - - /// Delegates to the referenced event. - fn clone_urls(&self) -> Option> { - (*self).clone_urls() - } - - /// Delegates to the referenced event. - fn branch_name(&self) -> Option { - (*self).branch_name() - } - - /// Delegates to the referenced event. - fn is_git_activity(&self) -> bool { - (*self).is_git_activity() - } - - /// Delegates to the referenced event. - fn references_root(&self, root: &EventId) -> bool { - (*self).references_root(root) - } -} diff --git a/crates/signed_core/src/inbox/group.rs b/crates/signed_core/src/inbox/group.rs index c301943..e4786e8 100644 --- a/crates/signed_core/src/inbox/group.rs +++ b/crates/signed_core/src/inbox/group.rs @@ -71,7 +71,7 @@ where items.sort_by(|a, b| { b.latest_activity() .cmp(&a.latest_activity()) - .then_with(|| b.root.to_hex().cmp(&a.root.to_hex())) + .then_with(|| b.root.cmp(&a.root)) }); items diff --git a/crates/signed_git/src/cache.rs b/crates/signed_git/src/cache.rs index 5b5c51d..429ecb1 100644 --- a/crates/signed_git/src/cache.rs +++ b/crates/signed_git/src/cache.rs @@ -29,9 +29,12 @@ impl GitCache { /// Returns the cache path for a repository address. pub fn repo_path(&self, addr: &RepoAddr) -> PathBuf { - self.root - .join(addr.public_key().to_hex()) - .join(Self::sanitize_path_component(addr.identifier())) + let identifier = addr.identifier(); + self.root.join(addr.public_key().to_hex()).join(format!( + "{}-{}", + Self::sanitize_path_component(identifier), + Self::identifier_suffix(identifier), + )) } /// Opens the cached repository, or `None` when it is not cloned yet. @@ -103,6 +106,16 @@ impl GitCache { sanitized } + /// Distinct identifiers can sanitize alike, and an empty one is the owner directory. + fn identifier_suffix(id: &str) -> String { + let mut hash: u64 = 0xcbf29ce484222325; + for byte in id.as_bytes() { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x100000001b3); + } + format!("{hash:016x}") + } + /// Returns the `owner/identifier` namespace used for fork checkouts. pub fn fork_namespace(announcement: &Announcement) -> String { format!( diff --git a/crates/signed_git/src/diff.rs b/crates/signed_git/src/diff.rs index 4163818..bf0d38b 100644 --- a/crates/signed_git/src/diff.rs +++ b/crates/signed_git/src/diff.rs @@ -271,11 +271,20 @@ impl ConsumeHunk for PatchCollector { GixLineKind::Remove => '-', GixLineKind::Add => '+', }; + // Tokens may already carry the line's newline; emit exactly one. - let content = content.strip_suffix(b"\n").unwrap_or(content); + let (content, terminated) = match content.strip_suffix(b"\n") { + Some(rest) => (rest, true), + None => (*content, false), + }; + self.text.push(prefix); self.text.push_str(&String::from_utf8_lossy(content)); self.text.push('\n'); + + if !terminated { + self.text.push_str("\\ No newline at end of file\n"); + } } Ok(()) diff --git a/crates/signed_git/src/history.rs b/crates/signed_git/src/history.rs index 5dfe18d..e480f86 100644 --- a/crates/signed_git/src/history.rs +++ b/crates/signed_git/src/history.rs @@ -19,8 +19,7 @@ pub struct FileCommit { pub description: Option, pub author: String, pub time: i64, - /// Human-readable absolute date in the commit's recorded offset, e.g. - /// "Nov 21, 2026 at 4:40 AM GMT+7"; empty when the date cannot be formatted. + /// Date in the commit's offset, e.g. "Nov 21, 2026 at 4:40 AM GMT+7". pub date_label: String, /// Full hex parent ids; empty for patch-parsed commits. pub parents: Vec, diff --git a/crates/signed_git/src/patch.rs b/crates/signed_git/src/patch.rs index f2c7935..badc493 100644 --- a/crates/signed_git/src/patch.rs +++ b/crates/signed_git/src/patch.rs @@ -67,9 +67,10 @@ impl PatchParser { let mut headers_closed = false; let mut offset = 0usize; - for line in patch.lines() { + for raw in patch.split_inclusive('\n') { let line_start = offset; - offset += line.len() + 1; + offset += raw.len(); + let line = raw.trim_end_matches(['\r', '\n']); let is_envelope = line .strip_prefix("From ") @@ -78,7 +79,8 @@ impl PatchParser { if is_envelope { if let Some((start, id, headers)) = current.take() { - messages.push(Envelope::new(&patch[start..], id, headers)); + // A message runs until the next envelope starts. + messages.push(Envelope::new(&patch[start..line_start], id, headers)); } let id = line diff --git a/crates/signed_git/src/repo.rs b/crates/signed_git/src/repo.rs index 4cae1bc..3617335 100644 --- a/crates/signed_git/src/repo.rs +++ b/crates/signed_git/src/repo.rs @@ -594,16 +594,16 @@ impl Repo { } let platform = attached.diff(&mut cache)?; - platform - .resource_cache - .options - .skip_internal_diff_if_external_is_configured = true; let outcome = platform.resource_cache.prepare_diff().into_anyhow()?; match outcome.operation { Operation::InternalDiff { algorithm } => { - let input = outcome.interned_input(); + // Keep line endings so a missing final newline can be marked. + let input = gix::diff::blob::InternedInput::new( + outcome.old.intern_source(), + outcome.new.intern_source(), + ); let diff = gix::diff::blob::diff_with_slider_heuristics(algorithm, &input); let text = gix::diff::blob::UnifiedDiff::new( &diff, @@ -719,10 +719,6 @@ impl Repo { }; let platform = attached.diff(&mut cache)?; - platform - .resource_cache - .options - .skip_internal_diff_if_external_is_configured = true; let outcome = platform.resource_cache.prepare_diff().into_anyhow()?; let (binary, hunks, insertions, deletions) = match outcome.operation { @@ -1180,14 +1176,15 @@ impl Repo { let (signature, mut time_buf) = Self::repository_signature(); let signature = signature.to_ref(&mut time_buf); + // HEAD moves only once the worktree holds the new content. + self.force_checkout(&tree)?; + self.move_head( signature, gix::refs::Target::Symbolic(branch), &format!("checkout: moving to {name}"), )?; - self.force_checkout(&tree)?; - Ok(()) } @@ -1196,21 +1193,19 @@ impl Repo { let full = format!("refs/tags/{name}"); let mut reference = self.inner.find_reference(&full)?; - let commit = reference.peel_to_id()?; let tree = reference.peel_to_tree()?.id; let (signature, mut time_buf) = Self::repository_signature(); let signature = signature.to_ref(&mut time_buf); + self.force_checkout(&tree)?; self.move_head( signature, gix::refs::Target::Object(commit.detach()), &format!("checkout: moving to {name}"), )?; - self.force_checkout(&tree)?; - Ok(()) } @@ -1224,31 +1219,53 @@ impl Repo { let mut index = self.inner.index_from_tree(tree)?; - if let Ok(previous) = self.inner.index_or_empty() { - let keep: HashSet = index - .entries() - .iter() - .map(|entry| { - PathBuf::from(String::from_utf8_lossy(entry.path(&index)).into_owned()) - }) - .collect(); - for entry in previous.entries() { - let rel = entry.path(&previous); - let rel = PathBuf::from(String::from_utf8_lossy(rel).into_owned()); + // `overwrite_existing` below is `git checkout --force`; never discard uncommitted work. + if self.inner.is_dirty()? { + bail!("uncommitted changes would be overwritten; commit or stash them first"); + } - if keep.contains(&rel) { - continue; - } + let previous = self.inner.index_or_empty()?; + let tracked: HashSet<&gix::bstr::BStr> = previous + .entries() + .iter() + .map(|entry| entry.path(&previous)) + .collect(); - let path = workdir.join(&rel); + if let Some(path) = index + .entries() + .iter() + .map(|entry| entry.path(&index)) + .find(|path| { + !tracked.contains(path) && workdir.join(gix::path::from_bstr(*path)).exists() + }) + { + bail!( + "untracked file {} would be overwritten", + String::from_utf8_lossy(path) + ); + } - match std::fs::remove_file(&path) { - Ok(()) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => { - return Err(error) - .with_context(|| format!("failed to remove {}", path.display())); - } + let keep: HashSet = index + .entries() + .iter() + .map(|entry| PathBuf::from(String::from_utf8_lossy(entry.path(&index)).into_owned())) + .collect(); + + for entry in previous.entries() { + let rel = entry.path(&previous); + let rel = PathBuf::from(String::from_utf8_lossy(rel).into_owned()); + + if keep.contains(&rel) { + continue; + } + + let path = workdir.join(&rel); + match std::fs::remove_file(&path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error) + .with_context(|| format!("failed to remove {}", path.display())); } } } @@ -1436,10 +1453,7 @@ impl Repo { ) } - /// Mirrors all branches and tags to the grasp repository at `base_url`. - /// - /// Force refspecs keep the server ref map following the local repository, - /// grasp authorizes pushes by ref map equality, not fast-forwards. + /// Mirrors branches and tags to `base_url` with force refspecs; grasp authorizes by ref map. pub fn push_all(&self, base_url: &str, owner: &str, repo_id: &str) -> Result<()> { self.push_refspecs( base_url, diff --git a/crates/signed_git/src/scan.rs b/crates/signed_git/src/scan.rs index 4b77127..161f8fe 100644 --- a/crates/signed_git/src/scan.rs +++ b/crates/signed_git/src/scan.rs @@ -38,10 +38,15 @@ pub fn find_git_repos(root: &Path) -> Vec { let Some(kind) = entry.file_type() else { return true; }; + if !kind.is_dir() { return true; } + if entry.file_name() == std::ffi::OsStr::new(".git") { + return false; + } + let dir = entry.path(); let Ok(repo) = gix::discover(dir) else { return true; diff --git a/crates/signed_git/src/sync.rs b/crates/signed_git/src/sync.rs index 592bdff..fbd7505 100644 --- a/crates/signed_git/src/sync.rs +++ b/crates/signed_git/src/sync.rs @@ -25,11 +25,6 @@ pub struct RepoSyncStatus { } impl RepoSyncStatus { - /// True when every branch matches the Nostr state. - pub fn in_sync(&self) -> bool { - self.refs.iter().all(|(_, sync)| *sync == RefSync::InSync) - } - /// Maps branch short name to lowercase commit oid. pub(crate) fn branches(refs: &[(String, String)]) -> BTreeMap<&str, String> { refs.iter() diff --git a/crates/signed_nostr/src/signer.rs b/crates/signed_nostr/src/signer.rs index 601a286..3a1f4b1 100644 --- a/crates/signed_nostr/src/signer.rs +++ b/crates/signed_nostr/src/signer.rs @@ -33,7 +33,15 @@ impl UniversalSigner { ::Error: Error + Send + Sync + 'static, ::Error: Error + Send + Sync + 'static, { - *self.inner.write().expect("RwLock poisoned") = Arc::new(InnerSignerImpl(new_signer)); + *self + .inner + .write() + .unwrap_or_else(|error| error.into_inner()) = Arc::new(InnerSignerImpl(new_signer)); + } + + /// A poisoned lock still holds a usable signer, so it is recovered instead of panicking. + fn inner(&self) -> Arc { + Arc::clone(&self.inner.read().unwrap_or_else(|error| error.into_inner())) } } @@ -119,7 +127,7 @@ impl AsyncGetPublicKey for UniversalSigner { fn get_public_key_async( &self, ) -> Pin> + Send + '_>> { - let inner = self.inner.read().expect("RwLock poisoned").clone(); + let inner = self.inner(); Box::pin(async move { inner.get_public_key_async().await }) } } @@ -131,7 +139,7 @@ impl AsyncSignEvent for UniversalSigner { &self, unsigned: UnsignedEvent, ) -> Pin> + Send + '_>> { - let inner = self.inner.read().expect("RwLock poisoned").clone(); + let inner = self.inner(); Box::pin(async move { inner.sign_event_async(unsigned).await }) } } @@ -144,7 +152,7 @@ impl AsyncNip44 for UniversalSigner { public_key: &'a PublicKey, content: &'a str, ) -> Pin> + Send + 'a>> { - let inner = self.inner.read().expect("RwLock poisoned").clone(); + let inner = self.inner(); Box::pin(async move { inner.nip44_encrypt_async(public_key, content).await }) } @@ -153,7 +161,7 @@ impl AsyncNip44 for UniversalSigner { public_key: &'a PublicKey, payload: &'a str, ) -> Pin> + Send + 'a>> { - let inner = self.inner.read().expect("RwLock poisoned").clone(); + let inner = self.inner(); Box::pin(async move { inner.nip44_decrypt_async(public_key, payload).await }) } } diff --git a/crates/signed_state/src/backend.rs b/crates/signed_state/src/backend.rs index a40f48c..0946a12 100644 --- a/crates/signed_state/src/backend.rs +++ b/crates/signed_state/src/backend.rs @@ -6,7 +6,7 @@ use std::time::{Duration, Instant}; use anyhow::{Error, anyhow, bail}; use bitcoin_hashes::sha1::Hash as Sha1Hash; -use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, Global, Task, TaskExt}; +use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, Global, Task}; use nostr::event::IntoEventBuilder; use nostr::nips::nip19::Nip19Coordinate; use nostr_connect::prelude::*; @@ -26,6 +26,7 @@ use crate::state::{GitPushMode, GitPushPolicy, GitRef, PushStepStatus, SyncState pub const USER_KEYRING: &str = "Signed Safe Storage"; const PUMP_DEBOUNCE: Duration = Duration::from_millis(200); +const MAX_SEEN_EVENT_IDS: usize = 65_536; #[derive(Debug, Clone)] pub enum BackendEvent { @@ -58,6 +59,8 @@ pub struct Backend { inbox: Entity, passphrase_required: bool, pushing_repos: Entity>, + /// Bumped by every explicit identity action, results from an older session are dropped. + session: u64, } struct GlobalBackend(Entity); @@ -169,6 +172,7 @@ impl Backend { inbox: cx.new(|_| Inbox::default()), passphrase_required: false, pushing_repos: cx.new(|_| HashSet::new()), + session: 0, } } @@ -179,12 +183,17 @@ impl Backend { } let user = cx.read_credentials(USER_KEYRING); + let session = self.session; let task: Task> = cx.spawn(async move |this, cx| { let content = match user.await { Ok(Some((_username, secret))) => String::from_utf8(secret)?, _ => { - this.update(cx, |_this, cx| cx.emit(BackendEvent::SignerRequired))?; + this.update(cx, |this, cx| { + if this.session == session { + cx.emit(BackendEvent::SignerRequired); + } + })?; return Ok(()); } }; @@ -193,7 +202,7 @@ impl Backend { if content.starts_with("nsec1") { let keys = Keys::new(SecretKey::parse(&content)?); this.update(cx, |this, cx| { - this.set_signer(keys, cx); + this.set_signer(keys, session, cx); })?; } else if content.starts_with("bunker://") { let (base, keys) = extract_master_key(&content)?; @@ -203,16 +212,20 @@ impl Backend { .build()?; this.update(cx, |this, cx| { - this.set_signer(signer, cx); + this.set_signer(signer, session, cx); })?; } else if content.starts_with("ncryptsec1") { this.update(cx, |this, cx| { - this.passphrase_required = true; - cx.emit(BackendEvent::PassphraseRequired); + if this.session == session { + this.passphrase_required = true; + cx.emit(BackendEvent::PassphraseRequired); + } })?; } else { - this.update(cx, |_this, cx| { - cx.emit(BackendEvent::SignerRequired); + this.update(cx, |this, cx| { + if this.session == session { + cx.emit(BackendEvent::SignerRequired); + } })?; } @@ -221,9 +234,11 @@ impl Backend { .await; if let Err(e) = result { - this.update(cx, |_this, cx| { - cx.emit(BackendEvent::error(e.to_string())); - cx.emit(BackendEvent::SignerRequired); + this.update(cx, |this, cx| { + if this.session == session { + cx.emit(BackendEvent::error(e.to_string())); + cx.emit(BackendEvent::SignerRequired); + } })?; } @@ -237,6 +252,7 @@ impl Backend { password: &str, cx: &mut Context, ) -> Task> { + let session = self.supersede_session(); let password = password.to_owned(); let user = cx.read_credentials(USER_KEYRING); @@ -260,7 +276,9 @@ impl Backend { let keys = decrypt_task.await?; let public_key = keys.public_key(); - this.update(cx, |this, cx| this.set_signer(keys, cx))?; + this.update(cx, |this, cx| { + this.set_signer(keys, session, cx); + })?; Ok(public_key) }) @@ -283,6 +301,7 @@ impl Backend { } let password = password.to_owned(); + let session = self.supersede_session(); cx.spawn(async move |this, cx| { let job = cx.background_spawn(async move { @@ -300,7 +319,9 @@ impl Backend { }); write.await?; - this.update(cx, |this, cx| this.set_signer(keys, cx))?; + this.update(cx, |this, cx| { + this.set_signer(keys, session, cx); + })?; Ok(public_key) }) @@ -313,13 +334,13 @@ impl Backend { password: &str, cx: &mut Context, ) -> Task> { - let ncryptsec = ncryptsec.trim().to_owned(); - if password.is_empty() { return Task::ready(Err(anyhow!("Passphrase must not be empty"))); } + let ncryptsec = ncryptsec.trim().to_owned(); let password = password.to_owned(); + let session = self.supersede_session(); cx.spawn(async move |this, cx| { let stored = ncryptsec.clone(); @@ -337,7 +358,9 @@ impl Backend { }); write.await?; - this.update(cx, |this, cx| this.set_signer(keys, cx))?; + this.update(cx, |this, cx| { + this.set_signer(keys, session, cx); + })?; Ok(public_key) }) @@ -359,6 +382,7 @@ impl Backend { let keys = Keys::generate(); let credential = with_master_key(&uri_string, &keys); let write = cx.write_credentials(USER_KEYRING, "bunker", credential.as_bytes()); + let session = self.supersede_session(); cx.spawn(async move |this, cx| { let signer = NostrConnect::builder(connect_uri, keys) @@ -369,7 +393,9 @@ impl Backend { let public_key = signer.get_public_key_async().await?; write.await?; - this.update(cx, |this, cx| this.set_signer(signer, cx))?; + this.update(cx, |this, cx| { + this.set_signer(signer, session, cx); + })?; Ok(public_key) }) @@ -384,13 +410,15 @@ impl Backend { let name = name.trim().to_owned(); let password = password.to_owned(); - if name.is_empty() || name.len() > 255 { + if name.is_empty() || name.chars().count() > 255 { return Task::ready(Err(anyhow!("Name must be 1-255 characters"))); } if password.is_empty() { return Task::ready(Err(anyhow!("Passphrase must not be empty"))); } + let session = self.supersede_session(); + cx.spawn(async move |this, cx| { let job = cx.background_spawn(async move { let keys = Keys::generate(); @@ -409,6 +437,9 @@ impl Backend { write.await?; this.update(cx, |this, cx| { + if this.session != session { + return; + } this.signer.swap_inner(keys); this.current_user = Some(public_key); this.bootstrap_user(public_key, cx); @@ -449,11 +480,13 @@ impl Backend { .map(|url| RelayUrl::parse(url).expect("valid relay URL")) .collect(); - for builder in [ + let publishes = [ RelayList::new(relays).into_event_builder(), metadata, GitUserGraspList { grasp_servers }.into_event_builder(), - ] { + ] + .into_iter() + .map(|builder| { let client = this.client.clone(); let signer = this.signer.clone(); cx.background_spawn(async move { @@ -472,8 +505,21 @@ impl Backend { Ok::<(), anyhow::Error>(()) }) - .detach(); - } + }) + .collect::>(); + + cx.spawn(async move |this, cx| { + if let Err(error) = futures::future::try_join_all(publishes).await { + this.update(cx, |_this, cx| { + cx.emit(BackendEvent::error(format!( + "identity created, but publishing it failed: {error}" + ))); + })?; + } + + Ok::<(), anyhow::Error>(()) + }) + .detach(); })?; Ok(public_key) @@ -976,10 +1022,8 @@ impl Backend { }); let events = events.await?; - this.update(cx, |this, cx| { - this.retract_events(&events, cx); - }) - .ok(); + let deletions = this.update(cx, |this, cx| this.retract_events(&events, cx))?; + futures::future::try_join_all(deletions).await?; Ok(()) }) @@ -1061,6 +1105,9 @@ impl Backend { } pub fn sign_out(&mut self, cx: &mut Context) { + self.supersede_session(); + // Nothing may be signed with the identity the user just left. + self.signer.swap_inner(Keys::generate()); self.current_user = None; self.passphrase_required = false; @@ -1068,7 +1115,19 @@ impl Backend { inbox.reset(cx); }); - cx.delete_credentials(USER_KEYRING).detach_and_log_err(cx); + let delete = cx.delete_credentials(USER_KEYRING); + cx.spawn(async move |this, cx| { + if let Err(error) = delete.await { + this.update(cx, |_this, cx| { + cx.emit(BackendEvent::error(format!( + "failed to remove the stored credential: {error}" + ))); + })?; + } + + Ok::<(), Error>(()) + }) + .detach(); cx.emit(BackendEvent::SignerChanged); cx.emit(BackendEvent::SignerRequired); cx.notify(); @@ -1103,7 +1162,12 @@ impl Backend { }); } - fn set_signer(&mut self, new_signer: T, cx: &mut Context) + fn supersede_session(&mut self) -> u64 { + self.session += 1; + self.session + } + + fn set_signer(&mut self, new_signer: T, session: u64, cx: &mut Context) where T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static, ::Error: std::error::Error + Send + Sync + 'static, @@ -1114,6 +1178,9 @@ impl Backend { match new_signer.get_public_key_async().await { Ok(public_key) => { this.update(cx, |this, cx| { + if this.session != session { + return; + } this.signer.swap_inner(new_signer); this.current_user = Some(public_key); this.passphrase_required = false; @@ -1243,24 +1310,31 @@ impl Backend { } // Each target gets its own deletion event. - fn retract_events(&mut self, events: &[Event], cx: &mut Context) { - for event in events.iter().cloned() { - let client = self.client.clone(); - let signer = self.signer.clone(); + fn retract_events( + &mut self, + events: &[Event], + cx: &mut Context, + ) -> Vec>> { + events + .iter() + .cloned() + .map(|event| { + let client = self.client.clone(); + let signer = self.signer.clone(); - cx.background_spawn(async move { - let builder = EventDeletionRequest::new().id(event.id); - let deletion = builder.finalize_async(&signer).await?; - let output = client.send_event(&deletion).broadcast().await?; + cx.background_spawn(async move { + let builder = EventDeletionRequest::new().id(event.id); + let deletion = builder.finalize_async(&signer).await?; + let output = client.send_event(&deletion).broadcast().await?; - if output.success.is_empty() { - bail!("deletion event not accepted by any relay"); - } + if output.success.is_empty() { + bail!("deletion event not accepted by any relay"); + } - Ok::<(), Error>(()) + Ok::<(), Error>(()) + }) }) - .detach_and_log_err(cx); - } + .collect() } } @@ -1287,8 +1361,7 @@ fn build_announcement( } } -/// Announces a repository and pushes its state to grasp servers, -/// or retracts the announcement if the push fails. +/// Announces a repository and pushes its state to grasp, retracting the announcement on failure. async fn announce_and_push_or_retract( client: &Client, signer: &S, @@ -1355,6 +1428,10 @@ impl UpdateEvent { }; if seen.insert(event.id) { + // Bounded, so a long session does not keep every event id. + if seen.len() >= MAX_SEEN_EVENT_IDS { + seen.clear(); + } return Some(update); } } diff --git a/crates/signed_state/src/checkouts.rs b/crates/signed_state/src/checkouts.rs index b72892e..08f158f 100644 --- a/crates/signed_state/src/checkouts.rs +++ b/crates/signed_state/src/checkouts.rs @@ -366,21 +366,11 @@ impl CheckoutsStore { let (statuses, push_statuses) = CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, true); - Ok::<_, Error>((associations, statuses, push_statuses)) + (associations, statuses, push_statuses) }); cx.spawn(async move |this, cx| { - let (associations, statuses, push_statuses) = match work.await { - Ok(results) => results, - Err(_) => { - return this.update(cx, |this, cx| { - this.refresh.abort(); - if poll { - this.schedule_local_pass(cx); - } - }); - } - }; + let (associations, statuses, push_statuses) = work.await; let again = this.update(cx, |this, cx| { let associations_changed = this.by_repo != associations; @@ -412,7 +402,7 @@ impl CheckoutsStore { } })?; - Ok(()) + Ok::<(), Error>(()) }) .detach(); } @@ -480,15 +470,11 @@ impl CheckoutsStore { let push_requested: Vec = self.push_requested.iter().cloned().collect(); let work = cx.background_spawn(async move { - let (statuses, push_statuses) = - CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, false); - Ok::<_, Error>((statuses, push_statuses)) + CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, false) }); cx.spawn(async move |this, cx| { - let Ok((statuses, push_statuses)) = work.await else { - return Ok(()); - }; + let (statuses, push_statuses) = work.await; this.update(cx, |this, cx| { if this.refresh.running() || this.debounce_pending { diff --git a/crates/signed_state/src/inbox.rs b/crates/signed_state/src/inbox.rs index 0dadf49..4dd9f57 100644 --- a/crates/signed_state/src/inbox.rs +++ b/crates/signed_state/src/inbox.rs @@ -120,9 +120,7 @@ impl Inbox { Ok((items, unread_count)) } -} -impl Inbox { fn inbox_state_d_tag(me: PublicKey) -> String { format!("signed-inbox-state:{}", me.to_hex()) } @@ -147,8 +145,7 @@ impl Inbox { } } - // Signed with a random key: the state is local-only, authorship does not - // matter and no key material needs to be kept. + // Signed with a random key: the state is local-only, authorship does not matter. async fn save_state( client: &Client, me: PublicKey, diff --git a/crates/signed_state/src/lib.rs b/crates/signed_state/src/lib.rs index cd82d51..bf294e2 100644 --- a/crates/signed_state/src/lib.rs +++ b/crates/signed_state/src/lib.rs @@ -36,14 +36,57 @@ pub fn init( repos_root: impl Into, scan_paths: Vec, cx: &mut App, -) { +) -> anyhow::Result<()> { // rustls uses the `aws_lc_rs` provider by default. - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + if rustls::crypto::aws_lc_rs::default_provider() + .install_default() + .is_err() + { + log::debug!("a crypto provider is already installed"); + } - let backend = cx + let db_path = db_path.as_ref().to_path_buf(); + + let backend = match cx .foreground_executor() - .block_on(async move { NostrBackend::open(db_path.as_ref()).await }); - let backend = backend.expect("failed to initialize nostr backend"); + .block_on(NostrBackend::open(&db_path)) + { + Ok(backend) => backend, + Err(error) => { + // A damaged or locked database must not keep the app from starting. + log::error!( + "failed to open the nostr database {}: {error:#}", + db_path.display() + ); + + let fallback = std::env::temp_dir() + .join("signed") + .join(format!("nostr-fallback-{}", std::process::id())); + + let backend = std::fs::create_dir_all(&fallback) + .map_err(anyhow::Error::from) + .and_then(|()| { + cx.foreground_executor() + .block_on(NostrBackend::open(&fallback)) + }); + + if backend.is_ok() { + cx.show_system_notification(gpui::SystemNotification { + tag: "signed-nostr-db".into(), + title: "Nostr cache unavailable".into(), + body: format!( + "{} could not be opened; this session uses a temporary cache", + db_path.display() + ) + .into(), + actions: Vec::new(), + }); + } + + backend? + } + }; + let (client, signer) = (backend.client, backend.signer); Mirrors::install(repos_root); @@ -53,4 +96,6 @@ pub fn init( LocalReposStore::set_global(cx.new(|cx| LocalReposStore::new(scan_paths, cx)), cx); CheckoutsStore::set_global(cx.new(CheckoutsStore::new), cx); SyncStatusStore::set_global(cx.new(SyncStatusStore::new), cx); + + Ok(()) } diff --git a/crates/signed_state/src/local_repos.rs b/crates/signed_state/src/local_repos.rs index 8d6ffa4..9ea0db3 100644 --- a/crates/signed_state/src/local_repos.rs +++ b/crates/signed_state/src/local_repos.rs @@ -100,33 +100,7 @@ impl LocalReposStore { task.detach(); } -} -pub fn local_repo_addr(repo: &LocalRepo) -> Option { - let binding = repo.nip34.as_ref()?; - let owner = binding.owner?; - let identifier = binding.identifier.as_deref()?; - - Some(RepoAddr::new(owner, identifier)) -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ResolvedLocalRepo { - pub path: PathBuf, - pub nip34: Option, - pub announcement: Option, -} - -impl ResolvedLocalRepo { - pub fn name(&self) -> SharedString { - self.path - .file_name() - .map(|name| SharedString::from(name.to_string_lossy().into_owned())) - .unwrap_or_else(|| SharedString::from("Untitled")) - } -} - -impl LocalReposStore { pub fn resolve( repos: &[LocalRepo], known: &[Announcement], @@ -164,66 +138,26 @@ impl LocalReposStore { } } -#[cfg(test)] -mod tests { - use nostr::prelude::*; - use signed_git::{GraspSignals, Nip34Kind}; +#[derive(Debug, Clone, PartialEq)] +pub struct ResolvedLocalRepo { + pub path: PathBuf, + pub nip34: Option, + pub announcement: Option, +} - use super::*; - - const KEY: &str = "0000000000000000000000000000000000000000000000000000000000000001"; - const OTHER_KEY: &str = "0000000000000000000000000000000000000000000000000000000000000002"; - - fn announcement(secret: &str, id: &str) -> Announcement { - let keys = Keys::new(SecretKey::from_hex(secret).expect("secret")); - let tag = Tag::parse(vec!["d", id]).expect("tag"); - let event = EventBuilder::new(Kind::GitRepoAnnouncement) - .tags(vec![tag]) - .finalize(&keys) - .expect("signed"); - - Announcement::from_event(&event).expect("parsed") - } - - fn owner(secret: &str) -> PublicKey { - Keys::new(SecretKey::from_hex(secret).expect("secret")).public_key() - } - - fn bound(secret: &str, id: &str) -> LocalRepo { - let binding = Nip34Binding { - kind: Nip34Kind::Initialized, - signals: GraspSignals { - nip34_json: true, - ..Default::default() - }, - owner: Some(owner(secret)), - identifier: Some(id.to_owned()), - grasp_urls: Vec::new(), - }; - - LocalRepo { - path: PathBuf::from(id), - nip34: Some(binding), - } - } - - #[test] - fn the_users_own_announcement_is_dropped() { - let own = announcement(KEY, "mine"); - let repo = bound(KEY, "mine"); - - let own = std::slice::from_ref(&own); - assert!(LocalReposStore::resolve(&[repo], own, own).is_empty()); - } - - #[test] - fn another_owners_announcement_is_linked_and_kept() { - let known = announcement(OTHER_KEY, "theirs"); - let repo = bound(OTHER_KEY, "theirs"); - - let resolved = LocalReposStore::resolve(&[repo], std::slice::from_ref(&known), &[]); - - assert_eq!(resolved.len(), 1); - assert_eq!(resolved[0].announcement.as_ref(), Some(&known)); +impl ResolvedLocalRepo { + pub fn name(&self) -> SharedString { + self.path + .file_name() + .map(|name| SharedString::from(name.to_string_lossy().into_owned())) + .unwrap_or_else(|| SharedString::from("Untitled")) } } + +pub fn local_repo_addr(repo: &LocalRepo) -> Option { + let binding = repo.nip34.as_ref()?; + let owner = binding.owner?; + let identifier = binding.identifier.as_deref()?; + + Some(RepoAddr::new(owner, identifier)) +} diff --git a/crates/signed_state/src/repo.rs b/crates/signed_state/src/repo.rs index 837d254..dad0ecd 100644 --- a/crates/signed_state/src/repo.rs +++ b/crates/signed_state/src/repo.rs @@ -55,8 +55,10 @@ pub struct RepoStore { // Covers NIP-22 comments and statuses without an `a` tag. root_fetches: HashSet, synced_maintainers: HashSet, - // In-flight tasks, cancelled when the store drops. + // Fire-and-forget publishes, reaped when the next one is queued. tasks: Vec>>, + // The latest refresh; assigning it cancels the previous one. + refresh_task: Option>>, _subscription: Option, } @@ -108,6 +110,7 @@ impl RepoStore { root_fetches: HashSet::new(), synced_maintainers: HashSet::new(), tasks: Vec::new(), + refresh_task: None, _subscription: Some(subscription), } } @@ -139,6 +142,7 @@ impl RepoStore { root_fetches: HashSet::new(), synced_maintainers: HashSet::new(), tasks: Vec::new(), + refresh_task: None, _subscription: None, } } @@ -580,7 +584,7 @@ impl RepoStore { Ok(()) }); - self.tasks.push(task); + self.refresh_task = Some(task); } pub fn status_of(&self, root: &Event) -> RepoStatus { @@ -652,7 +656,7 @@ impl RepoStore { ); } - #[allow(clippy::too_many_arguments)] + #[expect(clippy::too_many_arguments, reason = "mirrors the PR event")] pub fn open_pull_request( &mut self, subject: Option, @@ -708,12 +712,13 @@ impl RepoStore { cx.notify(); return Task::ready(Err(Error::msg(message))); }; - let author_npub = user.to_bech32().unwrap(); + let author_npub = user.to_bech32().unwrap_or_else(|error| match error {}); let owner = addr.public_key(); let euc = self.announcement.as_ref().and_then(|a| a.euc.clone()); let repo_id = addr.identifier().to_owned(); - let base_npub = owner.to_bech32().unwrap(); + let base_npub = owner.to_bech32().unwrap_or_else(|error| match error {}); + let push_relays = self .announcement .as_ref() @@ -721,6 +726,7 @@ impl RepoStore { .unwrap_or_default(); // GRASP-06 hosting falls back to the settings defaults. + // // That happens when the author has no published grasp list. let defaults: Vec = { let settings = settings::SettingsStore::global(cx).read(cx).settings(); @@ -752,17 +758,18 @@ impl RepoStore { { Ok(event) => event, Err(e) => { - return this.update(cx, |this, cx| { + this.update(cx, |this, cx| { this.last_error = Some(e.to_string()); cx.notify(); - }); + })?; + return Err(e); } }; - // GRASP-06 pushes the tip to the author's own grasp servers at - // `/prs//.git`; contributing to another - // project never depends on that project's servers. Resolve the - // servers from the author's latest kind-10317 grasp list. + // GRASP-06 pushes the tip to the author's own grasp servers at `/prs//.git`. + // Contributing to another project never depends on that project's servers. + // + // Resolve the servers from the author's latest grasp list. let author_servers = { let query_client = client.clone(); let published = cx @@ -790,6 +797,7 @@ impl RepoStore { } targets }; + let base_targets: Vec<(String, String)> = { let mut targets = Vec::new(); for relay in &push_relays { @@ -909,10 +917,11 @@ impl RepoStore { let pr_event = match publish_result { Ok(event) => event, Err(e) => { - return this.update(cx, |this, cx| { + this.update(cx, |this, cx| { this.last_error = Some(e.to_string()); cx.notify(); - }); + })?; + return Err(e); } }; @@ -926,7 +935,7 @@ impl RepoStore { }) } - #[allow(clippy::too_many_arguments)] + #[expect(clippy::too_many_arguments, reason = "mirrors the PR event")] pub fn open_pull_request_from_refs( &mut self, repo_path: PathBuf, @@ -939,8 +948,7 @@ impl RepoStore { cx: &mut Context, ) -> Task> { cx.spawn(async move |this, cx| { - // Regenerate at submit time so the published patch covers the - // current tip of the compare branch. + // Regenerate at submit time so the published patch covers the current tip of the compare branch. let patch = cx .background_spawn({ let repo_path = repo_path.clone(); @@ -958,8 +966,9 @@ impl RepoStore { Err(error) => bail!("Failed to generate the patch: {error}"), }; + let (done, finished) = flume::bounded::>(1); this.update(cx, |this, cx| { - let task = this.open_pull_request( + let publish = this.open_pull_request( subject, description, branch_name, @@ -969,8 +978,20 @@ impl RepoStore { Some(repo_path), cx, ); - this.tasks.push(task); - }) + + // The store owns the publish so it outlives the panel that requested it. + this.tasks.push(cx.spawn(async move |_this, _cx| { + if done.send(publish.await).is_err() { + log::debug!("pull request publish finished after its panel closed"); + } + Ok::<(), Error>(()) + })); + })?; + + finished + .recv_async() + .await + .map_err(|_| anyhow::anyhow!("the pull request publish was dropped"))? }) } @@ -1104,6 +1125,7 @@ impl RepoStore { Ok(()) }); + self.tasks.push(task); } @@ -1238,12 +1260,15 @@ impl RepoStore { cx.notify(); cx.spawn(async move |this, cx| { + // Cancellation releases the busy flag too, not only completion. + let guard = cx.on_drop(&this, |this, cx| { + this.pushing = false; + this.push_steps.clear(); + cx.notify(); + }); let result = push.await; this.update(cx, |this, cx| { - this.pushing = false; - this.push_steps.clear(); - match &result { Ok(outcome) => { this.last_error = None; @@ -1273,6 +1298,7 @@ impl RepoStore { cx.notify(); })?; + guard.abort(); result.map(|_| ()) }) } @@ -1331,11 +1357,14 @@ impl RepoStore { }; cx.spawn(async move |this, cx| { + // Cancellation releases the busy flag too, not only completion. + let guard = cx.on_drop(&this, |this, cx| { + this.cloning = false; + cx.notify(); + }); let result = clone.await; this.update(cx, |this, cx| { - this.cloning = false; - match &result { Ok(()) => { let checkouts = CheckoutsStore::global(cx); @@ -1351,6 +1380,8 @@ impl RepoStore { cx.notify(); })?; + guard.abort(); + result }) } @@ -1410,6 +1441,7 @@ impl RepoStore { Ok(()) }); + self.tasks.push(task); } } @@ -1453,7 +1485,7 @@ fn resolve_statuses( } /// Publish a patch series as a sequence of `git/patch` events. -#[allow(clippy::too_many_arguments)] +#[expect(clippy::too_many_arguments, reason = "independent inputs")] async fn publish_patch_series( client: &Client, signer: &S, diff --git a/crates/signed_state/src/repos.rs b/crates/signed_state/src/repos.rs index 6b26b0a..fd45735 100644 --- a/crates/signed_state/src/repos.rs +++ b/crates/signed_state/src/repos.rs @@ -223,8 +223,7 @@ impl RepoListStore { } } - // Unbounded, unlike the windowed activity query above, so totals - // are exact. + // Unbounded, unlike the windowed activity query above, so totals are exact. let mut counts: HashMap = HashMap::new(); let count_filter = Filter::new().kinds([Kind::GitIssue, Kind::GitPullRequest, Kind::GitPatch]); @@ -255,25 +254,33 @@ impl RepoListStore { cx.spawn(async move |this, cx| { let (announcements, last_activity, counts) = match work.await { Ok(results) => results, - Err(_) => { - return this.update(cx, |this, _cx| { - this.refresh.abort(); - }); + Err(error) => { + log::warn!("failed to refresh the repository list: {error}"); + return this.update(cx, |this, _cx| this.refresh.abort()); } }; let again = this.update(cx, |this, cx| { + let changed = *this.announcements != announcements + || *this.last_activity != last_activity + || *this.counts != counts; + this.announcements = Arc::new(announcements); this.last_activity = Arc::new(last_activity); this.counts = Arc::new(counts); this.sync_own_repo_states(cx); - cx.notify(); + + if changed { + cx.notify(); + } this.refresh.finish() })?; if again { - this.update(cx, |this, cx| this.refresh(cx))?; + this.update(cx, |this, cx| { + this.refresh(cx); + })?; } Ok(()) diff --git a/crates/signed_state/src/state.rs b/crates/signed_state/src/state.rs index 18bb98e..dcd1a7e 100644 --- a/crates/signed_state/src/state.rs +++ b/crates/signed_state/src/state.rs @@ -282,7 +282,9 @@ impl SyncState { if !missing.is_empty() { let (mode, policy) = (self.mode.clone(), self.policy); - *self = Self::from_repo(&snapshot_path)?; + *self = cx + .background_spawn(async move { Self::from_repo(&snapshot_path) }) + .await?; self.mode = mode; self.policy = policy; } @@ -295,9 +297,7 @@ impl SyncState { Self::build(repo_id, &self.refs, self.head.as_deref()) } - /// Push the state event and objects to the grasp servers. - /// - /// Calling `on_step` for each step. + /// Push the state event and objects to the grasp servers, calling `on_step` for each step. pub async fn push_to_grasps

( &self, client: &Client, @@ -446,9 +446,7 @@ impl SyncState { Ok(outcome) } - /// Announce the repository and push the state and objects to the grasp servers. - /// - /// Both events are signed by the caller, so a failure at the call site can retract the announcement by id. + /// Announces the repository and pushes state and objects; the caller signs, so it can retract. pub async fn announce_and_push

( &self, client: &Client, diff --git a/crates/signed_state/src/sync_status.rs b/crates/signed_state/src/sync_status.rs index 0ccd198..84e42ac 100644 --- a/crates/signed_state/src/sync_status.rs +++ b/crates/signed_state/src/sync_status.rs @@ -40,7 +40,9 @@ pub struct SyncStatusStore { pass_pending: bool, poll_pending: bool, sender: Sender<()>, - tasks: Vec>>, + _wake_task: Task>, + pass_task: Option>>, + poll_task: Option>>, _subscriptions: Vec, } @@ -96,7 +98,9 @@ impl SyncStatusStore { in_flight: false, pass_pending: false, poll_pending: false, - tasks: vec![task], + _wake_task: task, + pass_task: None, + poll_task: None, _subscriptions: subscriptions, } } @@ -204,7 +208,7 @@ impl SyncStatusStore { Ok::<_, Error>(updates) }); - self.tasks.push(cx.spawn(async move |this, cx| { + self.pass_task = Some(cx.spawn(async move |this, cx| { // Reset the slot even on failure, or every later pass folds forever. let updates = match work.await { Ok(updates) => updates, @@ -240,7 +244,7 @@ impl SyncStatusStore { } self.poll_pending = true; - self.tasks.push(cx.spawn(async move |this, cx| { + self.poll_task = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(SYNC_POLL).await; this.update(cx, |this, cx| { @@ -319,9 +323,7 @@ impl SyncStatusDirectory { .unwrap_or(0) } - /// Commit ids missing on Nostr, mapped to the checkout that holds them. - /// - /// When `checkout` matches a tracked checkout, only that checkout contributes. + /// Commit ids missing on Nostr, mapped to their checkout; restricted to `checkout` if tracked. pub fn ahead_commits_of( &self, addr: &RepoAddr, @@ -358,6 +360,10 @@ impl SyncStatusDirectory { } fn queue(&self, addr: &RepoAddr, cx: &App) { + if self.statuses.contains_key(addr) { + return; + } + if self.with_pending(|pending| pending.insert(addr.clone())) { let store = SyncStatusStore::global(cx); store.read(cx).probe([addr.clone()]); diff --git a/crates/ui/src/components/combobox.rs b/crates/ui/src/components/combobox.rs index 5fb457e..4a16a39 100644 --- a/crates/ui/src/components/combobox.rs +++ b/crates/ui/src/components/combobox.rs @@ -272,6 +272,24 @@ where } } + /// Replaces the value without reporting it through `on_change`. + pub fn set_selected_silent( + &mut self, + value: Option, + window: &mut Window, + cx: &mut Context, + ) { + if self.selected == value { + return; + } + self.selected = value; + let label = self.selected_label().unwrap_or_default(); + self.query + .update(cx, |query, cx| query.set_value_silent(label, window, cx)); + self.refilter(""); + cx.notify(); + } + /// Replaces the choice list and re-runs the current filter. pub fn set_options(&mut self, options: Vec>, cx: &mut Context) { self.options = options; diff --git a/crates/utils/src/repo_url.rs b/crates/utils/src/repo_url.rs index e038b49..3858f55 100644 --- a/crates/utils/src/repo_url.rs +++ b/crates/utils/src/repo_url.rs @@ -1,7 +1,6 @@ use nostr::prelude::*; -/// Compare git URLs ignoring scheme, trailing `.git` and path slashes, -/// so a grasp announce URL matches its https origin. +/// Compares git URLs ignoring scheme, trailing `.git` and slashes, so grasp matches https. pub fn same_repo_url(a: &str, b: &str) -> bool { match (url_identity(a), url_identity(b)) { (Some(a), Some(b)) => a == b, diff --git a/crates/utils/src/time.rs b/crates/utils/src/time.rs index 02ef807..48d3e29 100644 --- a/crates/utils/src/time.rs +++ b/crates/utils/src/time.rs @@ -4,7 +4,7 @@ pub fn sort_newest_first(events: &mut [Event]) { events.sort_by(|a, b| { b.created_at .cmp(&a.created_at) - .then_with(|| b.id.to_hex().cmp(&a.id.to_hex())) + .then_with(|| b.id.cmp(&a.id)) }); } diff --git a/desktop/src/main.rs b/desktop/src/main.rs index d8bd5cf..b295f26 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -50,7 +50,7 @@ fn main() { cx.on_action(|_: &Quit, cx| cx.quit()); cx.set_app_identity("info.reya.signed", "Signed"); - let store = cx.new(|cx| SettingsStore::new(paths::settings_file(), cx)); + let store = cx.new(|_| SettingsStore::new(paths::settings_file())); SettingsStore::set_global(store.clone(), cx); let settings = store.read(cx).settings().clone(); @@ -64,12 +64,16 @@ fn main() { tracing::warn!("failed to create repos dir: {error}"); } - signed_state::init( + if let Err(error) = signed_state::init( paths::nostr_dir(), - paths::repos_dir().clone(), + paths::repos_dir().to_path_buf(), settings.local_repos.scan_paths.clone(), cx, - ); + ) { + tracing::error!("failed to initialize application state: {error:#}"); + cx.quit(); + return; + } metadata::init(cx); @@ -106,6 +110,8 @@ fn main() { signed_app::root(window, cx) }) { tracing::error!("failed to open window: {error}"); + cx.quit(); + return; } cx.activate(true); });