fix: remove panics and unblock flows
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

This commit is contained in:
2026-11-25 03:20:40 +07:00
parent 0fd8ea12fb
commit 3f64b36ff4
52 changed files with 753 additions and 567 deletions
+3
View File
@@ -28,5 +28,8 @@ jobs:
- name: Build - name: Build
run: cargo build --verbose run: cargo build --verbose
- name: Lint
run: cargo clippy --workspace --all-targets -- -D warnings
- name: Run tests - name: Run tests
run: cargo test --verbose run: cargo test --verbose
+24
View File
@@ -1,5 +1,29 @@
# Changelog # 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 ## v0.2.0 - 2026/10/21
### Added ### Added
Generated
+1
View File
@@ -5626,6 +5626,7 @@ name = "paths"
version = "0.2.0" version = "0.2.0"
dependencies = [ dependencies = [
"dirs", "dirs",
"log",
] ]
[[package]] [[package]]
+1 -1
View File
@@ -1,7 +1,7 @@
mod profile; mod profile;
use gpui::{App, AppContext}; use gpui::{App, AppContext};
pub use profile::{Profile, ProfileDirectory, ProfileEvent, ProfileStore}; pub use profile::{Profile, ProfileDirectory, ProfileStore};
/// Initialize the global profile store. /// Initialize the global profile store.
pub fn init(cx: &mut App) { pub fn init(cx: &mut App) {
+7
View File
@@ -320,6 +320,7 @@ impl ProfileDirectory {
Ok::<_, anyhow::Error>(Profile::latest_profiles(events)) Ok::<_, anyhow::Error>(Profile::latest_profiles(events))
}); });
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
let loaded = work.await; let loaded = work.await;
@@ -335,6 +336,12 @@ impl ProfileDirectory {
} }
Err(e) => { Err(e) => {
log::warn!("failed to load profiles from the database: {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 keys
} }
}; };
+1
View File
@@ -6,6 +6,7 @@ publish.workspace = true
[dependencies] [dependencies]
dirs = "6" dirs = "6"
log.workspace = true
[lints] [lints]
workspace = true workspace = true
+57 -67
View File
@@ -1,67 +1,30 @@
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::sync::OnceLock; use std::sync::LazyLock;
/// The application name. /// The application name, which derives the platform-specific directory paths.
///
/// It derives the platform-specific data, config and cache directory paths.
pub const APP_NAME: &str = "Signed"; pub const APP_NAME: &str = "Signed";
/// Lowercased form of [`APP_NAME`]. /// Lowercased [`APP_NAME`], used in XDG paths and the macOS `~/.config` fallback.
///
/// Used in XDG-style paths on Linux and FreeBSD, and the macOS `~/.config` fallback.
pub const APP_NAME_LOWERCASE: &str = "signed"; pub const APP_NAME_LOWERCASE: &str = "signed";
/// The resolved data directory. /// The resolved config directory, under the platform's standard config location.
/// On macOS, this is `~/Library/Application Support/Signed`. static CONFIG_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
/// On Linux/FreeBSD, this is `$XDG_DATA_HOME/signed`.
/// On Windows, this is `%LOCALAPPDATA%\Signed`.
static CURRENT_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();
/// 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<PathBuf> = OnceLock::new();
fn home_dir() -> PathBuf {
dirs::home_dir().expect("failed to determine home directory")
}
/// Returns the current user's Desktop folder.
///
/// Falls back to the home directory or an empty path when it cannot be determined.
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.
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") { if cfg!(target_os = "windows") {
dirs::config_dir() resolve_dir(dirs::config_dir(), "RoamingAppData").join(APP_NAME)
.expect("failed to determine RoamingAppData directory")
.join(APP_NAME)
} else if cfg!(any(target_os = "linux", target_os = "freebsd")) { } else if cfg!(any(target_os = "linux", target_os = "freebsd")) {
if let Ok(flatpak_xdg_config) = std::env::var("FLATPAK_XDG_CONFIG_HOME") { if let Ok(flatpak_xdg_config) = std::env::var("FLATPAK_XDG_CONFIG_HOME") {
flatpak_xdg_config.into() flatpak_xdg_config.into()
} else { } else {
dirs::config_dir().expect("failed to determine XDG_CONFIG_HOME directory") resolve_dir(dirs::config_dir(), "XDG_CONFIG_HOME")
} }
.join(APP_NAME_LOWERCASE) .join(APP_NAME_LOWERCASE)
} else { } else {
home_dir().join(".config").join(APP_NAME_LOWERCASE) home_dir().join(".config").join(APP_NAME_LOWERCASE)
} }
}) });
}
fn data_dir() -> &'static PathBuf { /// The resolved data directory, under the platform's standard data location.
CURRENT_DATA_DIR.get_or_init(|| { static CURRENT_DATA_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
if cfg!(target_os = "macos") { if cfg!(target_os = "macos") {
home_dir() home_dir()
.join("Library/Application Support") .join("Library/Application Support")
@@ -70,36 +33,63 @@ fn data_dir() -> &'static PathBuf {
if let Ok(flatpak_xdg_data) = std::env::var("FLATPAK_XDG_DATA_HOME") { if let Ok(flatpak_xdg_data) = std::env::var("FLATPAK_XDG_DATA_HOME") {
flatpak_xdg_data.into() flatpak_xdg_data.into()
} else { } else {
dirs::data_local_dir().expect("failed to determine XDG_DATA_HOME directory") resolve_dir(dirs::data_local_dir(), "XDG_DATA_HOME")
} }
.join(APP_NAME_LOWERCASE) .join(APP_NAME_LOWERCASE)
} else if cfg!(target_os = "windows") { } else if cfg!(target_os = "windows") {
dirs::data_local_dir() resolve_dir(dirs::data_local_dir(), "LocalAppData").join(APP_NAME)
.expect("failed to determine LocalAppData directory")
.join(APP_NAME)
} else { } else {
config_dir().clone() config_dir().to_path_buf()
} }
});
static NOSTR_DIR: LazyLock<PathBuf> = LazyLock::new(|| data_dir().join("nostr"));
static REPOS_DIR: LazyLock<PathBuf> =
LazyLock::new(|| std::env::temp_dir().join(APP_NAME_LOWERCASE).join("repos"));
static SETTINGS_FILE: LazyLock<PathBuf> = 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<PathBuf>, 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()
}) })
} }
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 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 Path {
CONFIG_DIR.as_path()
}
fn data_dir() -> &'static Path {
CURRENT_DATA_DIR.as_path()
}
/// Returns the path to the nostr database directory, LMDB. /// Returns the path to the nostr database directory, LMDB.
pub fn nostr_dir() -> &'static PathBuf { pub fn nostr_dir() -> &'static Path {
static NOSTR_DIR: OnceLock<PathBuf> = OnceLock::new(); NOSTR_DIR.as_path()
NOSTR_DIR.get_or_init(|| data_dir().join("nostr"))
} }
/// Returns the path to the local git clone cache, the grasp mirrors. /// The grasp mirror cache, disposable and re-cloned on demand, so it lives in the temp directory.
/// pub fn repos_dir() -> &'static Path {
/// The mirrors are disposable and re-cloned from their grasp server on REPOS_DIR.as_path()
/// 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<PathBuf> = OnceLock::new();
REPOS_DIR.get_or_init(|| std::env::temp_dir().join(APP_NAME_LOWERCASE).join("repos"))
} }
pub fn settings_file() -> &'static PathBuf { pub fn settings_file() -> &'static Path {
static SETTINGS_FILE: OnceLock<PathBuf> = OnceLock::new(); SETTINGS_FILE.as_path()
SETTINGS_FILE.get_or_init(|| config_dir().join("settings.json"))
} }
+2 -9
View File
@@ -49,11 +49,7 @@ impl Default for GraspServersSettings {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)] #[serde(default)]
pub struct LocalReposSettings { pub struct LocalReposSettings {
/// The directories scanned for local git repositories, /// Directories scanned for local git repositories. `~/Desktop` and `~/Documents` by default.
/// Defaults:
///
/// - `~/Desktop`
/// - `~/Documents`
pub scan_paths: Vec<PathBuf>, pub scan_paths: Vec<PathBuf>,
} }
@@ -65,10 +61,7 @@ impl Default for LocalReposSettings {
} }
} }
/// A remembered association between a local checkout folder and an announced repository, /// A checkout folder paired with its announced repository, so the New PR panel can prefill it.
/// 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.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)] #[serde(default)]
pub struct CheckoutRecord { pub struct CheckoutRecord {
+33 -77
View File
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::Result; use anyhow::{Result, bail};
use gpui::{App, Context, Entity, Global}; use gpui::{App, Context, Entity, Global};
use crate::Settings; use crate::Settings;
@@ -9,13 +9,14 @@ struct GlobalSettingsStore(Entity<SettingsStore>);
impl Global for GlobalSettingsStore {} impl Global for GlobalSettingsStore {}
/// The application settings, /// The application settings, loaded from disk and saved on change; installed as a global.
/// 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.
pub struct SettingsStore { pub struct SettingsStore {
path: PathBuf, path: PathBuf,
settings: Settings, settings: Settings,
/// Why the on-disk file was not loaded; such a file is never overwritten.
unreadable: Option<String>,
/// Why the settings are currently not persisted.
pub error: Option<String>,
} }
impl SettingsStore { impl SettingsStore {
@@ -34,15 +35,14 @@ impl SettingsStore {
cx.set_global(GlobalSettingsStore(entity)); cx.set_global(GlobalSettingsStore(entity));
} }
/// Load the settings from `path`, /// Loads the settings from `path`, with defaults for a missing or unreadable file.
/// falls back to defaults when the file is missing or unreadable. pub fn new(path: impl AsRef<Path>) -> Self {
/// let (settings, error) = Self::load(path.as_ref());
/// Missing keys merge with the defaults,
/// older settings files keep working as new settings are added.
pub fn new(path: impl AsRef<Path>, _cx: &mut Context<Self>) -> Self {
Self { Self {
path: path.as_ref().to_path_buf(), 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. /// Mutate the settings, persist them to disk, and notify observers.
pub fn edit(&mut self, f: impl FnOnce(&mut Settings), cx: &mut Context<Self>) { pub fn edit(&mut self, f: impl FnOnce(&mut Settings), cx: &mut Context<Self>) {
f(&mut self.settings); f(&mut self.settings);
if let Err(err) = self.save() { match self.save() {
Ok(()) => self.error = None,
Err(err) => {
log::error!( log::error!(
"failed to save settings to {}: {err:#}", "failed to save settings to {}: {err:#}",
self.path.display() self.path.display()
); );
self.error = Some(format!("{err:#}"));
}
} }
cx.notify(); cx.notify();
} }
/// Read the settings file, merging any missing fields with the defaults. /// Read the settings file, merging any missing fields with the defaults.
fn load(path: &Path) -> Settings { fn load(path: &Path) -> (Settings, Option<String>) {
match std::fs::read_to_string(path) { match std::fs::read_to_string(path) {
Ok(contents) => match serde_json::from_str::<Settings>(&contents) { Ok(contents) => match serde_json::from_str::<Settings>(&contents) {
Ok(settings) => settings, Ok(settings) => (settings, None),
Err(err) => { Err(err) => {
log::error!( let error = format!("failed to parse settings file {}: {err}", path.display());
"failed to parse settings file {}: {err}; using defaults", log::error!("{error}; using defaults");
path.display() (Settings::default(), Some(error))
);
Settings::default()
} }
}, },
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) => { Err(err) => {
log::error!( let error = format!("failed to read settings file {}: {err}", path.display());
"failed to read settings file {}: {err}; using defaults", log::error!("{error}; using defaults");
path.display() (Settings::default(), Some(error))
);
Settings::default()
} }
} }
} }
/// Write the settings to disk, replacing the file atomically. /// Write the settings to disk, replacing the file atomically.
fn save(&self) -> Result<()> { 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() { if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?; std::fs::create_dir_all(parent)?;
} }
let json = serde_json::to_string_pretty(&self.settings)?; let json = serde_json::to_string_pretty(&self.settings)?;
let tmp = self.path.with_extension("json.tmp"); let tmp = self.path.with_extension("json.tmp");
std::fs::write(&tmp, json)?; std::fs::write(&tmp, json)?;
// `rename` cannot replace an existing file on Windows. // `rename` cannot replace an existing file on Windows.
if cfg!(target_os = "windows") && self.path.exists() { if cfg!(target_os = "windows") && self.path.exists() {
std::fs::remove_file(&self.path)?; std::fs::remove_file(&self.path)?;
} }
std::fs::rename(&tmp, &self.path)?; std::fs::rename(&tmp, &self.path)?;
Ok(()) 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);
}
}
+1 -3
View File
@@ -81,12 +81,10 @@ impl AppRoot {
Self::reset_to_explore(&app, window, cx); Self::reset_to_explore(&app, window, cx);
}); });
let appearance = settings.read(cx).settings().appearance;
Self { Self {
panels, panels,
titlebar, titlebar,
appearance, appearance: settings.read(cx).settings().appearance,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
} }
+5 -1
View File
@@ -108,7 +108,7 @@ impl ImportDialog {
} }
impl Render for ImportDialog { impl Render for ImportDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let state = self.state.clone(); let state = self.state.clone();
let secret_input = self.secret_input.clone(); let secret_input = self.secret_input.clone();
@@ -122,8 +122,12 @@ impl Render for ImportDialog {
let action_repass = repass_input.clone(); let action_repass = repass_input.clone();
let action_close = self.handle.clone(); let action_close = self.handle.clone();
let busy = state.read(cx).progress.busy;
Dialog::new("import-dialog") Dialog::new("import-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
.close_on_escape(!busy)
.close_on_backdrop(!busy)
.min_width(px(520.)) .min_width(px(520.))
.title("Import identity") .title("Import identity")
.content(move |_window, cx| { .content(move |_window, cx| {
@@ -72,9 +72,12 @@ impl Render for OnboardingDialog {
let state = self.state.clone(); let state = self.state.clone();
let action_state = state.clone(); let action_state = state.clone();
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
let busy = state.read(cx).busy;
Dialog::new("onboarding-dialog") Dialog::new("onboarding-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
.close_on_escape(!busy)
.close_on_backdrop(!busy)
.min_width(px(520.)) .min_width(px(520.))
.title("Create identity") .title("Create identity")
.content(move |_window, cx| { .content(move |_window, cx| {
+1 -1
View File
@@ -45,7 +45,7 @@ pub fn empty_section_row(cx: &App) -> AnyElement {
.into_any_element() .into_any_element()
} }
#[allow(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments, reason = "one per column")]
pub fn thread( pub fn thread(
prefix: &'static str, prefix: &'static str,
ix: usize, ix: usize,
+1 -1
View File
@@ -1,7 +1,7 @@
mod app; mod app;
mod explore; mod explore;
mod identity; mod identity;
#[allow(dead_code)] // temporarily unlinked while the shell migrates #[expect(dead_code, reason = "unlinked while the shell migrates")]
mod inbox; mod inbox;
mod issues; mod issues;
mod pull_requests; mod pull_requests;
+8 -2
View File
@@ -353,7 +353,10 @@ impl Render for PullRequestsView {
.title("Pull request warning") .title("Pull request warning")
.message(warning) .message(warning)
.on_dismiss(move |cx| { .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") .title("Pull request error")
.message(error) .message(error)
.on_dismiss(move |cx| { .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();
});
}), }),
) )
}) })
+9 -4
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, 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, UniformListScrollHandle, WeakEntity, Window, div, px,
}; };
use nostr::prelude::Url; use nostr::prelude::Url;
@@ -56,7 +56,6 @@ pub struct NewPullRequestView {
scroll_handle: UniformListScrollHandle, scroll_handle: UniformListScrollHandle,
pub(super) tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>, pub(super) tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
source_open: bool, source_open: bool,
_subscriptions: Vec<Subscription>,
} }
impl NewPullRequestView { impl NewPullRequestView {
@@ -159,7 +158,6 @@ impl NewPullRequestView {
scroll_handle: UniformListScrollHandle::new(), scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(), tasks: Vec::new(),
source_open: false, source_open: false,
_subscriptions: Vec::new(),
} }
} }
@@ -511,7 +509,9 @@ impl NewPullRequestView {
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
self.compare_generation = self.compare_generation.wrapping_add(1);
self.fork = None; self.fork = None;
let Some((branches, current)) = info else { let Some((branches, current)) = info else {
self.error = Some("The chosen folder is not a git repository".into()); self.error = Some("The chosen folder is not a git repository".into());
self.repo_path = None; self.repo_path = None;
@@ -522,6 +522,7 @@ impl NewPullRequestView {
cx.notify(); cx.notify();
return; return;
}; };
if branches.is_empty() { if branches.is_empty() {
self.error = Some("The repository has no branches yet".into()); self.error = Some("The repository has no branches yet".into());
self.repo_path = None; self.repo_path = None;
@@ -682,6 +683,8 @@ impl NewPullRequestView {
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
self.loading = false; self.loading = false;
self.compare_generation = self.compare_generation.wrapping_add(1);
let (base_branches, compare_branches) = match result { let (base_branches, compare_branches) = match result {
Ok(branches) => branches, Ok(branches) => branches,
Err(error) => { Err(error) => {
@@ -690,11 +693,13 @@ impl NewPullRequestView {
return; return;
} }
}; };
if compare_branches.is_empty() { if compare_branches.is_empty() {
self.error = Some("The fork has no branches to compare".into()); self.error = Some("The fork has no branches to compare".into());
cx.notify(); cx.notify();
return; return;
} }
if base_branches.is_empty() { if base_branches.is_empty() {
self.error = Some("Could not list the target repository's branches.".into()); self.error = Some("Could not list the target repository's branches.".into());
cx.notify(); cx.notify();
@@ -733,7 +738,7 @@ impl NewPullRequestView {
self.loading = true; self.loading = true;
self.error = None; self.error = None;
self.compare_generation += 1; self.compare_generation = self.compare_generation.wrapping_add(1);
let generation = self.compare_generation; let generation = self.compare_generation;
cx.notify(); cx.notify();
+9 -11
View File
@@ -728,22 +728,20 @@ impl CommitDiffView {
Err(_) => return Ok(()), Err(_) => return Ok(()),
}; };
let patch = cx let saved = cx
.background_spawn(async move { .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; .await;
match patch { if let Err(error) = saved {
Ok(patch) => { this.update(cx, |this, cx| {
if let Err(error) = std::fs::write(&destination, patch) { this.error = Some(format!("{error:#}").into());
log::warn!("failed to write commit patch: {error}"); cx.notify();
})?;
} }
}
Err(error) => log::warn!("failed to build commit patch: {error}"),
}
this.update(cx, |_, cx| cx.notify())?;
Ok(()) Ok(())
}); });
@@ -167,13 +167,18 @@ impl Render for CreateRepoDialog {
let desc_input = self.desc_input.clone(); let desc_input = self.desc_input.clone();
let folder_input = self.folder_input.clone(); let folder_input = self.folder_input.clone();
let relay_input = self.relay_input.clone(); let relay_input = self.relay_input.clone();
let state = self.state.clone(); let state = self.state.clone();
let busy = state.read(cx).busy;
let grasp_state = self.grasp_state.clone(); let grasp_state = self.grasp_state.clone();
let action_state = state.clone(); let action_state = state.clone();
let this = cx.entity().downgrade(); let this = cx.entity().downgrade();
Dialog::new("create-repo-dialog") Dialog::new("create-repo-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
.close_on_escape(!busy)
.close_on_backdrop(!busy)
.min_width(px(520.)) .min_width(px(520.))
.title("Create Repository") .title("Create Repository")
.content(move |_window, cx| { .content(move |_window, cx| {
@@ -179,9 +179,12 @@ impl Render for InitRepoDialog {
let folder = self.local_path.display().to_string(); let folder = self.local_path.display().to_string();
let branches = self.branches.clone(); let branches = self.branches.clone();
let selected_branch = self.selected_branch.clone(); let selected_branch = self.selected_branch.clone();
let busy = state.read(cx).busy;
Dialog::new("init-repo-dialog") Dialog::new("init-repo-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
.close_on_escape(!busy)
.close_on_backdrop(!busy)
.min_width(px(520.)) .min_width(px(520.))
.title("Initialize repository") .title("Initialize repository")
.content(move |_, cx| { .content(move |_, cx| {
+46 -13
View File
@@ -1,7 +1,7 @@
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
Styled as _, Window, div, px, Window, div, px,
}; };
use signed_state::RepoStore; use signed_state::RepoStore;
use ui::button::{Button, ButtonVariant}; use ui::button::{Button, ButtonVariant};
@@ -15,32 +15,48 @@ pub struct ResetRemoteDialog {
handle: DialogHandle, handle: DialogHandle,
store: Entity<RepoStore>, store: Entity<RepoStore>,
deleted: Vec<String>, deleted: Vec<String>,
/// Servers that could not be listed, so their refs are missing from `deleted`.
unreachable: Vec<String>,
state: Entity<DialogProgress>, state: Entity<DialogProgress>,
} }
impl ResetRemoteDialog { impl ResetRemoteDialog {
pub fn new(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) -> Entity<Self> { pub fn new(
store: Entity<RepoStore>,
deleted: Vec<String>,
unreachable: Vec<String>,
cx: &mut App,
) -> Entity<Self> {
let state = cx.new(|_| DialogProgress::default()); let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self { cx.new(|_| Self {
handle: DialogHandle::new(true), handle: DialogHandle::new(true),
store, store,
deleted, deleted,
unreachable,
state, state,
}) })
} }
} }
impl Render for ResetRemoteDialog { impl Render for ResetRemoteDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> 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 deleted = self.deleted.clone();
let unreachable = self.unreachable.clone();
let action_unreachable = unreachable.clone();
let store = self.store.clone(); let store = self.store.clone();
let cancel_close = self.handle.clone(); let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone(); let confirm_close = self.handle.clone();
let content_state = self.state.clone(); let content_state = self.state.clone();
let action_state = self.state.clone(); let action_state = self.state.clone();
let busy = self.state.read(cx).busy;
Dialog::new("reset-remote-dialog") Dialog::new("reset-remote-dialog")
.handle(self.handle.clone()) .handle(self.handle.clone())
.close_on_escape(!busy)
.close_on_backdrop(!busy)
.min_width(px(480.)) .min_width(px(480.))
.title("Reset remote to local") .title("Reset remote to local")
.content(move |_, cx| { .content(move |_, cx| {
@@ -49,14 +65,28 @@ impl Render for ResetRemoteDialog {
v_flex() v_flex()
.gap_2() .gap_2()
.child( .child(
div().text_base() div()
.text_base()
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.child( .child(WARNING),
"Grasp servers are overwritten to match the local mirror. Refs that do not exist locally are deleted from the servers. This cannot be undone.",
),
) )
.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() { .child(if deleted.is_empty() {
div().text_base() div()
.text_base()
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.child("No server refs will be deleted.") .child("No server refs will be deleted.")
.into_any_element() .into_any_element()
@@ -64,7 +94,8 @@ impl Render for ResetRemoteDialog {
v_flex() v_flex()
.gap_1() .gap_1()
.children(deleted.iter().map(|name| { .children(deleted.iter().map(|name| {
div().text_base() div()
.text_base()
.font_family(cx.theme().mono_font) .font_family(cx.theme().mono_font)
.child(name.clone()) .child(name.clone())
})) }))
@@ -80,22 +111,24 @@ impl Render for ResetRemoteDialog {
let confirm_close = confirm_close.clone(); let confirm_close = confirm_close.clone();
let confirm_state = action_state.clone(); let confirm_state = action_state.clone();
let cancel: AnyElement = Button::new("cancel-reset-remote") let cancel = Button::new("cancel-reset-remote")
.label("Cancel") .label("Cancel")
.variant(ButtonVariant::Secondary) .variant(ButtonVariant::Secondary)
.disabled(busy)
.on_click(move |_, _, cx| cancel_close.close(cx)) .on_click(move |_, _, cx| cancel_close.close(cx))
.into_any_element(); .into_any_element();
let confirm: AnyElement = Button::new("confirm-reset-remote") let confirm = Button::new("confirm-reset-remote")
.label("Reset remote") .label("Reset remote")
.variant(ButtonVariant::Destructive) .variant(ButtonVariant::Destructive)
.loading(busy) .loading(busy)
.disabled(busy) .disabled(busy || !action_unreachable.is_empty())
.on_click(move |_, window, cx| { .on_click(move |_, window, cx| {
let task = store.update(cx, |store, cx| store.reset_repository(cx)); let task = store.update(cx, |store, cx| store.reset_repository(cx));
let state = confirm_state.clone(); let state = confirm_state.clone();
let close = confirm_close.clone(); let close = confirm_close.clone();
let handle = window.window_handle(); let handle = window.window_handle();
cx.spawn(async move |cx| match task.await { cx.spawn(async move |cx| match task.await {
Ok(()) => { Ok(()) => {
cx.update_window(handle, |_, _, cx| close.close(cx)) cx.update_window(handle, |_, _, cx| close.close(cx))
+19 -3
View File
@@ -71,6 +71,8 @@ pub struct RepoFilesView {
pending_commits: Vec<String>, pending_commits: Vec<String>,
loading_commits: bool, loading_commits: bool,
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
/// Bumped when the previews are cleared, so loads started before it are dropped.
generation: u64,
} }
impl EventEmitter<RepoFilesEvent> for RepoFilesView {} impl EventEmitter<RepoFilesEvent> for RepoFilesView {}
@@ -96,6 +98,7 @@ impl RepoFilesView {
pending_commits: Vec::new(), pending_commits: Vec::new(),
loading_commits: false, loading_commits: false,
tasks: Vec::new(), tasks: Vec::new(),
generation: 0,
} }
} }
@@ -173,6 +176,7 @@ impl RepoFilesView {
self.md = None; self.md = None;
self.code = None; self.code = None;
self.readme_name = None; self.readme_name = None;
self.generation = self.generation.wrapping_add(1);
} }
/// Refresh after the mirror caught up with the remote. /// Refresh after the mirror caught up with the remote.
@@ -523,8 +527,7 @@ impl RepoFilesView {
return; return;
}; };
// Tree paths originate from git, so symlink escapes are accepted; only // Tree paths originate from git, so symlink escapes are accepted.
// crafted components are rejected, and visibly.
if unsafe_path { if unsafe_path {
self.files.insert( self.files.insert(
path.to_string(), path.to_string(),
@@ -539,6 +542,8 @@ impl RepoFilesView {
self.load_commit(&path, cx); self.load_commit(&path, cx);
let generation = self.generation;
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| { let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
let path_for_read = path.clone(); let path_for_read = path.clone();
let content = cx let content = cx
@@ -567,6 +572,9 @@ impl RepoFilesView {
.await; .await;
this.update_in(cx, |this, _window, cx| { this.update_in(cx, |this, _window, cx| {
if generation != this.generation {
return;
}
this.loading_files.remove(&path); this.loading_files.remove(&path);
match content { match content {
@@ -677,7 +685,9 @@ impl RepoFilesView {
}; };
self.loading_commits = true; self.loading_commits = true;
let paths = std::mem::take(&mut self.pending_commits); let paths = std::mem::take(&mut self.pending_commits);
let generation = self.generation;
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| { let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let rels: Vec<PathBuf> = paths.iter().map(PathBuf::from).collect(); let rels: Vec<PathBuf> = paths.iter().map(PathBuf::from).collect();
@@ -688,14 +698,20 @@ impl RepoFilesView {
.await; .await;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
if generation != this.generation {
return;
}
this.loading_commits = false; this.loading_commits = false;
if let Ok(found) = result { match result {
Ok(found) => {
for (path, commit) in found { for (path, commit) in found {
this.commits this.commits
.insert(path.to_string_lossy().into_owned(), commit); .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() { if !this.pending_commits.is_empty() {
this.load_commits(cx); this.load_commits(cx);
+1 -1
View File
@@ -443,7 +443,7 @@ pub(super) fn sync_selector(
if let Some(value) = selected if let Some(value) = selected
&& (items_changed || selection_changed) && (items_changed || selection_changed)
{ {
state.set_selected(Some(value), window, cx); state.set_selected_silent(Some(value), window, cx);
} }
}); });
*cached = items; *cached = items;
+4 -9
View File
@@ -37,7 +37,8 @@ pub struct RepoHistoryView {
/// The last load failure, shown instead of the empty list. /// The last load failure, shown instead of the empty list.
error: Option<SharedString>, error: Option<SharedString>,
scroll_handle: UniformListScrollHandle, scroll_handle: UniformListScrollHandle,
tasks: Vec<Task<Result<(), Error>>>, /// The latest walk, assigning it cancels the previous one.
load_task: Option<Task<Result<(), Error>>>,
} }
impl RepoHistoryView { impl RepoHistoryView {
@@ -58,7 +59,7 @@ impl RepoHistoryView {
commits: Arc::new(Vec::new()), commits: Arc::new(Vec::new()),
error: None, error: None,
scroll_handle: UniformListScrollHandle::new(), scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(), load_task: None,
} }
} }
@@ -82,12 +83,6 @@ impl RepoHistoryView {
self.load(cx); self.load(cx);
} }
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn load(&mut self, cx: &mut Context<Self>) { fn load(&mut self, cx: &mut Context<Self>) {
if self.loading_all_commits || self.all_commits.is_some() { if self.loading_all_commits || self.all_commits.is_some() {
return; return;
@@ -122,7 +117,7 @@ impl RepoHistoryView {
Ok(()) Ok(())
}); });
self.push_task(task); self.load_task = Some(task);
} }
pub fn open_commit_diff( pub fn open_commit_diff(
+51 -25
View File
@@ -264,6 +264,14 @@ impl RepoDetailView {
this.track_sync_status(cx); this.track_sync_status(cx);
if !this.repo_started && store.read(cx).announcement.is_some() { if !this.repo_started && store.read(cx).announcement.is_some() {
this.load_repo(window, cx); 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(); cx.notify();
})); }));
@@ -623,21 +631,24 @@ impl RepoDetailView {
let Some(worktree) = self.worktree.clone() else { let Some(worktree) = self.worktree.clone() else {
return; return;
}; };
let name = name.into(); 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 { match kind {
RefKind::Branch => { RefKind::Branch => {
self.refs self.refs
.tag_select .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 => { RefKind::Tag => {
self.refs self.refs
.branch_select .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 checkout_name = name.clone();
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| { let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
let result = cx let outcome = cx
.background_spawn(async move { .background_spawn(async move {
let repo = Repo::open(&worktree); 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 => { RefKind::Branch => {
repo.and_then(|repo| repo.checkout_branch(&checkout_name)) repo.and_then(|repo| repo.checkout_branch(&checkout_name))
} }
RefKind::Tag => repo.and_then(|repo| repo.checkout_tag(&checkout_name)), RefKind::Tag => repo.and_then(|repo| repo.checkout_tag(&checkout_name)),
};
match checkout {
Ok(()) => Ok(current),
Err(error) => Err((error, current)),
} }
}) })
.await; .await;
this.update_in(cx, |this, window, cx| { this.update_in(cx, |this, window, cx| {
match result { match outcome {
Ok(()) => this.reload_worktree(cx), Ok(_) => this.reload_worktree(cx),
Err(error) => { Err((error, current)) => {
this.error = Some(format!("Failed to check out {name}: {error}").into()); this.error = Some(format!("Failed to check out {name}: {error}").into());
this.refs.switching_ref = false; this.refs.switching_ref = false;
let detached = current.is_none();
this.refs.restore_selection( this.refs.restore_selection(
&this.refs.branch_select, &this.refs.branch_select,
&previous_branch, &current.map(Into::into),
window,
cx,
);
this.refs.restore_selection(
&this.refs.tag_select,
&previous_tag,
window, window,
cx, cx,
); );
let tag = if detached { previous_tag } else { None };
this.refs
.restore_selection(&this.refs.tag_select, &tag, window, cx);
} }
} }
cx.notify(); cx.notify();
@@ -890,6 +907,8 @@ impl RepoDetailView {
let probe = cx.background_spawn(async move { let probe = cx.background_spawn(async move {
let mut deleted: Vec<String> = Vec::new(); let mut deleted: Vec<String> = Vec::new();
// A server that cannot be listed may still hold refs the reset deletes.
let mut unreachable: Vec<String> = Vec::new();
let repo = Repo::open(&mirror)?; let repo = Repo::open(&mirror)?;
let local: HashSet<String> = repo let local: HashSet<String> = repo
@@ -900,26 +919,33 @@ impl RepoDetailView {
.collect(); .collect();
for url in &urls { for url in &urls {
let Ok(remote_refs) = repo.ls_remote(url) else { match repo.ls_remote(url) {
continue; Ok(remote_refs) => {
};
for (name, _) in remote_refs { for (name, _) in remote_refs {
if !local.contains(&name) && !deleted.contains(&name) { if !local.contains(&name) && !deleted.contains(&name) {
deleted.push(name); deleted.push(name);
} }
} }
} }
Err(_) => unreachable.push(url.clone()),
}
}
deleted.sort(); deleted.sort();
Ok::<_, Error>(deleted) Ok::<_, Error>((deleted, unreachable))
}); });
cx.spawn_in(window, async move |this, cx| { 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 { this.update_in(cx, |this, _window, cx| match probe {
Ok(deleted) => { Ok((deleted, unreachable)) => {
this.reset = Some(dialogs::reset::ResetRemoteDialog::new(store, deleted, cx)); this.reset = Some(dialogs::reset::ResetRemoteDialog::new(
store,
deleted,
unreachable,
cx,
));
cx.notify(); cx.notify();
} }
Err(error) => { Err(error) => {
+1 -1
View File
@@ -97,7 +97,7 @@ impl RefSwitcher {
cx: &mut App, cx: &mut App,
) { ) {
select.update(cx, |state, cx| { select.update(cx, |state, cx| {
state.set_selected(previous.clone(), window, cx) state.set_selected_silent(previous.clone(), window, cx)
}); });
} }
} }
@@ -13,7 +13,6 @@ use ui::select::{Select, SelectOption};
use ui::theme::ActiveTheme as _; use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip; use ui::tooltip::Tooltip;
use crate::apply_appearance_mode;
use crate::repo::dialogs::grasp_servers::{normalize_server, server_host}; use crate::repo::dialogs::grasp_servers::{normalize_server, server_host};
/// The title and description a settings row or block opens with. /// The title and description a settings row or block opens with.
@@ -80,7 +79,6 @@ pub fn appearance_select(cx: &App) -> Select<AppearanceMode> {
SettingsStore::global(cx).update(cx, |store, cx| { SettingsStore::global(cx).update(cx, |store, cx| {
store.edit(|settings| settings.appearance = mode, cx); store.edit(|settings| settings.appearance = mode, cx);
}); });
apply_appearance_mode(mode, cx);
}) })
} }
+13
View File
@@ -1,5 +1,6 @@
mod helpers; mod helpers;
use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
Window, px, Window, px,
@@ -9,6 +10,7 @@ use helpers::{
scan_paths_editor, setting_block, setting_row, scan_paths_editor, setting_block, setting_row,
}; };
use settings::SettingsStore; use settings::SettingsStore;
use ui::alert::{Alert, AlertSeverity};
use ui::common::v_flex; use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle}; use ui::dialog::{Dialog, DialogHandle};
use ui::input::InputState; use ui::input::InputState;
@@ -64,8 +66,19 @@ impl Render for SettingsDialog {
.height(px(560.)) .height(px(560.))
.title("Settings") .title("Settings")
.content(move |_, cx| { .content(move |_, cx| {
let error = SettingsStore::global(cx).read(cx).error.clone();
v_flex() v_flex()
.gap_4() .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( .child(setting_row(
cx, cx,
"Appearance", "Appearance",
+1 -2
View File
@@ -21,8 +21,7 @@ pub fn log_dropped<T>(result: Result<T, anyhow::Error>) {
} }
} }
/// Tracks a detail view's author, commenters, and repository owner for /// Tracks a detail view's author, commenters, and owner for profile prefetch.
/// profile prefetch.
pub fn track_event_participants( pub fn track_event_participants(
author: Option<PublicKey>, author: Option<PublicKey>,
owner: Option<PublicKey>, owner: Option<PublicKey>,
-4
View File
@@ -25,10 +25,6 @@ impl RepoAddr {
.collect() .collect()
} }
pub fn kind(&self) -> Kind {
self.0.kind
}
pub fn public_key(&self) -> PublicKey { pub fn public_key(&self) -> PublicKey {
self.0.public_key self.0.public_key
} }
-37
View File
@@ -106,40 +106,3 @@ impl GitEvent for Event {
.any(|tag| matches!(tag.kind(), "e" | "E") && tag.content() == Some(root.as_str())) .any(|tag| matches!(tag.kind(), "e" | "E") && tag.content() == Some(root.as_str()))
} }
} }
impl<T: GitEvent + ?Sized> 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<String> {
(*self).current_commit()
}
/// Delegates to the referenced event.
fn merge_base(&self) -> Option<String> {
(*self).merge_base()
}
/// Delegates to the referenced event.
fn clone_urls(&self) -> Option<Vec<Url>> {
(*self).clone_urls()
}
/// Delegates to the referenced event.
fn branch_name(&self) -> Option<String> {
(*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)
}
}
+1 -1
View File
@@ -71,7 +71,7 @@ where
items.sort_by(|a, b| { items.sort_by(|a, b| {
b.latest_activity() b.latest_activity()
.cmp(&a.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 items
+16 -3
View File
@@ -29,9 +29,12 @@ impl GitCache {
/// Returns the cache path for a repository address. /// Returns the cache path for a repository address.
pub fn repo_path(&self, addr: &RepoAddr) -> PathBuf { pub fn repo_path(&self, addr: &RepoAddr) -> PathBuf {
self.root let identifier = addr.identifier();
.join(addr.public_key().to_hex()) self.root.join(addr.public_key().to_hex()).join(format!(
.join(Self::sanitize_path_component(addr.identifier())) "{}-{}",
Self::sanitize_path_component(identifier),
Self::identifier_suffix(identifier),
))
} }
/// Opens the cached repository, or `None` when it is not cloned yet. /// Opens the cached repository, or `None` when it is not cloned yet.
@@ -103,6 +106,16 @@ impl GitCache {
sanitized 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. /// Returns the `owner/identifier` namespace used for fork checkouts.
pub fn fork_namespace(announcement: &Announcement) -> String { pub fn fork_namespace(announcement: &Announcement) -> String {
format!( format!(
+10 -1
View File
@@ -271,11 +271,20 @@ impl ConsumeHunk for PatchCollector {
GixLineKind::Remove => '-', GixLineKind::Remove => '-',
GixLineKind::Add => '+', GixLineKind::Add => '+',
}; };
// Tokens may already carry the line's newline; emit exactly one. // 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(prefix);
self.text.push_str(&String::from_utf8_lossy(content)); self.text.push_str(&String::from_utf8_lossy(content));
self.text.push('\n'); self.text.push('\n');
if !terminated {
self.text.push_str("\\ No newline at end of file\n");
}
} }
Ok(()) Ok(())
+1 -2
View File
@@ -19,8 +19,7 @@ pub struct FileCommit {
pub description: Option<String>, pub description: Option<String>,
pub author: String, pub author: String,
pub time: i64, pub time: i64,
/// Human-readable absolute date in the commit's recorded offset, e.g. /// Date in the commit's offset, e.g. "Nov 21, 2026 at 4:40 AM GMT+7".
/// "Nov 21, 2026 at 4:40 AM GMT+7"; empty when the date cannot be formatted.
pub date_label: String, pub date_label: String,
/// Full hex parent ids; empty for patch-parsed commits. /// Full hex parent ids; empty for patch-parsed commits.
pub parents: Vec<String>, pub parents: Vec<String>,
+5 -3
View File
@@ -67,9 +67,10 @@ impl PatchParser {
let mut headers_closed = false; let mut headers_closed = false;
let mut offset = 0usize; let mut offset = 0usize;
for line in patch.lines() { for raw in patch.split_inclusive('\n') {
let line_start = offset; let line_start = offset;
offset += line.len() + 1; offset += raw.len();
let line = raw.trim_end_matches(['\r', '\n']);
let is_envelope = line let is_envelope = line
.strip_prefix("From ") .strip_prefix("From ")
@@ -78,7 +79,8 @@ impl PatchParser {
if is_envelope { if is_envelope {
if let Some((start, id, headers)) = current.take() { 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 let id = line
+38 -24
View File
@@ -594,16 +594,16 @@ impl Repo {
} }
let platform = attached.diff(&mut cache)?; 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 outcome = platform.resource_cache.prepare_diff().into_anyhow()?;
match outcome.operation { match outcome.operation {
Operation::InternalDiff { algorithm } => { 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 diff = gix::diff::blob::diff_with_slider_heuristics(algorithm, &input);
let text = gix::diff::blob::UnifiedDiff::new( let text = gix::diff::blob::UnifiedDiff::new(
&diff, &diff,
@@ -719,10 +719,6 @@ impl Repo {
}; };
let platform = attached.diff(&mut cache)?; 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 outcome = platform.resource_cache.prepare_diff().into_anyhow()?;
let (binary, hunks, insertions, deletions) = match outcome.operation { let (binary, hunks, insertions, deletions) = match outcome.operation {
@@ -1180,14 +1176,15 @@ impl Repo {
let (signature, mut time_buf) = Self::repository_signature(); let (signature, mut time_buf) = Self::repository_signature();
let signature = signature.to_ref(&mut time_buf); 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( self.move_head(
signature, signature,
gix::refs::Target::Symbolic(branch), gix::refs::Target::Symbolic(branch),
&format!("checkout: moving to {name}"), &format!("checkout: moving to {name}"),
)?; )?;
self.force_checkout(&tree)?;
Ok(()) Ok(())
} }
@@ -1196,21 +1193,19 @@ impl Repo {
let full = format!("refs/tags/{name}"); let full = format!("refs/tags/{name}");
let mut reference = self.inner.find_reference(&full)?; let mut reference = self.inner.find_reference(&full)?;
let commit = reference.peel_to_id()?; let commit = reference.peel_to_id()?;
let tree = reference.peel_to_tree()?.id; let tree = reference.peel_to_tree()?.id;
let (signature, mut time_buf) = Self::repository_signature(); let (signature, mut time_buf) = Self::repository_signature();
let signature = signature.to_ref(&mut time_buf); let signature = signature.to_ref(&mut time_buf);
self.force_checkout(&tree)?;
self.move_head( self.move_head(
signature, signature,
gix::refs::Target::Object(commit.detach()), gix::refs::Target::Object(commit.detach()),
&format!("checkout: moving to {name}"), &format!("checkout: moving to {name}"),
)?; )?;
self.force_checkout(&tree)?;
Ok(()) Ok(())
} }
@@ -1224,14 +1219,38 @@ impl Repo {
let mut index = self.inner.index_from_tree(tree)?; let mut index = self.inner.index_from_tree(tree)?;
if let Ok(previous) = self.inner.index_or_empty() { // `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");
}
let previous = self.inner.index_or_empty()?;
let tracked: HashSet<&gix::bstr::BStr> = previous
.entries()
.iter()
.map(|entry| entry.path(&previous))
.collect();
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)
);
}
let keep: HashSet<PathBuf> = index let keep: HashSet<PathBuf> = index
.entries() .entries()
.iter() .iter()
.map(|entry| { .map(|entry| PathBuf::from(String::from_utf8_lossy(entry.path(&index)).into_owned()))
PathBuf::from(String::from_utf8_lossy(entry.path(&index)).into_owned())
})
.collect(); .collect();
for entry in previous.entries() { for entry in previous.entries() {
let rel = entry.path(&previous); let rel = entry.path(&previous);
let rel = PathBuf::from(String::from_utf8_lossy(rel).into_owned()); let rel = PathBuf::from(String::from_utf8_lossy(rel).into_owned());
@@ -1241,7 +1260,6 @@ impl Repo {
} }
let path = workdir.join(&rel); let path = workdir.join(&rel);
match std::fs::remove_file(&path) { match std::fs::remove_file(&path) {
Ok(()) => {} Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
@@ -1251,7 +1269,6 @@ impl Repo {
} }
} }
} }
}
let mut options = self let mut options = self
.inner .inner
@@ -1436,10 +1453,7 @@ impl Repo {
) )
} }
/// Mirrors all branches and tags to the grasp repository at `base_url`. /// Mirrors branches and tags to `base_url` with force refspecs; grasp authorizes by ref map.
///
/// Force refspecs keep the server ref map following the local repository,
/// grasp authorizes pushes by ref map equality, not fast-forwards.
pub fn push_all(&self, base_url: &str, owner: &str, repo_id: &str) -> Result<()> { pub fn push_all(&self, base_url: &str, owner: &str, repo_id: &str) -> Result<()> {
self.push_refspecs( self.push_refspecs(
base_url, base_url,
+5
View File
@@ -38,10 +38,15 @@ pub fn find_git_repos(root: &Path) -> Vec<LocalRepo> {
let Some(kind) = entry.file_type() else { let Some(kind) = entry.file_type() else {
return true; return true;
}; };
if !kind.is_dir() { if !kind.is_dir() {
return true; return true;
} }
if entry.file_name() == std::ffi::OsStr::new(".git") {
return false;
}
let dir = entry.path(); let dir = entry.path();
let Ok(repo) = gix::discover(dir) else { let Ok(repo) = gix::discover(dir) else {
return true; return true;
-5
View File
@@ -25,11 +25,6 @@ pub struct RepoSyncStatus {
} }
impl 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. /// Maps branch short name to lowercase commit oid.
pub(crate) fn branches(refs: &[(String, String)]) -> BTreeMap<&str, String> { pub(crate) fn branches(refs: &[(String, String)]) -> BTreeMap<&str, String> {
refs.iter() refs.iter()
+13 -5
View File
@@ -33,7 +33,15 @@ impl UniversalSigner {
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static, <T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
<T as AsyncNip44>::Error: Error + Send + Sync + 'static, <T as AsyncNip44>::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<dyn InnerSigner> {
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( fn get_public_key_async(
&self, &self,
) -> Pin<Box<dyn Future<Output = Result<PublicKey, Self::Error>> + Send + '_>> { ) -> Pin<Box<dyn Future<Output = Result<PublicKey, Self::Error>> + Send + '_>> {
let inner = self.inner.read().expect("RwLock poisoned").clone(); let inner = self.inner();
Box::pin(async move { inner.get_public_key_async().await }) Box::pin(async move { inner.get_public_key_async().await })
} }
} }
@@ -131,7 +139,7 @@ impl AsyncSignEvent for UniversalSigner {
&self, &self,
unsigned: UnsignedEvent, unsigned: UnsignedEvent,
) -> Pin<Box<dyn Future<Output = Result<Event, Self::Error>> + Send + '_>> { ) -> Pin<Box<dyn Future<Output = Result<Event, Self::Error>> + Send + '_>> {
let inner = self.inner.read().expect("RwLock poisoned").clone(); let inner = self.inner();
Box::pin(async move { inner.sign_event_async(unsigned).await }) Box::pin(async move { inner.sign_event_async(unsigned).await })
} }
} }
@@ -144,7 +152,7 @@ impl AsyncNip44 for UniversalSigner {
public_key: &'a PublicKey, public_key: &'a PublicKey,
content: &'a str, content: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, Self::Error>> + Send + 'a>> { ) -> Pin<Box<dyn Future<Output = Result<String, Self::Error>> + 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 }) Box::pin(async move { inner.nip44_encrypt_async(public_key, content).await })
} }
@@ -153,7 +161,7 @@ impl AsyncNip44 for UniversalSigner {
public_key: &'a PublicKey, public_key: &'a PublicKey,
payload: &'a str, payload: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, Self::Error>> + Send + 'a>> { ) -> Pin<Box<dyn Future<Output = Result<String, Self::Error>> + 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 }) Box::pin(async move { inner.nip44_decrypt_async(public_key, payload).await })
} }
} }
+105 -28
View File
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
use anyhow::{Error, anyhow, bail}; use anyhow::{Error, anyhow, bail};
use bitcoin_hashes::sha1::Hash as Sha1Hash; 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::event::IntoEventBuilder;
use nostr::nips::nip19::Nip19Coordinate; use nostr::nips::nip19::Nip19Coordinate;
use nostr_connect::prelude::*; use nostr_connect::prelude::*;
@@ -26,6 +26,7 @@ use crate::state::{GitPushMode, GitPushPolicy, GitRef, PushStepStatus, SyncState
pub const USER_KEYRING: &str = "Signed Safe Storage"; pub const USER_KEYRING: &str = "Signed Safe Storage";
const PUMP_DEBOUNCE: Duration = Duration::from_millis(200); const PUMP_DEBOUNCE: Duration = Duration::from_millis(200);
const MAX_SEEN_EVENT_IDS: usize = 65_536;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum BackendEvent { pub enum BackendEvent {
@@ -58,6 +59,8 @@ pub struct Backend {
inbox: Entity<Inbox>, inbox: Entity<Inbox>,
passphrase_required: bool, passphrase_required: bool,
pushing_repos: Entity<HashSet<RepoAddr>>, pushing_repos: Entity<HashSet<RepoAddr>>,
/// Bumped by every explicit identity action, results from an older session are dropped.
session: u64,
} }
struct GlobalBackend(Entity<Backend>); struct GlobalBackend(Entity<Backend>);
@@ -169,6 +172,7 @@ impl Backend {
inbox: cx.new(|_| Inbox::default()), inbox: cx.new(|_| Inbox::default()),
passphrase_required: false, passphrase_required: false,
pushing_repos: cx.new(|_| HashSet::new()), pushing_repos: cx.new(|_| HashSet::new()),
session: 0,
} }
} }
@@ -179,12 +183,17 @@ impl Backend {
} }
let user = cx.read_credentials(USER_KEYRING); let user = cx.read_credentials(USER_KEYRING);
let session = self.session;
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| { let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let content = match user.await { let content = match user.await {
Ok(Some((_username, secret))) => String::from_utf8(secret)?, 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(()); return Ok(());
} }
}; };
@@ -193,7 +202,7 @@ impl Backend {
if content.starts_with("nsec1") { if content.starts_with("nsec1") {
let keys = Keys::new(SecretKey::parse(&content)?); let keys = Keys::new(SecretKey::parse(&content)?);
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_signer(keys, cx); this.set_signer(keys, session, cx);
})?; })?;
} else if content.starts_with("bunker://") { } else if content.starts_with("bunker://") {
let (base, keys) = extract_master_key(&content)?; let (base, keys) = extract_master_key(&content)?;
@@ -203,16 +212,20 @@ impl Backend {
.build()?; .build()?;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_signer(signer, cx); this.set_signer(signer, session, cx);
})?; })?;
} else if content.starts_with("ncryptsec1") { } else if content.starts_with("ncryptsec1") {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
if this.session == session {
this.passphrase_required = true; this.passphrase_required = true;
cx.emit(BackendEvent::PassphraseRequired); cx.emit(BackendEvent::PassphraseRequired);
}
})?; })?;
} else { } else {
this.update(cx, |_this, cx| { this.update(cx, |this, cx| {
if this.session == session {
cx.emit(BackendEvent::SignerRequired); cx.emit(BackendEvent::SignerRequired);
}
})?; })?;
} }
@@ -221,9 +234,11 @@ impl Backend {
.await; .await;
if let Err(e) = result { if let Err(e) = result {
this.update(cx, |_this, cx| { this.update(cx, |this, cx| {
if this.session == session {
cx.emit(BackendEvent::error(e.to_string())); cx.emit(BackendEvent::error(e.to_string()));
cx.emit(BackendEvent::SignerRequired); cx.emit(BackendEvent::SignerRequired);
}
})?; })?;
} }
@@ -237,6 +252,7 @@ impl Backend {
password: &str, password: &str,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Task<Result<PublicKey, Error>> { ) -> Task<Result<PublicKey, Error>> {
let session = self.supersede_session();
let password = password.to_owned(); let password = password.to_owned();
let user = cx.read_credentials(USER_KEYRING); let user = cx.read_credentials(USER_KEYRING);
@@ -260,7 +276,9 @@ impl Backend {
let keys = decrypt_task.await?; let keys = decrypt_task.await?;
let public_key = keys.public_key(); 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) Ok(public_key)
}) })
@@ -283,6 +301,7 @@ impl Backend {
} }
let password = password.to_owned(); let password = password.to_owned();
let session = self.supersede_session();
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let job = cx.background_spawn(async move { let job = cx.background_spawn(async move {
@@ -300,7 +319,9 @@ impl Backend {
}); });
write.await?; 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) Ok(public_key)
}) })
@@ -313,13 +334,13 @@ impl Backend {
password: &str, password: &str,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Task<Result<PublicKey, Error>> { ) -> Task<Result<PublicKey, Error>> {
let ncryptsec = ncryptsec.trim().to_owned();
if password.is_empty() { if password.is_empty() {
return Task::ready(Err(anyhow!("Passphrase must not be empty"))); return Task::ready(Err(anyhow!("Passphrase must not be empty")));
} }
let ncryptsec = ncryptsec.trim().to_owned();
let password = password.to_owned(); let password = password.to_owned();
let session = self.supersede_session();
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let stored = ncryptsec.clone(); let stored = ncryptsec.clone();
@@ -337,7 +358,9 @@ impl Backend {
}); });
write.await?; 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) Ok(public_key)
}) })
@@ -359,6 +382,7 @@ impl Backend {
let keys = Keys::generate(); let keys = Keys::generate();
let credential = with_master_key(&uri_string, &keys); let credential = with_master_key(&uri_string, &keys);
let write = cx.write_credentials(USER_KEYRING, "bunker", credential.as_bytes()); let write = cx.write_credentials(USER_KEYRING, "bunker", credential.as_bytes());
let session = self.supersede_session();
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let signer = NostrConnect::builder(connect_uri, keys) let signer = NostrConnect::builder(connect_uri, keys)
@@ -369,7 +393,9 @@ impl Backend {
let public_key = signer.get_public_key_async().await?; let public_key = signer.get_public_key_async().await?;
write.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) Ok(public_key)
}) })
@@ -384,13 +410,15 @@ impl Backend {
let name = name.trim().to_owned(); let name = name.trim().to_owned();
let password = password.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"))); return Task::ready(Err(anyhow!("Name must be 1-255 characters")));
} }
if password.is_empty() { if password.is_empty() {
return Task::ready(Err(anyhow!("Passphrase must not be empty"))); return Task::ready(Err(anyhow!("Passphrase must not be empty")));
} }
let session = self.supersede_session();
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let job = cx.background_spawn(async move { let job = cx.background_spawn(async move {
let keys = Keys::generate(); let keys = Keys::generate();
@@ -409,6 +437,9 @@ impl Backend {
write.await?; write.await?;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
if this.session != session {
return;
}
this.signer.swap_inner(keys); this.signer.swap_inner(keys);
this.current_user = Some(public_key); this.current_user = Some(public_key);
this.bootstrap_user(public_key, cx); this.bootstrap_user(public_key, cx);
@@ -449,11 +480,13 @@ impl Backend {
.map(|url| RelayUrl::parse(url).expect("valid relay URL")) .map(|url| RelayUrl::parse(url).expect("valid relay URL"))
.collect(); .collect();
for builder in [ let publishes = [
RelayList::new(relays).into_event_builder(), RelayList::new(relays).into_event_builder(),
metadata, metadata,
GitUserGraspList { grasp_servers }.into_event_builder(), GitUserGraspList { grasp_servers }.into_event_builder(),
] { ]
.into_iter()
.map(|builder| {
let client = this.client.clone(); let client = this.client.clone();
let signer = this.signer.clone(); let signer = this.signer.clone();
cx.background_spawn(async move { cx.background_spawn(async move {
@@ -472,8 +505,21 @@ impl Backend {
Ok::<(), anyhow::Error>(()) Ok::<(), anyhow::Error>(())
}) })
.detach(); })
.collect::<Vec<_>>();
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) Ok(public_key)
@@ -976,10 +1022,8 @@ impl Backend {
}); });
let events = events.await?; let events = events.await?;
this.update(cx, |this, cx| { let deletions = this.update(cx, |this, cx| this.retract_events(&events, cx))?;
this.retract_events(&events, cx); futures::future::try_join_all(deletions).await?;
})
.ok();
Ok(()) Ok(())
}) })
@@ -1061,6 +1105,9 @@ impl Backend {
} }
pub fn sign_out(&mut self, cx: &mut Context<Self>) { pub fn sign_out(&mut self, cx: &mut Context<Self>) {
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.current_user = None;
self.passphrase_required = false; self.passphrase_required = false;
@@ -1068,7 +1115,19 @@ impl Backend {
inbox.reset(cx); 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::SignerChanged);
cx.emit(BackendEvent::SignerRequired); cx.emit(BackendEvent::SignerRequired);
cx.notify(); cx.notify();
@@ -1103,7 +1162,12 @@ impl Backend {
}); });
} }
fn set_signer<T>(&mut self, new_signer: T, cx: &mut Context<Self>) fn supersede_session(&mut self) -> u64 {
self.session += 1;
self.session
}
fn set_signer<T>(&mut self, new_signer: T, session: u64, cx: &mut Context<Self>)
where where
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static, T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
<T as AsyncGetPublicKey>::Error: std::error::Error + Send + Sync + 'static, <T as AsyncGetPublicKey>::Error: std::error::Error + Send + Sync + 'static,
@@ -1114,6 +1178,9 @@ impl Backend {
match new_signer.get_public_key_async().await { match new_signer.get_public_key_async().await {
Ok(public_key) => { Ok(public_key) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
if this.session != session {
return;
}
this.signer.swap_inner(new_signer); this.signer.swap_inner(new_signer);
this.current_user = Some(public_key); this.current_user = Some(public_key);
this.passphrase_required = false; this.passphrase_required = false;
@@ -1243,8 +1310,15 @@ impl Backend {
} }
// Each target gets its own deletion event. // Each target gets its own deletion event.
fn retract_events(&mut self, events: &[Event], cx: &mut Context<Self>) { fn retract_events(
for event in events.iter().cloned() { &mut self,
events: &[Event],
cx: &mut Context<Self>,
) -> Vec<Task<Result<(), Error>>> {
events
.iter()
.cloned()
.map(|event| {
let client = self.client.clone(); let client = self.client.clone();
let signer = self.signer.clone(); let signer = self.signer.clone();
@@ -1259,8 +1333,8 @@ impl Backend {
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, /// Announces a repository and pushes its state to grasp, retracting the announcement on failure.
/// or retracts the announcement if the push fails.
async fn announce_and_push_or_retract<S, P>( async fn announce_and_push_or_retract<S, P>(
client: &Client, client: &Client,
signer: &S, signer: &S,
@@ -1355,6 +1428,10 @@ impl UpdateEvent {
}; };
if seen.insert(event.id) { 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); return Some(update);
} }
} }
+5 -19
View File
@@ -366,21 +366,11 @@ impl CheckoutsStore {
let (statuses, push_statuses) = let (statuses, push_statuses) =
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, true); CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, true);
Ok::<_, Error>((associations, statuses, push_statuses)) (associations, statuses, push_statuses)
}); });
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let (associations, statuses, push_statuses) = match work.await { let (associations, statuses, push_statuses) = work.await;
Ok(results) => results,
Err(_) => {
return this.update(cx, |this, cx| {
this.refresh.abort();
if poll {
this.schedule_local_pass(cx);
}
});
}
};
let again = this.update(cx, |this, cx| { let again = this.update(cx, |this, cx| {
let associations_changed = this.by_repo != associations; let associations_changed = this.by_repo != associations;
@@ -412,7 +402,7 @@ impl CheckoutsStore {
} }
})?; })?;
Ok(()) Ok::<(), Error>(())
}) })
.detach(); .detach();
} }
@@ -480,15 +470,11 @@ impl CheckoutsStore {
let push_requested: Vec<RepoAddr> = self.push_requested.iter().cloned().collect(); let push_requested: Vec<RepoAddr> = self.push_requested.iter().cloned().collect();
let work = cx.background_spawn(async move { let work = cx.background_spawn(async move {
let (statuses, push_statuses) = CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, false)
CheckoutsStore::compute_statuses(&associations, &requested, &push_requested, false);
Ok::<_, Error>((statuses, push_statuses))
}); });
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let Ok((statuses, push_statuses)) = work.await else { let (statuses, push_statuses) = work.await;
return Ok(());
};
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
if this.refresh.running() || this.debounce_pending { if this.refresh.running() || this.debounce_pending {
+1 -4
View File
@@ -120,9 +120,7 @@ impl Inbox {
Ok((items, unread_count)) Ok((items, unread_count))
} }
}
impl Inbox {
fn inbox_state_d_tag(me: PublicKey) -> String { fn inbox_state_d_tag(me: PublicKey) -> String {
format!("signed-inbox-state:{}", me.to_hex()) 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 // Signed with a random key: the state is local-only, authorship does not matter.
// matter and no key material needs to be kept.
async fn save_state( async fn save_state(
client: &Client, client: &Client,
me: PublicKey, me: PublicKey,
+50 -5
View File
@@ -36,14 +36,57 @@ pub fn init(
repos_root: impl Into<PathBuf>, repos_root: impl Into<PathBuf>,
scan_paths: Vec<PathBuf>, scan_paths: Vec<PathBuf>,
cx: &mut App, cx: &mut App,
) { ) -> anyhow::Result<()> {
// rustls uses the `aws_lc_rs` provider by default. // 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() .foreground_executor()
.block_on(async move { NostrBackend::open(db_path.as_ref()).await }); .block_on(NostrBackend::open(&db_path))
let backend = backend.expect("failed to initialize nostr backend"); {
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); let (client, signer) = (backend.client, backend.signer);
Mirrors::install(repos_root); Mirrors::install(repos_root);
@@ -53,4 +96,6 @@ pub fn init(
LocalReposStore::set_global(cx.new(|cx| LocalReposStore::new(scan_paths, cx)), cx); LocalReposStore::set_global(cx.new(|cx| LocalReposStore::new(scan_paths, cx)), cx);
CheckoutsStore::set_global(cx.new(CheckoutsStore::new), cx); CheckoutsStore::set_global(cx.new(CheckoutsStore::new), cx);
SyncStatusStore::set_global(cx.new(SyncStatusStore::new), cx); SyncStatusStore::set_global(cx.new(SyncStatusStore::new), cx);
Ok(())
} }
+16 -82
View File
@@ -100,33 +100,7 @@ impl LocalReposStore {
task.detach(); task.detach();
} }
}
pub fn local_repo_addr(repo: &LocalRepo) -> Option<RepoAddr> {
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<Nip34Binding>,
pub announcement: Option<Announcement>,
}
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( pub fn resolve(
repos: &[LocalRepo], repos: &[LocalRepo],
known: &[Announcement], known: &[Announcement],
@@ -164,66 +138,26 @@ impl LocalReposStore {
} }
} }
#[cfg(test)] #[derive(Debug, Clone, PartialEq)]
mod tests { pub struct ResolvedLocalRepo {
use nostr::prelude::*; pub path: PathBuf,
use signed_git::{GraspSignals, Nip34Kind}; pub nip34: Option<Nip34Binding>,
pub announcement: Option<Announcement>,
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 { impl ResolvedLocalRepo {
Keys::new(SecretKey::from_hex(secret).expect("secret")).public_key() pub fn name(&self) -> SharedString {
} self.path
.file_name()
fn bound(secret: &str, id: &str) -> LocalRepo { .map(|name| SharedString::from(name.to_string_lossy().into_owned()))
let binding = Nip34Binding { .unwrap_or_else(|| SharedString::from("Untitled"))
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] pub fn local_repo_addr(repo: &LocalRepo) -> Option<RepoAddr> {
fn the_users_own_announcement_is_dropped() { let binding = repo.nip34.as_ref()?;
let own = announcement(KEY, "mine"); let owner = binding.owner?;
let repo = bound(KEY, "mine"); let identifier = binding.identifier.as_deref()?;
let own = std::slice::from_ref(&own); Some(RepoAddr::new(owner, identifier))
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));
}
} }
+57 -25
View File
@@ -55,8 +55,10 @@ pub struct RepoStore {
// Covers NIP-22 comments and statuses without an `a` tag. // Covers NIP-22 comments and statuses without an `a` tag.
root_fetches: HashSet<EventId>, root_fetches: HashSet<EventId>,
synced_maintainers: HashSet<PublicKey>, synced_maintainers: HashSet<PublicKey>,
// In-flight tasks, cancelled when the store drops. // Fire-and-forget publishes, reaped when the next one is queued.
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
// The latest refresh; assigning it cancels the previous one.
refresh_task: Option<Task<Result<(), Error>>>,
_subscription: Option<Subscription>, _subscription: Option<Subscription>,
} }
@@ -108,6 +110,7 @@ impl RepoStore {
root_fetches: HashSet::new(), root_fetches: HashSet::new(),
synced_maintainers: HashSet::new(), synced_maintainers: HashSet::new(),
tasks: Vec::new(), tasks: Vec::new(),
refresh_task: None,
_subscription: Some(subscription), _subscription: Some(subscription),
} }
} }
@@ -139,6 +142,7 @@ impl RepoStore {
root_fetches: HashSet::new(), root_fetches: HashSet::new(),
synced_maintainers: HashSet::new(), synced_maintainers: HashSet::new(),
tasks: Vec::new(), tasks: Vec::new(),
refresh_task: None,
_subscription: None, _subscription: None,
} }
} }
@@ -580,7 +584,7 @@ impl RepoStore {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.refresh_task = Some(task);
} }
pub fn status_of(&self, root: &Event) -> RepoStatus { 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( pub fn open_pull_request(
&mut self, &mut self,
subject: Option<String>, subject: Option<String>,
@@ -708,12 +712,13 @@ impl RepoStore {
cx.notify(); cx.notify();
return Task::ready(Err(Error::msg(message))); 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 owner = addr.public_key();
let euc = self.announcement.as_ref().and_then(|a| a.euc.clone()); let euc = self.announcement.as_ref().and_then(|a| a.euc.clone());
let repo_id = addr.identifier().to_owned(); 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 let push_relays = self
.announcement .announcement
.as_ref() .as_ref()
@@ -721,6 +726,7 @@ impl RepoStore {
.unwrap_or_default(); .unwrap_or_default();
// GRASP-06 hosting falls back to the settings defaults. // GRASP-06 hosting falls back to the settings defaults.
//
// That happens when the author has no published grasp list. // That happens when the author has no published grasp list.
let defaults: Vec<RelayUrl> = { let defaults: Vec<RelayUrl> = {
let settings = settings::SettingsStore::global(cx).read(cx).settings(); let settings = settings::SettingsStore::global(cx).read(cx).settings();
@@ -752,17 +758,18 @@ impl RepoStore {
{ {
Ok(event) => event, Ok(event) => event,
Err(e) => { Err(e) => {
return this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.last_error = Some(e.to_string()); this.last_error = Some(e.to_string());
cx.notify(); cx.notify();
}); })?;
return Err(e);
} }
}; };
// GRASP-06 pushes the tip to the author's own grasp servers at // GRASP-06 pushes the tip to the author's own grasp servers at `/prs/<author-npub>/<repo-id>.git`.
// `/prs/<author-npub>/<repo-id>.git`; contributing to another // Contributing to another project never depends on that project's servers.
// project never depends on that project's servers. Resolve the //
// servers from the author's latest kind-10317 grasp list. // Resolve the servers from the author's latest grasp list.
let author_servers = { let author_servers = {
let query_client = client.clone(); let query_client = client.clone();
let published = cx let published = cx
@@ -790,6 +797,7 @@ impl RepoStore {
} }
targets targets
}; };
let base_targets: Vec<(String, String)> = { let base_targets: Vec<(String, String)> = {
let mut targets = Vec::new(); let mut targets = Vec::new();
for relay in &push_relays { for relay in &push_relays {
@@ -909,10 +917,11 @@ impl RepoStore {
let pr_event = match publish_result { let pr_event = match publish_result {
Ok(event) => event, Ok(event) => event,
Err(e) => { Err(e) => {
return this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.last_error = Some(e.to_string()); this.last_error = Some(e.to_string());
cx.notify(); 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( pub fn open_pull_request_from_refs(
&mut self, &mut self,
repo_path: PathBuf, repo_path: PathBuf,
@@ -939,8 +948,7 @@ impl RepoStore {
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Task<Result<(), Error>> { ) -> Task<Result<(), Error>> {
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
// Regenerate at submit time so the published patch covers the // Regenerate at submit time so the published patch covers the current tip of the compare branch.
// current tip of the compare branch.
let patch = cx let patch = cx
.background_spawn({ .background_spawn({
let repo_path = repo_path.clone(); let repo_path = repo_path.clone();
@@ -958,8 +966,9 @@ impl RepoStore {
Err(error) => bail!("Failed to generate the patch: {error}"), Err(error) => bail!("Failed to generate the patch: {error}"),
}; };
let (done, finished) = flume::bounded::<Result<(), Error>>(1);
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
let task = this.open_pull_request( let publish = this.open_pull_request(
subject, subject,
description, description,
branch_name, branch_name,
@@ -969,8 +978,20 @@ impl RepoStore {
Some(repo_path), Some(repo_path),
cx, 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(()) Ok(())
}); });
self.tasks.push(task); self.tasks.push(task);
} }
@@ -1238,12 +1260,15 @@ impl RepoStore {
cx.notify(); cx.notify();
cx.spawn(async move |this, cx| { 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; let result = push.await;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.pushing = false;
this.push_steps.clear();
match &result { match &result {
Ok(outcome) => { Ok(outcome) => {
this.last_error = None; this.last_error = None;
@@ -1273,6 +1298,7 @@ impl RepoStore {
cx.notify(); cx.notify();
})?; })?;
guard.abort();
result.map(|_| ()) result.map(|_| ())
}) })
} }
@@ -1331,11 +1357,14 @@ impl RepoStore {
}; };
cx.spawn(async move |this, cx| { 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; let result = clone.await;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.cloning = false;
match &result { match &result {
Ok(()) => { Ok(()) => {
let checkouts = CheckoutsStore::global(cx); let checkouts = CheckoutsStore::global(cx);
@@ -1351,6 +1380,8 @@ impl RepoStore {
cx.notify(); cx.notify();
})?; })?;
guard.abort();
result result
}) })
} }
@@ -1410,6 +1441,7 @@ impl RepoStore {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.tasks.push(task);
} }
} }
@@ -1453,7 +1485,7 @@ fn resolve_statuses(
} }
/// Publish a patch series as a sequence of `git/patch` events. /// 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<S>( async fn publish_patch_series<S>(
client: &Client, client: &Client,
signer: &S, signer: &S,
+14 -7
View File
@@ -223,8 +223,7 @@ impl RepoListStore {
} }
} }
// Unbounded, unlike the windowed activity query above, so totals // Unbounded, unlike the windowed activity query above, so totals are exact.
// are exact.
let mut counts: HashMap<RepoAddr, RepoActivityCounts> = HashMap::new(); let mut counts: HashMap<RepoAddr, RepoActivityCounts> = HashMap::new();
let count_filter = let count_filter =
Filter::new().kinds([Kind::GitIssue, Kind::GitPullRequest, Kind::GitPatch]); Filter::new().kinds([Kind::GitIssue, Kind::GitPullRequest, Kind::GitPatch]);
@@ -255,25 +254,33 @@ impl RepoListStore {
cx.spawn(async move |this, cx| { cx.spawn(async move |this, cx| {
let (announcements, last_activity, counts) = match work.await { let (announcements, last_activity, counts) = match work.await {
Ok(results) => results, Ok(results) => results,
Err(_) => { Err(error) => {
return this.update(cx, |this, _cx| { log::warn!("failed to refresh the repository list: {error}");
this.refresh.abort(); return this.update(cx, |this, _cx| this.refresh.abort());
});
} }
}; };
let again = this.update(cx, |this, cx| { 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.announcements = Arc::new(announcements);
this.last_activity = Arc::new(last_activity); this.last_activity = Arc::new(last_activity);
this.counts = Arc::new(counts); this.counts = Arc::new(counts);
this.sync_own_repo_states(cx); this.sync_own_repo_states(cx);
if changed {
cx.notify(); cx.notify();
}
this.refresh.finish() this.refresh.finish()
})?; })?;
if again { if again {
this.update(cx, |this, cx| this.refresh(cx))?; this.update(cx, |this, cx| {
this.refresh(cx);
})?;
} }
Ok(()) Ok(())
+5 -7
View File
@@ -282,7 +282,9 @@ impl SyncState {
if !missing.is_empty() { if !missing.is_empty() {
let (mode, policy) = (self.mode.clone(), self.policy); 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.mode = mode;
self.policy = policy; self.policy = policy;
} }
@@ -295,9 +297,7 @@ impl SyncState {
Self::build(repo_id, &self.refs, self.head.as_deref()) Self::build(repo_id, &self.refs, self.head.as_deref())
} }
/// Push the state event and objects to the grasp servers. /// Push the state event and objects to the grasp servers, calling `on_step` for each step.
///
/// Calling `on_step` for each step.
pub async fn push_to_grasps<P>( pub async fn push_to_grasps<P>(
&self, &self,
client: &Client, client: &Client,
@@ -446,9 +446,7 @@ impl SyncState {
Ok(outcome) Ok(outcome)
} }
/// Announce the repository and push the state and objects to the grasp servers. /// Announces the repository and pushes state and objects; the caller signs, so it can retract.
///
/// Both events are signed by the caller, so a failure at the call site can retract the announcement by id.
pub async fn announce_and_push<P>( pub async fn announce_and_push<P>(
&self, &self,
client: &Client, client: &Client,
+13 -7
View File
@@ -40,7 +40,9 @@ pub struct SyncStatusStore {
pass_pending: bool, pass_pending: bool,
poll_pending: bool, poll_pending: bool,
sender: Sender<()>, sender: Sender<()>,
tasks: Vec<Task<Result<(), Error>>>, _wake_task: Task<Result<(), Error>>,
pass_task: Option<Task<Result<(), Error>>>,
poll_task: Option<Task<Result<(), Error>>>,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
} }
@@ -96,7 +98,9 @@ impl SyncStatusStore {
in_flight: false, in_flight: false,
pass_pending: false, pass_pending: false,
poll_pending: false, poll_pending: false,
tasks: vec![task], _wake_task: task,
pass_task: None,
poll_task: None,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
} }
@@ -204,7 +208,7 @@ impl SyncStatusStore {
Ok::<_, Error>(updates) 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. // Reset the slot even on failure, or every later pass folds forever.
let updates = match work.await { let updates = match work.await {
Ok(updates) => updates, Ok(updates) => updates,
@@ -240,7 +244,7 @@ impl SyncStatusStore {
} }
self.poll_pending = true; 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; cx.background_executor().timer(SYNC_POLL).await;
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
@@ -319,9 +323,7 @@ impl SyncStatusDirectory {
.unwrap_or(0) .unwrap_or(0)
} }
/// Commit ids missing on Nostr, mapped to the checkout that holds them. /// Commit ids missing on Nostr, mapped to their checkout; restricted to `checkout` if tracked.
///
/// When `checkout` matches a tracked checkout, only that checkout contributes.
pub fn ahead_commits_of( pub fn ahead_commits_of(
&self, &self,
addr: &RepoAddr, addr: &RepoAddr,
@@ -358,6 +360,10 @@ impl SyncStatusDirectory {
} }
fn queue(&self, addr: &RepoAddr, cx: &App) { fn queue(&self, addr: &RepoAddr, cx: &App) {
if self.statuses.contains_key(addr) {
return;
}
if self.with_pending(|pending| pending.insert(addr.clone())) { if self.with_pending(|pending| pending.insert(addr.clone())) {
let store = SyncStatusStore::global(cx); let store = SyncStatusStore::global(cx);
store.read(cx).probe([addr.clone()]); store.read(cx).probe([addr.clone()]);
+18
View File
@@ -272,6 +272,24 @@ where
} }
} }
/// Replaces the value without reporting it through `on_change`.
pub fn set_selected_silent(
&mut self,
value: Option<T>,
window: &mut Window,
cx: &mut Context<Self>,
) {
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. /// Replaces the choice list and re-runs the current filter.
pub fn set_options(&mut self, options: Vec<ComboboxOption<T>>, cx: &mut Context<Self>) { pub fn set_options(&mut self, options: Vec<ComboboxOption<T>>, cx: &mut Context<Self>) {
self.options = options; self.options = options;
+1 -2
View File
@@ -1,7 +1,6 @@
use nostr::prelude::*; use nostr::prelude::*;
/// Compare git URLs ignoring scheme, trailing `.git` and path slashes, /// Compares git URLs ignoring scheme, trailing `.git` and slashes, so grasp matches https.
/// so a grasp announce URL matches its https origin.
pub fn same_repo_url(a: &str, b: &str) -> bool { pub fn same_repo_url(a: &str, b: &str) -> bool {
match (url_identity(a), url_identity(b)) { match (url_identity(a), url_identity(b)) {
(Some(a), Some(b)) => a == b, (Some(a), Some(b)) => a == b,
+1 -1
View File
@@ -4,7 +4,7 @@ pub fn sort_newest_first(events: &mut [Event]) {
events.sort_by(|a, b| { events.sort_by(|a, b| {
b.created_at b.created_at
.cmp(&a.created_at) .cmp(&a.created_at)
.then_with(|| b.id.to_hex().cmp(&a.id.to_hex())) .then_with(|| b.id.cmp(&a.id))
}); });
} }
+10 -4
View File
@@ -50,7 +50,7 @@ fn main() {
cx.on_action(|_: &Quit, cx| cx.quit()); cx.on_action(|_: &Quit, cx| cx.quit());
cx.set_app_identity("info.reya.signed", "Signed"); 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); SettingsStore::set_global(store.clone(), cx);
let settings = store.read(cx).settings().clone(); let settings = store.read(cx).settings().clone();
@@ -64,12 +64,16 @@ fn main() {
tracing::warn!("failed to create repos dir: {error}"); tracing::warn!("failed to create repos dir: {error}");
} }
signed_state::init( if let Err(error) = signed_state::init(
paths::nostr_dir(), paths::nostr_dir(),
paths::repos_dir().clone(), paths::repos_dir().to_path_buf(),
settings.local_repos.scan_paths.clone(), settings.local_repos.scan_paths.clone(),
cx, cx,
); ) {
tracing::error!("failed to initialize application state: {error:#}");
cx.quit();
return;
}
metadata::init(cx); metadata::init(cx);
@@ -106,6 +110,8 @@ fn main() {
signed_app::root(window, cx) signed_app::root(window, cx)
}) { }) {
tracing::error!("failed to open window: {error}"); tracing::error!("failed to open window: {error}");
cx.quit();
return;
} }
cx.activate(true); cx.activate(true);
}); });