From 037728ffe9ec243222d7e8ff654ea88205e1a7df Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 14 Sep 2026 08:08:19 +0700 Subject: [PATCH 1/8] extract local repos --- crates/signed_state/src/checkouts.rs | 3 +- crates/signed_state/src/lib.rs | 4 +- crates/signed_state/src/local_repos.rs | 105 +++++++++++++++++++++++++ crates/signed_state/src/repos.rs | 103 +----------------------- 4 files changed, 111 insertions(+), 104 deletions(-) create mode 100644 crates/signed_state/src/local_repos.rs diff --git a/crates/signed_state/src/checkouts.rs b/crates/signed_state/src/checkouts.rs index 52d0214..2b01d06 100644 --- a/crates/signed_state/src/checkouts.rs +++ b/crates/signed_state/src/checkouts.rs @@ -10,8 +10,9 @@ use signed_core::{Announcement, RepoAddr}; use crate::backend::{Backend, BackendEvent}; use crate::git_store::repo_mirror_root; +use crate::local_repos::LocalReposStore; use crate::refresh::{RefreshGate, RefreshRequest}; -use crate::repos::{LocalReposStore, RepoListStore}; +use crate::repos::RepoListStore; const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300); diff --git a/crates/signed_state/src/lib.rs b/crates/signed_state/src/lib.rs index 97afe9f..a936dd9 100644 --- a/crates/signed_state/src/lib.rs +++ b/crates/signed_state/src/lib.rs @@ -2,6 +2,7 @@ mod backend; mod checkouts; mod git_store; mod inbox; +mod local_repos; mod profile; mod refresh; mod repo; @@ -15,11 +16,12 @@ use git_store::set_git_cache; pub use git_store::{ensure_repo_mirror, open_repo_mirror, repo_mirror_path}; use gpui::{App, AppContext}; pub use inbox::{Inbox, query_inbox}; +pub use local_repos::LocalReposStore; pub use nostr_sdk::prelude::Timestamp; pub use profile::{Profile, ProfileStore}; pub use refresh::{RefreshGate, RefreshRequest}; pub use repo::RepoStore; -pub use repos::{LocalReposStore, RepoActivityCounts, RepoListStore}; +pub use repos::{RepoActivityCounts, RepoListStore}; use signed_nostr::new_backend; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/signed_state/src/local_repos.rs b/crates/signed_state/src/local_repos.rs new file mode 100644 index 0000000..95b6a55 --- /dev/null +++ b/crates/signed_state/src/local_repos.rs @@ -0,0 +1,105 @@ +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use anyhow::Error; +use gpui::{App, AppContext, Context, Entity, Global, Task}; +use signed_git::find_git_repos; + +struct GlobalLocalReposStore(Entity); + +impl Global for GlobalLocalReposStore {} + +/// Store of the git repositories discovered under a set of scan paths. +pub struct LocalReposStore { + pub roots: Arc>, + /// Git repositories discovered under [`Self::roots`], sorted by path. + pub repos: Arc>, + pub scanning: bool, + scan_dirty: bool, +} + +impl LocalReposStore { + pub fn global(cx: &App) -> Entity { + cx.global::().0.clone() + } + + pub(crate) fn set_global(entity: Entity, cx: &mut App) { + cx.set_global(GlobalLocalReposStore(entity)); + } + + pub fn new(roots: Vec, cx: &mut Context) -> Self { + let weak = cx.entity().downgrade(); + cx.defer(move |cx| { + if let Err(error) = weak.update(cx, |this, cx| this.rescan(cx)) { + log::warn!("local repos store dropped before initial scan could run: {error}"); + } + }); + + Self { + roots: Arc::new(roots), + repos: Arc::new(Vec::new()), + scanning: false, + scan_dirty: false, + } + } + + /// Forget a repository that has just been published to NIP-34. + pub fn remove(&mut self, path: &Path, cx: &mut Context) { + self.repos = Arc::new( + self.repos + .iter() + .filter(|repo| repo.as_path() != path) + .cloned() + .collect(), + ); + cx.notify(); + } + + pub fn rescan(&mut self, cx: &mut Context) { + if self.scanning { + self.scan_dirty = true; + return; + } + + if self.roots.is_empty() { + return; + } + + self.scanning = true; + cx.notify(); + + let roots = self.roots.clone(); + + let work = cx.background_spawn(async move { + let mut repos = Vec::new(); + for root in roots.iter() { + repos.extend(find_git_repos(root)); + } + repos.sort(); + repos.dedup(); + repos + }); + + let task: Task> = cx.spawn(async move |this, cx| { + let repos = work.await; + let again = this.update(cx, |this, cx| { + this.repos = Arc::new(repos); + this.scanning = false; + cx.notify(); + + let dirty = this.scan_dirty; + this.scan_dirty = false; + dirty + })?; + + // Scans requested while this one ran are coalesced into one follow-up scan. + if again { + this.update(cx, |this, cx| this.rescan(cx))?; + } + + Ok(()) + }); + + task.detach(); + } +} diff --git a/crates/signed_state/src/repos.rs b/crates/signed_state/src/repos.rs index be1fca7..3c4758f 100644 --- a/crates/signed_state/src/repos.rs +++ b/crates/signed_state/src/repos.rs @@ -1,116 +1,15 @@ use std::collections::HashMap; -use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; use anyhow::Error; -use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task}; +use gpui::{App, AppContext, Context, Entity, Global, Subscription}; use nostr_sdk::prelude::*; use signed_core::{Announcement, Deletions, RepoAddr, filters, repo_addr}; -use signed_git::find_git_repos; use crate::backend::{Backend, BackendEvent}; use crate::refresh::{RefreshGate, RefreshRequest}; -struct GlobalLocalReposStore(Entity); - -impl Global for GlobalLocalReposStore {} - -/// Store of the git repositories discovered under a set of scan paths. -pub struct LocalReposStore { - pub roots: Arc>, - /// Git repositories discovered under [`Self::roots`], sorted by path. - pub repos: Arc>, - pub scanning: bool, - scan_dirty: bool, -} - -impl LocalReposStore { - pub fn global(cx: &App) -> Entity { - cx.global::().0.clone() - } - - pub(crate) fn set_global(entity: Entity, cx: &mut App) { - cx.set_global(GlobalLocalReposStore(entity)); - } - - pub fn new(roots: Vec, cx: &mut Context) -> Self { - let weak = cx.entity().downgrade(); - cx.defer(move |cx| { - if let Err(error) = weak.update(cx, |this, cx| this.rescan(cx)) { - log::warn!("local repos store dropped before initial scan could run: {error}"); - } - }); - - Self { - roots: Arc::new(roots), - repos: Arc::new(Vec::new()), - scanning: false, - scan_dirty: false, - } - } - - /// Forget a repository that has just been published to NIP-34. - pub fn remove(&mut self, path: &Path, cx: &mut Context) { - self.repos = Arc::new( - self.repos - .iter() - .filter(|repo| repo.as_path() != path) - .cloned() - .collect(), - ); - cx.notify(); - } - - pub fn rescan(&mut self, cx: &mut Context) { - if self.scanning { - self.scan_dirty = true; - return; - } - - if self.roots.is_empty() { - return; - } - - self.scanning = true; - cx.notify(); - - let roots = self.roots.clone(); - - let work = cx.background_spawn(async move { - let mut repos = Vec::new(); - for root in roots.iter() { - repos.extend(find_git_repos(root)); - } - repos.sort(); - repos.dedup(); - repos - }); - - let task: Task> = cx.spawn(async move |this, cx| { - let repos = work.await; - let again = this.update(cx, |this, cx| { - this.repos = Arc::new(repos); - this.scanning = false; - cx.notify(); - - let dirty = this.scan_dirty; - this.scan_dirty = false; - dirty - })?; - - // Scans requested while this one ran are coalesced into one follow-up scan. - if again { - this.update(cx, |this, cx| this.rescan(cx))?; - } - - Ok(()) - }); - - task.detach(); - } -} - /// How far back activity events count toward a repository's last activity. const ACTIVITY_WINDOW: Duration = Duration::from_secs(90 * 86_400); -- 2.54.0 From e556654be83fbb0d18af4225510aa0dded4be5cd Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 14 Sep 2026 08:44:19 +0700 Subject: [PATCH 2/8] add nip34 detector --- Cargo.lock | 2 + crates/signed_git/Cargo.toml | 2 + crates/signed_git/src/lib.rs | 2 + crates/signed_git/src/nip34.rs | 428 +++++++++++++++++++++++++++++ docs/local-repo-nip34-detection.md | 307 +++++++++++++++++++++ 5 files changed, 741 insertions(+) create mode 100644 crates/signed_git/src/nip34.rs create mode 100644 docs/local-repo-nip34-detection.md diff --git a/Cargo.lock b/Cargo.lock index 7a27540..a364b65 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7981,6 +7981,8 @@ dependencies = [ "gix-worktree-state", "ignore", "nostr", + "serde", + "serde_json", "signed_core", "tempfile", ] diff --git a/crates/signed_git/Cargo.toml b/crates/signed_git/Cargo.toml index a4cd750..d5992cb 100644 --- a/crates/signed_git/Cargo.toml +++ b/crates/signed_git/Cargo.toml @@ -8,6 +8,8 @@ publish.workspace = true signed_core = { path = "../signed_core" } nostr.workspace = true +serde.workspace = true +serde_json.workspace = true gix = { workspace = true, features = ["revision", "blob-diff"] } gix-worktree = "0.56" gix-worktree-state = "0.34" diff --git a/crates/signed_git/src/lib.rs b/crates/signed_git/src/lib.rs index 5d8dd65..efeb1ba 100644 --- a/crates/signed_git/src/lib.rs +++ b/crates/signed_git/src/lib.rs @@ -1,6 +1,7 @@ mod cache; mod diff; mod history; +mod nip34; mod patch; mod remote; mod repo; @@ -19,6 +20,7 @@ pub use history::{ CommitList, FileCommit, MAX_LISTED_COMMITS, all_commits, head_commit, worktree_all_commits, worktree_commit, worktree_commit_range_commits, worktree_last_commits, }; +pub use nip34::{GraspSignals, Nip34Binding, Nip34Kind, detect_nip34, is_grasp_url}; pub use patch::{ apply_patch, format_patch_between, patch_commits, patch_diffs, split_patch_series, }; diff --git a/crates/signed_git/src/nip34.rs b/crates/signed_git/src/nip34.rs new file mode 100644 index 0000000..cd7ebc7 --- /dev/null +++ b/crates/signed_git/src/nip34.rs @@ -0,0 +1,428 @@ +use std::path::Path; + +use gix::bstr::ByteSlice; +use nostr::prelude::*; + +/// The kind of NIP-34 relationship a local repository has on disk. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Nip34Kind { + /// Bound to a NIP-34 coordinate, by `nak`'s `nip34.json` or `ngit`'s `nostr.repo`. + Initialized, + /// Cloned from a `nostr://` remote but never initialized locally. + Cloned, + /// Nostr tooling touched the repository but no binding is recoverable. + ToolingOnly, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct GraspSignals { + pub nip34_json: bool, + pub nip34_excluded: bool, + pub nostr_repo_config: bool, + pub nostr_remote: bool, + pub grasp_remote: bool, + /// `nip34_grasp_remote` is the `nak`-specific `nip34/grasp/` remote name. + pub nip34_grasp_remote: bool, + pub nip34_state_refs: bool, + pub nostr_cache: bool, + pub nostr_aux_config: bool, + pub maintainers_yaml: bool, +} + +impl GraspSignals { + pub fn any(&self) -> bool { + *self != Self::default() + } +} + +/// What a local repository's on-disk state says about its NIP-34 binding. +#[derive(Debug, Clone)] +pub struct Nip34Binding { + pub kind: Nip34Kind, + pub signals: GraspSignals, + /// Coordinate owner and identifier, from `nip34.json` or `nostr.repo`. + pub owner: Option, + pub identifier: Option, + pub grasp_urls: Vec, +} + +#[derive(serde::Deserialize)] +struct Nip34Json { + identifier: Option, + owner: Option, +} + +pub fn detect_nip34(repo_path: &Path) -> Option { + let repo = gix::open(repo_path).ok()?; + let common_dir = repo.common_dir().to_path_buf(); + let workdir = repo.workdir().map(Path::to_path_buf); + + let mut signals = GraspSignals::default(); + let mut owner: Option = None; + let mut identifier: Option = None; + let mut grasp_urls: Vec = Vec::new(); + + if let Some(workdir) = &workdir { + if let Ok(bytes) = std::fs::read(workdir.join("nip34.json")) + && let Ok(config) = serde_json::from_slice::(&bytes) + { + signals.nip34_json = true; + identifier = config.identifier.and_then(non_empty); + owner = config + .owner + .as_deref() + .and_then(|value| PublicKey::parse(value).ok()); + } + + if workdir.join("maintainers.yaml").is_file() { + signals.maintainers_yaml = true; + } + } + + if let Ok(exclude) = std::fs::read_to_string(common_dir.join("info/exclude")) + && exclude.contains("nip34.json") + { + signals.nip34_excluded = true; + } + + // `ngit` keeps its repository event cache in the Git common directory. + if common_dir.join("nostr-cache.lmdb").is_file() { + signals.nostr_cache = true; + } + + // `ngit` reads and writes `nostr.repo` at repository-local scope only. + if let Ok(config) = gix::config::File::from_path_no_includes( + common_dir.join("config"), + gix::config::Source::Local, + ) { + if let Some(value) = config.string("nostr.repo") + && let Some((key, id)) = coordinate_from_naddr(&value.to_str_lossy()) + { + signals.nostr_repo_config = true; + owner = Some(key); + identifier = Some(id); + } + + for key in ["nostr.repo-relay-only", "nostr.nostate", "nostr.private"] { + if config.string(key).is_some() { + signals.nostr_aux_config = true; + } + } + + if let Some(sections) = config.sections_by_name("remote") { + for section in sections { + let Some(name) = section.header().subsection_name() else { + continue; + }; + let nak_grasp_remote = name.to_str_lossy().starts_with("nip34/grasp/"); + + for url in section.values("url") { + let url = url.to_str_lossy(); + + if url.starts_with("nostr://") { + signals.nostr_remote = true; + // Strong markers win; only fill an empty binding. + if owner.is_none() + && identifier.is_none() + && let Some((key, id)) = parse_nostr_url(&url) + { + owner = Some(key); + identifier = Some(id); + } + } + + if is_grasp_url(&url) { + signals.grasp_remote = true; + signals.nip34_grasp_remote |= nak_grasp_remote; + grasp_urls.push(url.to_string()); + + if owner.is_none() + && identifier.is_none() + && let Some((key, id)) = grasp_parts(&url) + { + owner = Some(key); + identifier = Some(id); + } + } + } + } + } + } + + // `nak` materializes a kind-30618 state as `refs/heads/nip34/state/*`. + if let Ok(platform) = repo.references() + && let Ok(mut refs) = platform.prefixed(b"refs/heads/nip34/state/") + && refs.next().is_some() + { + signals.nip34_state_refs = true; + } + + if !signals.any() { + return None; + } + + let kind = if signals.nip34_json + || signals.nostr_repo_config + || signals.nip34_grasp_remote + || signals.nip34_state_refs + { + Nip34Kind::Initialized + } else if signals.nostr_remote { + Nip34Kind::Cloned + } else { + Nip34Kind::ToolingOnly + }; + + Some(Nip34Binding { + kind, + signals, + owner, + identifier, + grasp_urls, + }) +} + +/// Mirrors `nak`'s `IsGraspURL`: two path segments, a path of at least 65 bytes, +/// and a first segment that decodes as an `npub`. +pub fn is_grasp_url(url: &str) -> bool { + let Ok(parsed) = Url::parse(url) else { + return false; + }; + + if !matches!(parsed.scheme(), "http" | "https" | "grasp") { + return false; + } + + let path = parsed.path(); + if path.matches('/').count() != 2 || path.len() < 65 { + return false; + } + + grasp_parts(url).is_some() +} + +fn grasp_parts(url: &str) -> Option<(PublicKey, String)> { + let parsed = Url::parse(url).ok()?; + let mut segments = parsed.path_segments()?.filter(|part| !part.is_empty()); + + let owner = PublicKey::parse(segments.next()?).ok()?; + let identifier = non_empty(segments.next()?.trim_end_matches(".git"))?; + + Some((owner, identifier)) +} + +fn coordinate_from_naddr(value: &str) -> Option<(PublicKey, String)> { + let coordinate = Nip19Coordinate::from_bech32(value).ok()?; + if coordinate.kind != Kind::GitRepoAnnouncement { + return None; + } + + let identifier = non_empty(coordinate.identifier.clone())?; + Some((coordinate.public_key, identifier)) +} + +/// Handles a bare `naddr`, an `npub`, and the optional `[ssh-key-file@]`, +/// `[protocol/]` and `[relay/]` components. An `nip05` owner yields no binding. +fn parse_nostr_url(url: &str) -> Option<(PublicKey, String)> { + let rest = url.strip_prefix("nostr://")?; + + if rest.starts_with("naddr1") { + return coordinate_from_naddr(rest); + } + + let rest = rest.rsplit_once('@').map_or(rest, |(_, after)| after); + let mut parts: Vec<&str> = rest.split('/').filter(|part| !part.is_empty()).collect(); + + if parts + .first() + .is_some_and(|first| matches!(*first, "ssh" | "https" | "http")) + { + parts.remove(0); + } + + // `[owner, (relay), identifier]`. + if parts.len() < 2 { + return None; + } + + let owner = PublicKey::parse(parts[0]).ok()?; + let identifier = non_empty(parts.last()?.trim_end_matches(".git"))?; + + Some((owner, identifier)) +} + +fn non_empty(value: impl Into) -> Option { + let value = value.into(); + (!value.is_empty()).then_some(value) +} + +#[cfg(test)] +mod tests { + use std::process::Command; + + use super::*; + + fn init_repo() -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("repo"); + std::fs::create_dir_all(&path).expect("mkdir"); + git(&path, &["init", "-q"]); + (dir, path) + } + + fn git(dir: &Path, args: &[&str]) { + let status = Command::new("git") + .current_dir(dir) + .env("GIT_AUTHOR_NAME", "Test Author") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test Author") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .env("GIT_EDITOR", "true") + .args(args) + .status() + .expect("spawn git"); + assert!(status.success(), "git {args:?} failed"); + } + + fn key() -> PublicKey { + Keys::generate().public_key() + } + + fn naddr(kind: Kind, owner: PublicKey, identifier: &str) -> String { + let coordinate = Coordinate::new(kind, owner).identifier(identifier); + Nip19Coordinate::new(coordinate, Vec::::new()) + .to_bech32() + .expect("naddr") + } + + #[test] + fn plain_repository_has_no_binding() { + let (_dir, path) = init_repo(); + assert!(detect_nip34(&path).is_none()); + } + + #[test] + fn nip34_json_marks_a_repository_initialized() { + let (_dir, path) = init_repo(); + let owner = key(); + let npub = owner.to_bech32().expect("npub"); + std::fs::write( + path.join("nip34.json"), + format!(r#"{{"identifier":"my-repo","owner":"{npub}"}}"#), + ) + .expect("write"); + + let binding = detect_nip34(&path).expect("binding"); + assert_eq!(binding.kind, Nip34Kind::Initialized); + assert!(binding.signals.nip34_json); + assert_eq!(binding.owner, Some(owner)); + assert_eq!(binding.identifier.as_deref(), Some("my-repo")); + } + + #[test] + fn malformed_nip34_json_is_ignored() { + let (_dir, path) = init_repo(); + std::fs::write(path.join("nip34.json"), b"not json").expect("write"); + + assert!(detect_nip34(&path).is_none()); + } + + #[test] + fn nak_exclude_and_state_refs_are_detected() { + let (_dir, path) = init_repo(); + + std::fs::create_dir_all(path.join(".git/info")).expect("mkdir"); + std::fs::write(path.join(".git/info/exclude"), "nip34.json\n").expect("write"); + + git(&path, &["commit", "-q", "--allow-empty", "-m", "initial"]); + git( + &path, + &["update-ref", "refs/heads/nip34/state/HEAD", "HEAD"], + ); + + let binding = detect_nip34(&path).expect("binding"); + assert_eq!(binding.kind, Nip34Kind::Initialized); + assert!(binding.signals.nip34_excluded); + assert!(binding.signals.nip34_state_refs); + } + + #[test] + fn nostr_repo_config_marks_a_repository_initialized() { + let (_dir, path) = init_repo(); + let owner = key(); + let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo"); + git(&path, &["config", "nostr.repo", &naddr]); + + let binding = detect_nip34(&path).expect("binding"); + assert_eq!(binding.kind, Nip34Kind::Initialized); + assert!(binding.signals.nostr_repo_config); + assert_eq!(binding.owner, Some(owner)); + assert_eq!(binding.identifier.as_deref(), Some("my-repo")); + } + + #[test] + fn nostr_remote_is_a_nip34_clone() { + let (_dir, path) = init_repo(); + let owner = key(); + let npub = owner.to_bech32().expect("npub"); + let url = format!("nostr://{npub}/relay.ngit.dev/my-repo"); + git(&path, &["remote", "add", "origin", &url]); + + let binding = detect_nip34(&path).expect("binding"); + assert_eq!(binding.kind, Nip34Kind::Cloned); + assert!(binding.signals.nostr_remote); + assert_eq!(binding.owner, Some(owner)); + assert_eq!(binding.identifier.as_deref(), Some("my-repo")); + } + + #[test] + fn nak_grasp_remote_marks_a_repository_initialized() { + let (_dir, path) = init_repo(); + let owner = key(); + let npub = owner.to_bech32().expect("npub"); + let url = format!("https://gitnostr.com/{npub}/my-repo.git"); + git( + &path, + &["config", "remote.nip34/grasp/gitnostr.com.url", &url], + ); + + let binding = detect_nip34(&path).expect("binding"); + assert_eq!(binding.kind, Nip34Kind::Initialized); + assert!(binding.signals.nip34_grasp_remote); + assert!(binding.signals.grasp_remote); + assert_eq!(binding.grasp_urls, vec![url]); + assert_eq!(binding.owner, Some(owner)); + assert_eq!(binding.identifier.as_deref(), Some("my-repo")); + } + + #[test] + fn nostr_cache_alone_is_tooling_only() { + let (_dir, path) = init_repo(); + std::fs::write(path.join(".git/nostr-cache.lmdb"), b"cache").expect("write"); + + let binding = detect_nip34(&path).expect("binding"); + assert_eq!(binding.kind, Nip34Kind::ToolingOnly); + assert!(binding.signals.nostr_cache); + } + + #[test] + fn grasp_urls_are_recognised_by_shape() { + let owner = key(); + let npub = owner.to_bech32().expect("npub"); + + assert!(is_grasp_url(&format!( + "https://gitnostr.com/{npub}/my-repo.git" + ))); + assert!(is_grasp_url(&format!( + "grasp://gitnostr.com/{npub}/my-repo.git" + ))); + + assert!(!is_grasp_url("https://gitnostr.com/my-repo.git")); + assert!(!is_grasp_url( + "https://gitnostr.com/not-a-pubkey/my-repo.git" + )); + assert!(!is_grasp_url(&format!( + "ssh://gitnostr.com/{npub}/my-repo.git" + ))); + } +} diff --git a/docs/local-repo-nip34-detection.md b/docs/local-repo-nip34-detection.md new file mode 100644 index 0000000..125e658 --- /dev/null +++ b/docs/local-repo-nip34-detection.md @@ -0,0 +1,307 @@ +# Local repository NIP-34 detection + +Status: plan, not yet implemented. + +## Motivation + +`LocalReposStore::rescan` (`crates/signed_state/src/local_repos.rs`) walks the configured scan +roots with `find_git_repos` (`crates/signed_git/src/scan.rs`) and returns every directory that +contains a `.git` entry. It has no idea whether the repository was already bound to NIP-34 by +another tool (nak, ngit) or by Signed itself. + +Today the sidebar works around this by matching the repository folder name against the signed-in +user's own announcements (`crates/workspace/src/views/sidebar/mod.rs`, in `refresh`). That is +fragile: it only recognises repositories the user already announced, it depends on the folder name +happening to sanitize to the identifier, and it never notices repositories initialized by other +tooling. + +The goal is for every scanned repository to carry a **NIP-34 binding** (or none), so the UI can +label it, link it to its announcement, and stop offering to publish something that is already +published. + +## Decisions taken + +1. **Open as the announced repository.** When a local repository's detected binding resolves to a + coordinate that matches a known announcement, clicking it opens the announced repository (with + the local worktree attached), not a local-only detail view. +2. **Cloned is its own visible state.** A repository cloned from a `nostr://` remote but never + initialized locally is a distinct state from both a plain repository and an initialized one. + +## Detection signals + +nak and ngit use completely different on-disk conventions. There is no shared marker, so both must +be recognised. Everything below is verified against ngit v3.0.1 and nak `master`. + +| # | Signal | Exact location | Meaning | Tool | Strength | +|---|--------|----------------|---------|------|----------| +| 1 | `nip34.json` | `/nip34.json` | Repo initialized. JSON fields: `identifier`, `name`, `description`, `owner`, `grasp-servers[]`, `earliest-unique-commit` | nak | Strong; yields owner + identifier | +| 2 | `nip34.json` line | `/info/exclude` | Corroborates #1 (nak hides the file this way) | nak | Corroborating | +| 3 | `refs/heads/nip34/state/HEAD` and `refs/heads/nip34/state/` | refs | nak materialized a kind-30618 state | nak | Strong | +| 4 | Remote `nip34/grasp/` | `.git/config`: `remote.nip34/grasp/.url` = `https:////.git` | nak `gitSetupRemotes` | nak | Strong; owner + id from the URL | +| 5 | `nostr.repo` = `naddr1…` (kind 30617) | **local** git config | ngit bound the repo to a coordinate | ngit | Strong; yields the coordinate | +| 6 | Remote URL `nostr://…` | `.git/config` | ngit init, or a plain `git clone nostr://…` | ngit | Medium; init **or** clone | +| 7 | `nostr-cache.lmdb` | `/nostr-cache.lmdb` | ngit has run here (also on clone) | ngit | Weak; touched only | +| 8 | `nostr.repo-relay-only`, `nostr.nostate`, `nostr.private` | local git config | ngit auxiliary flags | ngit | Weak | +| 9 | Grasp-shaped remote `https:////.git` (or `grasp://…`) | `.git/config` | Some client registered a grasp remote | unknown | Medium | +| 10 | `maintainers.yaml` | `/maintainers.yaml` | ngit multi-maintainer config | ngit | Weak | + +Notes: + +- ngit has **no** `nip34.json`, and nak has **no** `nostr.repo` config key. The two conventions are + disjoint, so seeing both is essentially impossible; if it happens, prefer #1/#5 (a real binding) + for the coordinate and record both evidence flags. +- `nostr.repo` is written and read at **local** scope by ngit, so detection must read the local + config only, never the merged/global view. +- The grasp URL shape mirrors nak's `IsGraspURL`: exactly two `/` in the path (two segments), total + path length ≥ 65, and the first 63 characters after the leading `/` decode as an `npub`. The + identifier segment conventionally ends in `.git`. +- Signed's own clone URLs use the `grasp://` scheme (see `transport_url` in + `crates/signed_git/src/remote.rs`), so the shape check must accept `grasp://` too. +- A disk-only check cannot prove a repository was *announced*; ngit explicitly has a + "coordinate set, no announcement on relays" state. Detection answers "is this repository bound + to NIP-34", and the relay lookup stays a separate layer. + +## Classification + +```mermaid +flowchart TD + A[Scanned repo] --> B{nip34.json parses?} + B -- yes --> INIT[NIP-34 initialized
nak, owner+id known] + B -- no --> C{nostr.repo decodes
as kind-30617 naddr?} + C -- yes --> INIT2[NIP-34 initialized
ngit, coordinate known] + C -- no --> D{nip34/grasp remote
or nip34/state refs?} + D -- yes --> INIT3[NIP-34 initialized
nak, id from remote URL] + D -- no --> E{nostr:// remote only?} + E -- yes --> CLONE[NIP-34 clone
derive owner+id from URL] + E -- no --> F{lmdb / aux config /
grasp-shaped remote only?} + F -- yes --> TOOL[Nostr tooling seen
binding unclear] + F -- no --> PLAIN[Plain local repository] +``` + +Precedence, in order: + +1. #1 `nip34.json` parses → `Initialized`, owner + identifier known (nak). +2. #5 `nostr.repo` decodes as a kind-30617 `naddr` → `Initialized`, coordinate known (ngit). +3. #3 or #4, without #1/#2 → `Initialized` (nak); derive owner + identifier from the + `nip34/grasp/` remote URL when present. +4. Only #6 `nostr://` remote → `Cloned`; derive owner + identifier from the URL when parseable. +5. Only #7, #8, #9 or #10 → `ToolingOnly`. +6. Nothing → `None`. + +## Data model + +Detection lives in `signed_git` next to the other git plumbing (`scan.rs`, `remote.rs`). It reports +raw on-disk facts plus the nostr identity it can recover; mapping to `RepoAddr` and matching against +announcements happens in `signed_state`, where `RepoAddr` and the announcement list live. + +New file `crates/signed_git/src/nip34.rs`: + +```rust +use std::path::Path; + +use nostr::PublicKey; + +/// The kind of NIP-34 relationship a local repository has on disk. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Nip34Kind { + /// Bound to a NIP-34 coordinate (nak `nip34.json` or ngit `nostr.repo`). + Initialized, + /// Cloned from a `nostr://` remote but never initialized locally. + Cloned, + /// Nostr tooling touched the repository but no binding is recoverable. + ToolingOnly, +} + +/// `nip34_grasp_remote` is the nak-specific `nip34/grasp/` remote name (#4), +/// while `grasp_remote` covers any grasp-shaped remote URL (#9). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct GraspSignals { + pub nip34_json: bool, + pub nip34_excluded: bool, + pub nostr_repo_config: bool, + pub nostr_remote: bool, + pub grasp_remote: bool, + pub nip34_grasp_remote: bool, + pub nip34_state_refs: bool, + pub nostr_cache: bool, + pub nostr_aux_config: bool, + pub maintainers_yaml: bool, +} + +#[derive(Debug, Clone)] +pub struct Nip34Binding { + pub kind: Nip34Kind, + pub signals: GraspSignals, + /// Coordinate owner and identifier, from #1 or #5. + pub owner: Option, + pub identifier: Option, + pub grasp_urls: Vec, +} + +/// Inspect a repository's on-disk state. +/// +/// `None` for a plain repository. Best-effort: unreadable or malformed input is +/// treated as a missing signal, never an error, so a bad repository cannot fail a scan. +pub fn detect_nip34(repo_path: &Path) -> Option; + +/// Whether `url` has the grasp URL shape, `[https|http|grasp]:////.git`. +pub fn is_grasp_url(url: &str) -> bool; +``` + +Implementation notes: + +- Use **gix** (`gix::open`, `config::File::from_path_no_includes`, remote config sections, + `references().prefixed`), not `git` subprocesses: the scan walks many repositories on a + background thread. +- Worktree root via `repo.workdir()`; `.git`-relative paths (`info/exclude`, + `nostr-cache.lmdb`) via `repo.common_dir()`. +- Read `nostr.repo` from the **local** config file only (`repo.common_dir().join("config")`), + mirroring ngit's own scope. +- Parse `nip34.json` with `serde_json`. The `owner` field is an npub in nak's writer but its + validator accepts hex too, so use `PublicKey::parse` (bech32 or hex). +- Decode ngit's `naddr` with the nostr crate's NIP-19 coordinate decoder (`Nip19Coordinate`), and + require kind 30617. +- Add `serde` and `serde_json` to `crates/signed_git/Cargo.toml` (both are already + workspace dependencies). + +`crates/signed_git/src/scan.rs` returns richer entries: + +```rust +pub struct LocalRepo { + pub path: PathBuf, + /// `None` for a plain repository. + pub nip34: Option, +} + +pub fn find_git_repos(root: &Path) -> Vec; +``` + +The existing dedup rules (nested repositories, canonicalize, sort) are unchanged; `detect_nip34` +runs per kept path. Export `LocalRepo`, `Nip34Binding`, `Nip34Kind`, `GraspSignals` from +`signed_git/src/lib.rs`. + +## Action plan + +### Phase 1 — `signed_git` detection (no app behavior change) + +Implemented. + +- [x] `crates/signed_git/Cargo.toml`: add `serde.workspace = true`, `serde_json.workspace = true`. +- [x] `crates/signed_git/src/nip34.rs`: implement `detect_nip34`, `is_grasp_url`, the enums and + structs above. Keep every file/config read fallible-but-ignored: a missing or malformed + input clears only its own flag. +- [x] `crates/signed_git/src/lib.rs`: add `mod nip34;` and re-export the public items. +- [x] Tests in `crates/signed_git/src/nip34.rs` (see Testing). + +### Phase 2 — thread `LocalRepo` through the state layer + +- [ ] `crates/signed_git/src/scan.rs`: change `find_git_repos` to `Vec`; in the walk, + `detect_nip34` each kept path. +- [ ] `crates/signed_git/src/tests.rs`: update `find_git_repos_*` expectations to the new type + (compare `.path`). +- [ ] `crates/signed_state/src/local_repos.rs`: `repos: Arc>`; `remove(&path)` + filters on `.path`; the background scan already returns the richer vector unchanged. +- [ ] `crates/signed_state/src/checkouts.rs` (~`run_refresh`): iterate `.path` instead of bare + paths when collecting `scanned`. +- [ ] `crates/signed_state/src/lib.rs`: re-export `LocalRepo`, `Nip34Binding`, `Nip34Kind` (and + `GraspSignals` if the UI needs the flags). +- [ ] `crates/signed_state/src/local_repos.rs`: add a helper that resolves a binding to a + `RepoAddr` (`signed_core::repo_addr(owner, identifier)`) when both are known. + +### Phase 3 — sidebar: derive the local list and link to announcements + +File: `crates/workspace/src/views/sidebar/mod.rs`. + +- [ ] Replace the folder-name dedupe in `refresh` with a resolution pass over + `LocalReposStore::global(cx).read(cx).repos`: + - For each entry, compute the detected `RepoAddr` when the binding is `Initialized` with + owner + identifier. + - Look the address up in `RepoListStore` announcements. + - If it matches an announcement **already shown** in the sidebar's list (the signed-in + user's own), drop it from the local list to avoid showing it twice. + - If it matches an announcement that is not in the shown list, keep it as a local entry + rendered with the "initialized" badge; clicking opens the announced repository (decision 1). + - Otherwise keep it with a badge derived from the binding kind. +- [ ] Extend the sidebar's local entry model from `Vec` to a small struct carrying the + path, the binding kind, the tool label and the resolved address, so `render_repo_at` can + render the badge and route clicks. +- [ ] Add the badge rendering to the local row in `render_repo_at` (three visible states): + - `Initialized` → "NIP-34 · nak" / "NIP-34 · ngit" + - `Cloned` → "NIP-34 clone" (decision 2, its own visible state) + - `ToolingOnly` → "Nostr tooling" (muted) + - plain → unchanged. + +### Phase 4 — detail view: open as announced, gate the publish CTA + +- [ ] `crates/signed_state/src/repo.rs`: add a constructor that keeps the worktree path while in + NIP-34 mode, e.g. `RepoStore::from_worktree(addr, announcement, path, cx)`, or a small + `set_path`. `RepoStore::announce` already keeps an existing path, so this can be built from + `new` plus assigning the path. Opening a repository must **not** remove it from + `LocalReposStore` (that removal belongs to `apply_announcement`, which only runs on a real + publish). +- [ ] `crates/workspace/src/views/repo/mod.rs`: add `RepoDetailView::new_local_announced(...)` + (or an `Option` parameter on `new_local`) that builds the announced store with + the local worktree attached, then `new_common`. +- [ ] `crates/workspace/src/views/sidebar/mod.rs`: route local-entry clicks through the new + constructor when an announcement matched, and through `open_local_repo` otherwise. +- [ ] `crates/workspace/src/views/repo/mod.rs`: for a `new_local` view whose store carries an + `Initialized` binding, suppress the "publish to NIP-34" call to action and instead show the + owner and identifier. `Cloned` keeps the ability to be adopted/published. + +### Phase 5 — optional: mark Signed's own publications + +Signed's `publish_local_repo` (`crates/signed_state/src/backend.rs`) currently pushes by URL and +writes no on-disk marker, so a repository Signed itself published is not detected on the next scan. +Decide separately whether to write a marker on publish: + +- ngit-compatible and least intrusive: `git config --local nostr.repo `. +- nak-compatible: write `nip34.json` and add it to `.git/info/exclude`. + +Do not write both. This is a behavior change to a third-party convention and should be a +deliberate, separate decision. + +## Edge cases + +- Bare repositories are never scanned (no `.git` entry to match), so their absence as a worktree is + not a problem. Linked worktrees have a `.git` file and are scanned; `gix::open` resolves them and + `info/exclude`, `config` and `nostr-cache.lmdb` live in the shared common dir. +- Submodules are already filtered out by the nested-path rule in `scan.rs`. +- Detection must be cheap and side-effect-free: no network, no writes, no `git` subprocesses. +- Multiple grasp servers produce multiple `nip34/grasp/*` remotes; use the first parseable one for + the coordinate and keep all of them in `grasp_urls`. +- Offline: matching against announcements may find nothing, but the disk badge still shows. Disk + state is authoritative for "bound"; relay state only adds "and announced". +- The scan runs on wasm with empty roots (`init` passes `Vec::new()`), so detection code must not + assume a non-empty root list; no `cfg` gymnastics are needed since it is never reached. + +## Testing + +Unit tests in `crates/signed_git/src/nip34.rs` (use `tempfile` and a small local `git` helper): + +- `nip34.json` with an npub owner → `Initialized`, owner + identifier parsed. +- malformed `nip34.json` → falls back to no #1 signal, does not panic. +- `nostr.repo` set to a kind-30617 `naddr` → `Initialized` with the matching coordinate. +- `origin` = `nostr://npub…/relay/identifier` and no `nostr.repo` → `Cloned`. +- remote `nip34/grasp/` = `https:////.git` → nak remote signal, owner + id + recovered from the URL. +- `refs/heads/nip34/state/HEAD` present and `nip34.json` in `.git/info/exclude` → nak state signals. +- `.git/nostr-cache.lmdb` alone → `ToolingOnly`. +- plain repository → `None`. +- `is_grasp_url`: accept `https://host/npub1…/repo.git` and `grasp://host/npub1…/repo.git`; reject + `https://host/repo.git` (no owner), a first segment that is not a valid `npub`, and an unrelated + scheme such as `ssh://`. + +Integration test in `crates/signed_state`: + +- A scanned repository whose binding resolves to a `RepoAddr` that matches a seeded announcement is + deduped out of the local list when it is the user's own; one with no matching announcement + remains and is labelled. + +Final verification: `cargo check -p signed_git -p signed_state -p workspace` and +`cargo test -p signed_git`. + +## Out of scope + +- Proving a repository is announced on relays. That stays the announcement layer's job. +- Writing markers for Signed-published repositories is Phase 5 and optional. +- Migrating or rewriting other tools' markers (we only read them). -- 2.54.0 From 1a13d4e0d7d382559b40712283be159ce8c9371b Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 14 Sep 2026 08:50:15 +0700 Subject: [PATCH 3/8] update --- crates/signed_git/src/lib.rs | 2 +- crates/signed_git/src/scan.rs | 21 ++++++++++++++++++--- crates/signed_git/src/tests.rs | 5 ++++- crates/signed_state/src/checkouts.rs | 4 +++- crates/signed_state/src/lib.rs | 3 ++- crates/signed_state/src/local_repos.rs | 21 ++++++++++++++++----- crates/workspace/src/views/sidebar/mod.rs | 6 +++--- docs/local-repo-nip34-detection.md | 22 +++++++++++++--------- 8 files changed, 60 insertions(+), 24 deletions(-) diff --git a/crates/signed_git/src/lib.rs b/crates/signed_git/src/lib.rs index efeb1ba..f1eae1f 100644 --- a/crates/signed_git/src/lib.rs +++ b/crates/signed_git/src/lib.rs @@ -34,7 +34,7 @@ pub use repo::{ repo_tags, root_commit, worktree_branches, worktree_current_branch, worktree_ref_exists, worktree_ref_state, }; -pub use scan::find_git_repos; +pub use scan::{LocalRepo, find_git_repos}; pub use worktree::{ WorktreeSnapshot, find_readme, worktree_checkout_branch, worktree_checkout_tag, worktree_commits_ahead, worktree_dirty, worktree_entries, worktree_read, worktree_snapshot, diff --git a/crates/signed_git/src/scan.rs b/crates/signed_git/src/scan.rs index cd16606..6e64fc0 100644 --- a/crates/signed_git/src/scan.rs +++ b/crates/signed_git/src/scan.rs @@ -2,12 +2,21 @@ use std::path::{Path, PathBuf}; use ignore::WalkBuilder; +use crate::nip34::{Nip34Binding, detect_nip34}; + /// Caps nesting so pathological trees can't stall the scan. const SCAN_MAX_DEPTH: usize = 12; -/// Walk `root` recursively and collect the paths of git repositories below it. -/// `.gitignore` and `.ignore` files are honoured. -pub fn find_git_repos(root: &Path) -> Vec { +/// A git repository discovered under a scan root. +#[derive(Debug, Clone)] +pub struct LocalRepo { + pub path: PathBuf, + /// `None` for a plain repository. + pub nip34: Option, +} + +/// Walk `root` recursively and collect the git repositories below it. +pub fn find_git_repos(root: &Path) -> Vec { if !root.is_dir() { return Vec::new(); } @@ -38,4 +47,10 @@ pub fn find_git_repos(root: &Path) -> Vec { } roots + .into_iter() + .map(|path| { + let nip34 = detect_nip34(&path); + LocalRepo { path, nip34 } + }) + .collect() } diff --git a/crates/signed_git/src/tests.rs b/crates/signed_git/src/tests.rs index 890efb3..6f37456 100644 --- a/crates/signed_git/src/tests.rs +++ b/crates/signed_git/src/tests.rs @@ -42,7 +42,10 @@ fn find_git_repos_discovers_repositories_recursively() { std::fs::create_dir_all(outer.join(".git")).unwrap(); std::fs::create_dir_all(outer.join("sub/other/.git")).unwrap(); - let mut found = find_git_repos(root); + let mut found: Vec = find_git_repos(root) + .into_iter() + .map(|repo| repo.path) + .collect(); found.sort(); let mut expected = vec![ diff --git a/crates/signed_state/src/checkouts.rs b/crates/signed_state/src/checkouts.rs index 2b01d06..67e52ce 100644 --- a/crates/signed_state/src/checkouts.rs +++ b/crates/signed_state/src/checkouts.rs @@ -350,7 +350,9 @@ impl CheckoutsStore { // // The facts are the origin URL and the root commit, both CLI reads. let mut facts: Vec<(PathBuf, Option, Option)> = Vec::new(); - for path in scanned.iter() { + for scanned in scanned.iter() { + let path = &scanned.path; + // The browser's mirror clones share the announce URLs and EUCs. They are not user checkouts. if cache_root .as_ref() diff --git a/crates/signed_state/src/lib.rs b/crates/signed_state/src/lib.rs index a936dd9..297578f 100644 --- a/crates/signed_state/src/lib.rs +++ b/crates/signed_state/src/lib.rs @@ -16,12 +16,13 @@ use git_store::set_git_cache; pub use git_store::{ensure_repo_mirror, open_repo_mirror, repo_mirror_path}; use gpui::{App, AppContext}; pub use inbox::{Inbox, query_inbox}; -pub use local_repos::LocalReposStore; +pub use local_repos::{LocalReposStore, local_repo_addr}; pub use nostr_sdk::prelude::Timestamp; pub use profile::{Profile, ProfileStore}; pub use refresh::{RefreshGate, RefreshRequest}; pub use repo::RepoStore; pub use repos::{RepoActivityCounts, RepoListStore}; +pub use signed_git::{GraspSignals, LocalRepo, Nip34Binding, Nip34Kind}; use signed_nostr::new_backend; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/signed_state/src/local_repos.rs b/crates/signed_state/src/local_repos.rs index 95b6a55..85891a3 100644 --- a/crates/signed_state/src/local_repos.rs +++ b/crates/signed_state/src/local_repos.rs @@ -3,7 +3,8 @@ use std::sync::Arc; use anyhow::Error; use gpui::{App, AppContext, Context, Entity, Global, Task}; -use signed_git::find_git_repos; +use signed_core::{RepoAddr, repo_addr}; +use signed_git::{LocalRepo, find_git_repos}; struct GlobalLocalReposStore(Entity); @@ -13,7 +14,7 @@ impl Global for GlobalLocalReposStore {} pub struct LocalReposStore { pub roots: Arc>, /// Git repositories discovered under [`Self::roots`], sorted by path. - pub repos: Arc>, + pub repos: Arc>, pub scanning: bool, scan_dirty: bool, } @@ -48,7 +49,7 @@ impl LocalReposStore { self.repos = Arc::new( self.repos .iter() - .filter(|repo| repo.as_path() != path) + .filter(|repo| repo.path.as_path() != path) .cloned() .collect(), ); @@ -75,8 +76,8 @@ impl LocalReposStore { for root in roots.iter() { repos.extend(find_git_repos(root)); } - repos.sort(); - repos.dedup(); + repos.sort_by(|a, b| a.path.cmp(&b.path)); + repos.dedup_by(|a, b| a.path == b.path); repos }); @@ -103,3 +104,13 @@ impl LocalReposStore { task.detach(); } } + +/// The NIP-34 coordinate a repository's detection resolved, when both the owner +/// and the identifier were recovered. +pub fn local_repo_addr(repo: &LocalRepo) -> Option { + let binding = repo.nip34.as_ref()?; + let owner = binding.owner?; + let identifier = binding.identifier.as_deref()?; + + Some(repo_addr(owner, identifier)) +} diff --git a/crates/workspace/src/views/sidebar/mod.rs b/crates/workspace/src/views/sidebar/mod.rs index 2da0a3e..6d5c063 100644 --- a/crates/workspace/src/views/sidebar/mod.rs +++ b/crates/workspace/src/views/sidebar/mod.rs @@ -132,13 +132,13 @@ impl SidebarPanel { .read(cx) .repos .iter() - .filter(|path| { - let Some(name) = path.file_name() else { + .filter(|repo| { + let Some(name) = repo.path.file_name() else { return true; }; !ids.contains(&identifier_from_name(&name.to_string_lossy())) }) - .cloned() + .map(|repo| repo.path.clone()) .collect() }; diff --git a/docs/local-repo-nip34-detection.md b/docs/local-repo-nip34-detection.md index 125e658..7c7f71f 100644 --- a/docs/local-repo-nip34-detection.md +++ b/docs/local-repo-nip34-detection.md @@ -1,6 +1,6 @@ # Local repository NIP-34 detection -Status: plan, not yet implemented. +Status: Phases 1–2 implemented. Phases 3–5 pending. ## Motivation @@ -195,18 +195,22 @@ Implemented. ### Phase 2 — thread `LocalRepo` through the state layer -- [ ] `crates/signed_git/src/scan.rs`: change `find_git_repos` to `Vec`; in the walk, +Implemented. + +- [x] `crates/signed_git/src/scan.rs`: change `find_git_repos` to `Vec`; in the walk, `detect_nip34` each kept path. -- [ ] `crates/signed_git/src/tests.rs`: update `find_git_repos_*` expectations to the new type +- [x] `crates/signed_git/src/tests.rs`: update `find_git_repos_*` expectations to the new type (compare `.path`). -- [ ] `crates/signed_state/src/local_repos.rs`: `repos: Arc>`; `remove(&path)` +- [x] `crates/signed_state/src/local_repos.rs`: `repos: Arc>`; `remove(&path)` filters on `.path`; the background scan already returns the richer vector unchanged. -- [ ] `crates/signed_state/src/checkouts.rs` (~`run_refresh`): iterate `.path` instead of bare +- [x] `crates/signed_state/src/checkouts.rs` (`run_refresh`): iterate `.path` instead of bare paths when collecting `scanned`. -- [ ] `crates/signed_state/src/lib.rs`: re-export `LocalRepo`, `Nip34Binding`, `Nip34Kind` (and - `GraspSignals` if the UI needs the flags). -- [ ] `crates/signed_state/src/local_repos.rs`: add a helper that resolves a binding to a - `RepoAddr` (`signed_core::repo_addr(owner, identifier)`) when both are known. +- [x] `crates/signed_state/src/lib.rs`: re-export `LocalRepo`, `Nip34Binding`, `Nip34Kind` and + `GraspSignals`. +- [x] `crates/signed_state/src/local_repos.rs`: `local_repo_addr(&LocalRepo) -> Option` + resolves a binding when both owner and identifier are known. +- [x] `crates/workspace/src/views/sidebar/mod.rs`: minimal adaptation of the existing folder-name + dedupe to the new entry type so the tree compiles; the badge/dedupe rewrite is Phase 3. ### Phase 3 — sidebar: derive the local list and link to announcements -- 2.54.0 From c6ada10afa51dd9bf890051fc8c3cc26059f743d Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 14 Sep 2026 08:56:32 +0700 Subject: [PATCH 4/8] update sidebar --- crates/signed_git/src/nip34.rs | 2 +- crates/signed_state/src/lib.rs | 2 +- crates/signed_state/src/local_repos.rs | 144 +++++++++++++++++++++- crates/workspace/src/views/sidebar/mod.rs | 141 ++++++++++++++------- docs/local-repo-nip34-detection.md | 52 ++++---- 5 files changed, 267 insertions(+), 74 deletions(-) diff --git a/crates/signed_git/src/nip34.rs b/crates/signed_git/src/nip34.rs index cd7ebc7..bf58ac2 100644 --- a/crates/signed_git/src/nip34.rs +++ b/crates/signed_git/src/nip34.rs @@ -36,7 +36,7 @@ impl GraspSignals { } /// What a local repository's on-disk state says about its NIP-34 binding. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] pub struct Nip34Binding { pub kind: Nip34Kind, pub signals: GraspSignals, diff --git a/crates/signed_state/src/lib.rs b/crates/signed_state/src/lib.rs index 297578f..323577f 100644 --- a/crates/signed_state/src/lib.rs +++ b/crates/signed_state/src/lib.rs @@ -16,7 +16,7 @@ use git_store::set_git_cache; pub use git_store::{ensure_repo_mirror, open_repo_mirror, repo_mirror_path}; use gpui::{App, AppContext}; pub use inbox::{Inbox, query_inbox}; -pub use local_repos::{LocalReposStore, local_repo_addr}; +pub use local_repos::{LocalReposStore, ResolvedLocalRepo, local_repo_addr, resolve_local_repos}; pub use nostr_sdk::prelude::Timestamp; pub use profile::{Profile, ProfileStore}; pub use refresh::{RefreshGate, RefreshRequest}; diff --git a/crates/signed_state/src/local_repos.rs b/crates/signed_state/src/local_repos.rs index 85891a3..ac2607d 100644 --- a/crates/signed_state/src/local_repos.rs +++ b/crates/signed_state/src/local_repos.rs @@ -1,10 +1,11 @@ +use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::Arc; use anyhow::Error; use gpui::{App, AppContext, Context, Entity, Global, Task}; -use signed_core::{RepoAddr, repo_addr}; -use signed_git::{LocalRepo, find_git_repos}; +use signed_core::{Announcement, RepoAddr, repo_addr}; +use signed_git::{LocalRepo, Nip34Binding, find_git_repos}; struct GlobalLocalReposStore(Entity); @@ -114,3 +115,142 @@ pub fn local_repo_addr(repo: &LocalRepo) -> Option { Some(repo_addr(owner, identifier)) } + +/// A scanned repository resolved against the known announcements. +#[derive(Debug, Clone, PartialEq)] +pub struct ResolvedLocalRepo { + pub path: PathBuf, + /// `None` for a plain repository. + pub nip34: Option, + /// The known announcement this repository is bound to, when one matched. + pub announcement: Option, +} + +/// Resolve the scanned repositories against the known announcements. +pub fn resolve_local_repos( + repos: &[LocalRepo], + known: &[Announcement], + own: &[Announcement], +) -> Vec { + let shown: HashSet = own.iter().map(Announcement::addr).collect(); + + repos + .iter() + .filter_map(|repo| { + let addr = local_repo_addr(repo); + + if let Some(addr) = &addr + && shown.contains(addr) + { + return None; + } + + let announcement = addr + .as_ref() + .and_then(|addr| { + known + .iter() + .find(|announcement| announcement.addr() == *addr) + }) + .cloned(); + + Some(ResolvedLocalRepo { + path: repo.path.clone(), + nip34: repo.nip34.clone(), + announcement, + }) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use nostr::prelude::*; + use signed_git::{GraspSignals, Nip34Kind}; + + use super::*; + + const KEY: &str = "0000000000000000000000000000000000000000000000000000000000000001"; + const OTHER_KEY: &str = "0000000000000000000000000000000000000000000000000000000000000002"; + + fn announcement(secret: &str, id: &str) -> Announcement { + let keys = Keys::new(SecretKey::from_hex(secret).expect("secret")); + let tag = Tag::parse(vec!["d", id]).expect("tag"); + let event = EventBuilder::new(Kind::GitRepoAnnouncement, "") + .tags(vec![tag]) + .finalize(&keys) + .expect("signed"); + + Announcement::from_event(&event).expect("parsed") + } + + fn owner(secret: &str) -> PublicKey { + Keys::new(SecretKey::from_hex(secret).expect("secret")).public_key() + } + + fn bound(secret: &str, id: &str) -> LocalRepo { + let binding = Nip34Binding { + kind: Nip34Kind::Initialized, + signals: GraspSignals { + nip34_json: true, + ..Default::default() + }, + owner: Some(owner(secret)), + identifier: Some(id.to_owned()), + grasp_urls: Vec::new(), + }; + + LocalRepo { + path: PathBuf::from(id), + nip34: Some(binding), + } + } + + #[test] + fn the_users_own_announcement_is_dropped() { + let own = announcement(KEY, "mine"); + let repo = bound(KEY, "mine"); + + let own = std::slice::from_ref(&own); + assert!(resolve_local_repos(&[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 = resolve_local_repos(&[repo], std::slice::from_ref(&known), &[]); + + assert_eq!(resolved.len(), 1); + assert_eq!(resolved[0].announcement.as_ref(), Some(&known)); + } + + #[test] + fn an_unmatched_repository_keeps_its_binding() { + let repo = bound(KEY, "unlisted"); + + let resolved = resolve_local_repos(&[repo], &[], &[]); + + assert_eq!(resolved.len(), 1); + assert!(resolved[0].announcement.is_none()); + assert_eq!( + resolved[0].nip34.as_ref().map(|binding| binding.kind), + Some(Nip34Kind::Initialized) + ); + } + + #[test] + fn a_plain_repository_is_kept_without_a_binding() { + let repo = LocalRepo { + path: PathBuf::from("plain"), + nip34: None, + }; + + let resolved = resolve_local_repos(&[repo], &[], &[]); + + assert_eq!(resolved.len(), 1); + assert!(resolved[0].nip34.is_none()); + assert!(resolved[0].announcement.is_none()); + } +} diff --git a/crates/workspace/src/views/sidebar/mod.rs b/crates/workspace/src/views/sidebar/mod.rs index 6d5c063..8dc7b99 100644 --- a/crates/workspace/src/views/sidebar/mod.rs +++ b/crates/workspace/src/views/sidebar/mod.rs @@ -1,6 +1,6 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::ops::Range; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; @@ -10,7 +10,7 @@ use dock::{ }; use gpui::prelude::*; use gpui::{ - AnyElement, App, Context, Div, EventEmitter, FocusHandle, Focusable, ObjectFit, Render, + AnyElement, App, Context, Div, EventEmitter, FocusHandle, Focusable, Hsla, ObjectFit, Render, SharedString, Subscription, WeakEntity, Window, div, img, px, relative, uniform_list, white, }; use gpui_base::Button as BaseButton; @@ -18,9 +18,10 @@ use gpui_component::button::{Button, ButtonVariants}; use gpui_component::input::InputState; use gpui_component::{ActiveTheme, Icon, IconName, Sizable, StyledExt, h_flex, v_flex}; use nostr::prelude::RelayUrl; -use signed_core::{Announcement, RepoAddr, identifier_from_name}; +use signed_core::{Announcement, RepoAddr}; use signed_state::{ - Backend, BackendEvent, CheckoutsStore, LocalReposStore, Profile, ProfileStore, RepoListStore, + Backend, BackendEvent, CheckoutsStore, LocalReposStore, Nip34Binding, Nip34Kind, Profile, + ProfileStore, RepoListStore, ResolvedLocalRepo, resolve_local_repos, }; use signed_ui::{NavItem, PixelAvatar, UserAvatar, title_bar_drag_handlers}; @@ -35,18 +36,31 @@ mod settings_dialog; use self::onboarding_dialog::OnboardingState; +/// The tool that bound a repository, `"nak"` or `"ngit"`. +fn local_tool(binding: &Nip34Binding) -> Option<&'static str> { + let signals = &binding.signals; + + if signals.nip34_json || signals.nip34_grasp_remote || signals.nip34_state_refs { + Some("nak") + } else if signals.nostr_repo_config { + Some("ngit") + } else { + None + } +} + pub struct SidebarPanel { focus_handle: FocusHandle, dock_area: WeakEntity, inbox: Option>, explore: Option>, banner: SharedString, - /// The signed-in user's announced repositories, newest first. + /// User's announced repositories. announcements: Arc>, /// Local repositories found by the scan that are not announced yet. - local_repos: Arc>, + local_repos: Arc>, scanning: bool, - /// Unpushed commit counts per announced repository, shown as row badges. + /// Unpushed commit counts per announced repository. unpushed: HashMap, _subscriptions: Vec, } @@ -116,30 +130,21 @@ impl SidebarPanel { let backend = Backend::global(cx); let user = backend.read(cx).current_user(); - let repo_list = RepoListStore::global(cx); - let announcements = user - .as_ref() - .map(|user| repo_list.read(cx).announcements_of(user)) - .unwrap_or_default(); + let (announcements, local_repos, scanning) = { + let repo_list = RepoListStore::global(cx); + let repo_list = repo_list.read(cx); - // Drop a scanned repository once the user announces it, so it is not listed twice. - let local = LocalReposStore::global(cx); - let scanning = local.read(cx).scanning; + let announcements = user + .as_ref() + .map(|user| repo_list.announcements_of(user)) + .unwrap_or_default(); - let local_repos = { - let ids: HashSet = announcements.iter().map(|a| a.id.clone()).collect(); - local - .read(cx) - .repos - .iter() - .filter(|repo| { - let Some(name) = repo.path.file_name() else { - return true; - }; - !ids.contains(&identifier_from_name(&name.to_string_lossy())) - }) - .map(|repo| repo.path.clone()) - .collect() + let local = LocalReposStore::global(cx); + let local = local.read(cx); + let local_repos = + resolve_local_repos(&local.repos, &repo_list.announcements, &announcements); + + (announcements, local_repos, local.scanning) }; let announcements_changed = *self.announcements != announcements; @@ -270,6 +275,22 @@ impl SidebarPanel { .ok(); } + /// A local repository opens as the announced repository when its binding matches one, + /// and as a local-only repository otherwise. + fn open_local_entry( + &mut self, + entry: ResolvedLocalRepo, + window: &mut Window, + cx: &mut Context, + ) { + if let Some(announcement) = entry.announcement { + self.open_repo(&announcement, window, cx); + return; + } + + self.open_local_repo(entry.path, window, cx); + } + fn render_repos(&self, cx: &mut Context) -> impl IntoElement { let announcements = self.announcements.clone(); let local_repos = self.local_repos.clone(); @@ -361,11 +382,10 @@ impl SidebarPanel { }) } - /// Renders row `ix` of the merged list: an announced repository or a local one. fn render_repo_at( &self, announcements: &[Announcement], - local_repos: &[PathBuf], + local_repos: &[ResolvedLocalRepo], ix: usize, cx: &mut Context, ) -> AnyElement { @@ -376,9 +396,9 @@ impl SidebarPanel { } let local_ix = ix - announcements.len(); - let path = &local_repos[local_ix]; + let entry = &local_repos[local_ix]; - self.render_local_row(path, cx).into_any_element() + self.render_local_row(entry, cx).into_any_element() } fn render_repo_row( @@ -419,23 +439,43 @@ impl SidebarPanel { ) } - /// A local repository that is not yet set up for NIP-34, marked with a warning. - fn render_local_row(&self, path: &Path, cx: &mut Context) -> impl IntoElement { - let name = path + fn render_local_row( + &self, + entry: &ResolvedLocalRepo, + cx: &mut Context, + ) -> impl IntoElement { + let name = entry + .path .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or("Untitled".into()); - let path = path.to_path_buf(); - let avatar = PixelAvatar::new(path.to_string_lossy()); + let avatar = PixelAvatar::new(entry.path.to_string_lossy()); - NavItem::new(format!("local-repo:{}", path.display()), name, avatar) - .suffix( - Icon::new(IconName::TriangleAlert) - .small() - .text_color(cx.theme().warning), - ) + let suffix: AnyElement = match entry.nip34.as_ref().map(|binding| binding.kind) { + Some(Nip34Kind::Initialized) => { + let label = match entry.nip34.as_ref().and_then(local_tool) { + Some(tool) => format!("NIP-34 · {tool}"), + None => "NIP-34".to_owned(), + }; + local_badge(&label, cx.theme().muted_foreground) + } + Some(Nip34Kind::Cloned) => local_badge("NIP-34 clone", cx.theme().muted_foreground), + Some(Nip34Kind::ToolingOnly) => { + local_badge("Nostr tooling", cx.theme().muted_foreground) + } + None => Icon::new(IconName::TriangleAlert) + .small() + .text_color(cx.theme().warning) + .into_any_element(), + }; + + let id = format!("local-repo:{}", entry.path.display()); + let entry = entry.clone(); + + NavItem::new(id, name, avatar) + .suffix(suffix) .on_click(cx.listener(move |this, _ev, window, cx| { - this.open_local_repo(path.clone(), window, cx); + this.open_local_entry(entry.clone(), window, cx); })) } @@ -563,6 +603,15 @@ pub(super) fn server_host(relay: &RelayUrl) -> SharedString { .unwrap_or_else(|| SharedString::from(relay.to_string())) } +fn local_badge(label: &str, color: Hsla) -> AnyElement { + div() + .flex_shrink_0() + .text_xs() + .text_color(color) + .child(SharedString::from(label.to_owned())) + .into_any_element() +} + fn pick_banner() -> SharedString { let num = SystemTime::now() .duration_since(UNIX_EPOCH) diff --git a/docs/local-repo-nip34-detection.md b/docs/local-repo-nip34-detection.md index 7c7f71f..388aa55 100644 --- a/docs/local-repo-nip34-detection.md +++ b/docs/local-repo-nip34-detection.md @@ -1,6 +1,6 @@ # Local repository NIP-34 detection -Status: Phases 1–2 implemented. Phases 3–5 pending. +Status: Phases 1–3 implemented. Phases 4–5 pending. ## Motivation @@ -212,28 +212,31 @@ Implemented. - [x] `crates/workspace/src/views/sidebar/mod.rs`: minimal adaptation of the existing folder-name dedupe to the new entry type so the tree compiles; the badge/dedupe rewrite is Phase 3. -### Phase 3 — sidebar: derive the local list and link to announcements +### Phase 3 — derive the local list and link it to announcements -File: `crates/workspace/src/views/sidebar/mod.rs`. +Implemented. The matching lives in `signed_state` (per the data-model note above), so the sidebar +stays a thin renderer. -- [ ] Replace the folder-name dedupe in `refresh` with a resolution pass over - `LocalReposStore::global(cx).read(cx).repos`: - - For each entry, compute the detected `RepoAddr` when the binding is `Initialized` with - owner + identifier. - - Look the address up in `RepoListStore` announcements. - - If it matches an announcement **already shown** in the sidebar's list (the signed-in - user's own), drop it from the local list to avoid showing it twice. - - If it matches an announcement that is not in the shown list, keep it as a local entry - rendered with the "initialized" badge; clicking opens the announced repository (decision 1). - - Otherwise keep it with a badge derived from the binding kind. -- [ ] Extend the sidebar's local entry model from `Vec` to a small struct carrying the - path, the binding kind, the tool label and the resolved address, so `render_repo_at` can - render the badge and route clicks. -- [ ] Add the badge rendering to the local row in `render_repo_at` (three visible states): +- [x] `crates/signed_state/src/local_repos.rs`: `ResolvedLocalRepo` and + `resolve_local_repos(repos, known, own)` resolve each scanned repository's `RepoAddr` against + the known announcements: + - a binding matching one of the user's **own** announcements is dropped, since it is already + listed as an announcement row; + - a binding matching any other known announcement is kept and linked to it; + - every other repository is kept unchanged. +- [x] `crates/signed_git/src/nip34.rs`: `Nip34Binding` derives `PartialEq` so the sidebar can + detect changes to the resolved list. +- [x] `crates/workspace/src/views/sidebar/mod.rs`: the local list is `Arc>`; + `refresh` calls `resolve_local_repos` instead of the folder-name dedupe. A matched entry's + click opens the announced repository, the rest open the local detail view. +- [x] Badge rendering in `render_local_row`, derived from `Nip34Binding::signals`: - `Initialized` → "NIP-34 · nak" / "NIP-34 · ngit" - `Cloned` → "NIP-34 clone" (decision 2, its own visible state) - `ToolingOnly` → "Nostr tooling" (muted) - - plain → unchanged. + - plain → unchanged warning icon. + +Note: the announced-open path currently opens the announced repository without the local worktree; +attaching it is Phase 4. ### Phase 4 — detail view: open as announced, gate the publish CTA @@ -295,14 +298,15 @@ Unit tests in `crates/signed_git/src/nip34.rs` (use `tempfile` and a small local `https://host/repo.git` (no owner), a first segment that is not a valid `npub`, and an unrelated scheme such as `ssh://`. -Integration test in `crates/signed_state`: +Integration tests in `crates/signed_state/src/local_repos.rs` (plain `#[test]`, no GPUI harness): -- A scanned repository whose binding resolves to a `RepoAddr` that matches a seeded announcement is - deduped out of the local list when it is the user's own; one with no matching announcement - remains and is labelled. +- a repository bound to the user's own announcement is dropped from the local list; +- one bound to another owner's announcement is kept and linked to it; +- one with an unmatched binding is kept with its binding and no announcement; +- a plain repository is kept with no binding and no announcement. -Final verification: `cargo check -p signed_git -p signed_state -p workspace` and -`cargo test -p signed_git`. +Final verification: `cargo clippy -p signed_git -p signed_state -p workspace --all-targets` and +`cargo test -p signed_git -p signed_state`. ## Out of scope -- 2.54.0 From 9fbd1c9dfae41a79a9469dd0ff76c0a75e3ae253 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 14 Sep 2026 09:05:57 +0700 Subject: [PATCH 5/8] update --- crates/signed_state/src/repo.rs | 19 ++++- crates/workspace/src/views/repo/mod.rs | 99 +++++++++++++++++------ crates/workspace/src/views/sidebar/mod.rs | 71 ++++++++++++---- docs/local-repo-nip34-detection.md | 36 +++++---- 4 files changed, 166 insertions(+), 59 deletions(-) diff --git a/crates/signed_state/src/repo.rs b/crates/signed_state/src/repo.rs index 8ad9539..05c9a86 100644 --- a/crates/signed_state/src/repo.rs +++ b/crates/signed_state/src/repo.rs @@ -11,6 +11,7 @@ use signed_core::{ Announcement, Deletions, RepoAddr, RepoStatus, filters, parse_state, pull_request_patch, pull_request_patches, }; +use signed_git::Nip34Binding; use crate::backend::{ Backend, BackendEvent, grasp_base_url, grasp06_prs_url, pr_clone_urls, require_relay_accepted, @@ -39,6 +40,8 @@ pub struct RepoStore { /// Local working copy. The scan path for a local repository, kept when it is /// later announced so the panel keeps its worktree. pub path: Option, + /// NIP-34 state detected on disk for a local repository, if any. + pub nip34: Option, /// The first local pass has been applied. /// /// Views distinguish "no data yet" from a genuinely empty repository with it. @@ -112,6 +115,7 @@ impl RepoStore { addr: Some(addr), announcement: hint, path: None, + nip34: None, loaded: false, head: None, issues: Vec::new(), @@ -134,11 +138,12 @@ impl RepoStore { } /// Local repository discovered by the scan, not announced to NIP-34 yet. - pub fn new_local(path: PathBuf) -> Self { + pub fn new_local(path: PathBuf, nip34: Option) -> Self { Self { addr: None, announcement: None, path: Some(path), + nip34, loaded: true, head: None, issues: Vec::new(), @@ -160,6 +165,18 @@ impl RepoStore { } } + /// An announced repository whose working copy is already on disk. + pub fn from_worktree( + addr: RepoAddr, + announcement: Announcement, + path: PathBuf, + cx: &mut Context, + ) -> Self { + let mut store = Self::new(addr, Some(announcement), cx); + store.path = Some(path); + store + } + /// Switch a local repository to its NIP-34 mode, keeping its path. pub fn announce(&mut self, announcement: Announcement, cx: &mut Context) { self.addr = Some(announcement.addr()); diff --git a/crates/workspace/src/views/repo/mod.rs b/crates/workspace/src/views/repo/mod.rs index 747ca4d..fe61c68 100644 --- a/crates/workspace/src/views/repo/mod.rs +++ b/crates/workspace/src/views/repo/mod.rs @@ -26,8 +26,9 @@ use nostr::prelude::{RelayUrl, ToBech32, Url}; use signed_core::{Announcement, RepoAddr, RepoStatus}; use signed_git::FileCommit; use signed_state::{ - Backend, CheckoutStatus, CheckoutsStore, LocalReposStore, ProfileStore, RepoListStore, - RepoStore, ensure_repo_mirror, open_repo_mirror, pr_proposes_checkout, + Backend, CheckoutStatus, CheckoutsStore, LocalReposStore, Nip34Binding, Nip34Kind, + ProfileStore, RepoListStore, RepoStore, ensure_repo_mirror, open_repo_mirror, + pr_proposes_checkout, }; use signed_ui::{ CountBadge, DropdownButton, PixelAvatar, UserAvatar, copy_row, menu_copy_row, middle_truncate, @@ -123,10 +124,26 @@ impl RepoDetailView { pub fn new_local( dock_area: WeakEntity, local_path: PathBuf, + nip34: Option, window: &mut Window, cx: &mut Context, ) -> Self { - let store = cx.new(move |_cx| RepoStore::new_local(local_path)); + let store = cx.new(move |_cx| RepoStore::new_local(local_path, nip34)); + Self::new_common(dock_area, store, window, cx) + } + + /// A local repository whose detected binding matches an announcement. + /// + /// Opens as the announced repository with the local worktree attached. + pub fn new_local_announced( + dock_area: WeakEntity, + announcement: Announcement, + local_path: PathBuf, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let addr = announcement.addr(); + let store = cx.new(move |cx| RepoStore::from_worktree(addr, announcement, local_path, cx)); Self::new_common(dock_area, store, window, cx) } @@ -294,24 +311,17 @@ impl RepoDetailView { self.error = None; cx.notify(); - let (addr, announcement, local_path) = { + let (announcement, local_path) = { let store = self.store.read(cx); - ( - store.addr().cloned(), - store.announcement.clone(), - store.path.clone(), - ) + (store.announcement.clone(), store.path.clone()) }; - // Local repositories live on disk at their scan path. - // No clone step or network refresh applies here. - if addr.is_none() { + // A repository with a local worktree shows it directly. An announced one + // still loads its announcement and activity from the store, which is + // subscribed to the relays independently. + if let Some(local_path) = local_path { self.repo_started = true; - let Some(local_path) = local_path else { - return; - }; - let task: gpui::Task> = cx.spawn_in(window, async move |this, cx| { let data = cx .background_spawn(async move { @@ -1254,6 +1264,24 @@ impl RepoDetailView { .unwrap_or_default(); let avatar = PixelAvatar::new(path.clone()); + // A repository already bound to a coordinate is not offered for publishing again. + let bound = self.store.read(cx).nip34.clone(); + let action = match bound + .as_ref() + .filter(|binding| binding.kind == Nip34Kind::Initialized) + { + Some(binding) => bound_repo_label(binding, cx), + None => Button::new("init") + .icon(CustomIconName::Init) + .label("Initialize on Nostr") + .primary() + .tooltip("Publish this repository to Nostr") + .on_click(cx.listener(|this, _event, window, cx| { + this.open_init_dialog(window, cx); + })) + .into_any_element(), + }; + v_flex() .px_4() .pb_4() @@ -1291,16 +1319,7 @@ impl RepoDetailView { .child(path), ), ) - .child( - Button::new("init") - .icon(CustomIconName::Init) - .label("Initialize on Nostr") - .primary() - .tooltip("Publish this repository to Nostr") - .on_click(cx.listener(|this, _event, window, cx| { - this.open_init_dialog(window, cx); - })), - ), + .child(action), ) .child(self.render_header_tabs(cx)) .into_any_element() @@ -1996,6 +2015,34 @@ pub(super) fn repo_display_name(store: &RepoStore) -> SharedString { .unwrap_or_default() } +/// The owner and identifier a local repository is already bound to. +fn bound_repo_label(binding: &Nip34Binding, cx: &App) -> AnyElement { + let owner = binding + .owner + .and_then(|owner| owner.to_bech32().ok()) + .map(|npub| middle_truncate(&npub, 12, 8)) + .unwrap_or_else(|| "a NIP-34 coordinate".to_owned()); + + let mut label = v_flex().flex_shrink_0().items_end().gap_1().child( + div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child(SharedString::from(format!("Bound to {owner}"))), + ); + + if let Some(identifier) = binding.identifier.as_deref() { + label = label.child( + div() + .text_xs() + .font_semibold() + .text_color(cx.theme().muted_foreground) + .child(SharedString::from(identifier.to_owned())), + ); + } + + label.into_any_element() +} + impl BasePanel for RepoDetailView { fn panel_name(&self) -> &'static str { "repo" diff --git a/crates/workspace/src/views/sidebar/mod.rs b/crates/workspace/src/views/sidebar/mod.rs index 8dc7b99..5f2df34 100644 --- a/crates/workspace/src/views/sidebar/mod.rs +++ b/crates/workspace/src/views/sidebar/mod.rs @@ -10,8 +10,9 @@ use dock::{ }; use gpui::prelude::*; use gpui::{ - AnyElement, App, Context, Div, EventEmitter, FocusHandle, Focusable, Hsla, ObjectFit, Render, - SharedString, Subscription, WeakEntity, Window, div, img, px, relative, uniform_list, white, + AnyElement, App, Context, Div, Entity, EventEmitter, FocusHandle, Focusable, Hsla, ObjectFit, + Render, SharedString, Subscription, WeakEntity, Window, div, img, px, relative, uniform_list, + white, }; use gpui_base::Button as BaseButton; use gpui_component::button::{Button, ButtonVariants}; @@ -264,31 +265,71 @@ impl SidebarPanel { } /// The detail view offers to publish it to NIP-34. - fn open_local_repo(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context) { + fn open_local_repo( + &mut self, + path: PathBuf, + nip34: Option, + window: &mut Window, + cx: &mut Context, + ) { let detail = - cx.new(|cx| RepoDetailView::new_local(self.dock_area.clone(), path, window, cx)); - - self.dock_area - .update(cx, |dock_area, cx| { - add_center_panel(dock_area, panel_handle(detail), window, cx); - }) - .ok(); + cx.new(|cx| RepoDetailView::new_local(self.dock_area.clone(), path, nip34, window, cx)); + self.add_detail_panel(detail, window, cx); } - /// A local repository opens as the announced repository when its binding matches one, - /// and as a local-only repository otherwise. + /// A local repository whose binding matches an announcement opens as the announced repository. + fn open_local_announced( + &mut self, + announcement: Announcement, + path: PathBuf, + window: &mut Window, + cx: &mut Context, + ) { + let detail = cx.new(|cx| { + RepoDetailView::new_local_announced( + self.dock_area.clone(), + announcement, + path, + window, + cx, + ) + }); + self.add_detail_panel(detail, window, cx); + } + + /// A local repository opens as the announced repository + /// when its binding matches one, and as a local-only repository otherwise. fn open_local_entry( &mut self, entry: ResolvedLocalRepo, window: &mut Window, cx: &mut Context, ) { - if let Some(announcement) = entry.announcement { - self.open_repo(&announcement, window, cx); + let ResolvedLocalRepo { + path, + nip34, + announcement, + } = entry; + + if let Some(announcement) = announcement { + self.open_local_announced(announcement, path, window, cx); return; } - self.open_local_repo(entry.path, window, cx); + self.open_local_repo(path, nip34, window, cx); + } + + fn add_detail_panel( + &mut self, + detail: Entity, + window: &mut Window, + cx: &mut Context, + ) { + self.dock_area + .update(cx, |dock_area, cx| { + add_center_panel(dock_area, panel_handle(detail), window, cx); + }) + .ok(); } fn render_repos(&self, cx: &mut Context) -> impl IntoElement { diff --git a/docs/local-repo-nip34-detection.md b/docs/local-repo-nip34-detection.md index 388aa55..1511fdb 100644 --- a/docs/local-repo-nip34-detection.md +++ b/docs/local-repo-nip34-detection.md @@ -1,6 +1,6 @@ # Local repository NIP-34 detection -Status: Phases 1–3 implemented. Phases 4–5 pending. +Status: Phases 1–4 implemented. Phase 5 optional and pending. ## Motivation @@ -235,25 +235,27 @@ stays a thin renderer. - `ToolingOnly` → "Nostr tooling" (muted) - plain → unchanged warning icon. -Note: the announced-open path currently opens the announced repository without the local worktree; -attaching it is Phase 4. +A matched entry opens the announced repository; Phase 4 attaches its local worktree. ### Phase 4 — detail view: open as announced, gate the publish CTA -- [ ] `crates/signed_state/src/repo.rs`: add a constructor that keeps the worktree path while in - NIP-34 mode, e.g. `RepoStore::from_worktree(addr, announcement, path, cx)`, or a small - `set_path`. `RepoStore::announce` already keeps an existing path, so this can be built from - `new` plus assigning the path. Opening a repository must **not** remove it from - `LocalReposStore` (that removal belongs to `apply_announcement`, which only runs on a real - publish). -- [ ] `crates/workspace/src/views/repo/mod.rs`: add `RepoDetailView::new_local_announced(...)` - (or an `Option` parameter on `new_local`) that builds the announced store with - the local worktree attached, then `new_common`. -- [ ] `crates/workspace/src/views/sidebar/mod.rs`: route local-entry clicks through the new - constructor when an announcement matched, and through `open_local_repo` otherwise. -- [ ] `crates/workspace/src/views/repo/mod.rs`: for a `new_local` view whose store carries an - `Initialized` binding, suppress the "publish to NIP-34" call to action and instead show the - owner and identifier. `Cloned` keeps the ability to be adopted/published. +Implemented. + +- [x] `crates/signed_state/src/repo.rs`: `RepoStore::from_worktree(addr, announcement, path, cx)` + builds the announced store and attaches the local path. `RepoStore` gained a `nip34` field + carrying the detected binding, and `new_local` now takes it. +- [x] `crates/workspace/src/views/repo/mod.rs`: `RepoDetailView::new_local_announced(...)` builds the + announced store with the local worktree, then `new_common`. `new_local` gained an + `Option` parameter. +- [x] `crates/workspace/src/views/repo/mod.rs` (`load_repo`): a store with a local path now loads the + worktree from that path even when it is announced, instead of always using the cached mirror. + This is what actually attaches the local worktree; previously the announced branch ignored + `RepoStore::path` and cloned into the mirror. +- [x] `crates/workspace/src/views/sidebar/mod.rs`: local-entry clicks route through + `open_local_announced` when an announcement matched, and `open_local_repo` otherwise. +- [x] `crates/workspace/src/views/repo/mod.rs` (`render_local_header`): an `Initialized` binding + suppresses the "Initialize on Nostr" call to action and shows the owner and identifier + instead. `Cloned` and `ToolingOnly` keep the publish path. ### Phase 5 — optional: mark Signed's own publications -- 2.54.0 From e3c2dd280cc07641335ee31a8b19e2854ccaba63 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 14 Sep 2026 09:12:35 +0700 Subject: [PATCH 6/8] ngit compatible --- crates/signed_git/src/lib.rs | 4 +- crates/signed_git/src/nip34.rs | 26 +++ crates/signed_git/src/remote.rs | 5 +- crates/signed_state/src/backend.rs | 22 +- docs/local-repo-nip34-detection.md | 317 ----------------------------- 5 files changed, 51 insertions(+), 323 deletions(-) delete mode 100644 docs/local-repo-nip34-detection.md diff --git a/crates/signed_git/src/lib.rs b/crates/signed_git/src/lib.rs index f1eae1f..470aaee 100644 --- a/crates/signed_git/src/lib.rs +++ b/crates/signed_git/src/lib.rs @@ -20,7 +20,9 @@ pub use history::{ CommitList, FileCommit, MAX_LISTED_COMMITS, all_commits, head_commit, worktree_all_commits, worktree_commit, worktree_commit_range_commits, worktree_last_commits, }; -pub use nip34::{GraspSignals, Nip34Binding, Nip34Kind, detect_nip34, is_grasp_url}; +pub use nip34::{ + GraspSignals, Nip34Binding, Nip34Kind, detect_nip34, is_grasp_url, set_nostr_repo, +}; pub use patch::{ apply_patch, format_patch_between, patch_commits, patch_diffs, split_patch_series, }; diff --git a/crates/signed_git/src/nip34.rs b/crates/signed_git/src/nip34.rs index bf58ac2..7c50c13 100644 --- a/crates/signed_git/src/nip34.rs +++ b/crates/signed_git/src/nip34.rs @@ -1,5 +1,6 @@ use std::path::Path; +use anyhow::Result; use gix::bstr::ByteSlice; use nostr::prelude::*; @@ -182,6 +183,16 @@ pub fn detect_nip34(repo_path: &Path) -> Option { }) } +/// Record a repository's NIP-34 coordinate in its local `nostr.repo` config. +pub fn set_nostr_repo(repo_path: &Path, naddr: &str) -> Result<()> { + let repo = gix::open(repo_path)?; + + crate::remote::edit_local_config(&repo, |config| { + config.set_raw_value("nostr.repo", naddr)?; + Ok(()) + }) +} + /// Mirrors `nak`'s `IsGraspURL`: two path segments, a path of at least 65 bytes, /// and a first segment that decodes as an `npub`. pub fn is_grasp_url(url: &str) -> bool { @@ -360,6 +371,21 @@ mod tests { assert_eq!(binding.identifier.as_deref(), Some("my-repo")); } + #[test] + fn the_written_nostr_repo_marker_is_detected() { + let (_dir, path) = init_repo(); + let owner = key(); + let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo"); + + set_nostr_repo(&path, &naddr).expect("write marker"); + + let binding = detect_nip34(&path).expect("binding"); + assert_eq!(binding.kind, Nip34Kind::Initialized); + assert!(binding.signals.nostr_repo_config); + assert_eq!(binding.owner, Some(owner)); + assert_eq!(binding.identifier.as_deref(), Some("my-repo")); + } + #[test] fn nostr_remote_is_a_nip34_clone() { let (_dir, path) = init_repo(); diff --git a/crates/signed_git/src/remote.rs b/crates/signed_git/src/remote.rs index 6bbc4e4..78d2452 100644 --- a/crates/signed_git/src/remote.rs +++ b/crates/signed_git/src/remote.rs @@ -252,10 +252,7 @@ pub fn set_origin(repo_path: &Path, url: &str) -> Result<()> { } /// Apply `edit` to the repository-local configuration and persist it. -/// -/// The config file is locked while it is read, edited and written back, -/// like git would when running `git config` or `git remote`. -fn edit_local_config( +pub(crate) fn edit_local_config( repo: &gix::Repository, edit: impl FnOnce(&mut gix::config::File) -> Result<()>, ) -> Result<()> { diff --git a/crates/signed_state/src/backend.rs b/crates/signed_state/src/backend.rs index fa9fccf..362c820 100644 --- a/crates/signed_state/src/backend.rs +++ b/crates/signed_state/src/backend.rs @@ -7,10 +7,11 @@ use anyhow::{Error, anyhow, bail}; use bitcoin_hashes::sha1::Hash as Sha1Hash; use gpui::{App, AppContext, BackgroundExecutor, Context, Entity, EventEmitter, Global, Task}; use nostr::event::IntoEventBuilder; +use nostr::nips::nip19::Nip19Coordinate; use nostr_connect::prelude::*; use nostr_sdk::client::SyncSummary; use nostr_sdk::prelude::*; -use signed_core::{Announcement, RepoAddr, build_state, filters, identifier_from_name}; +use signed_core::{Announcement, RepoAddr, build_state, filters, identifier_from_name, repo_addr}; use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update}; use crate::git_store::repo_mirror_path; @@ -743,6 +744,25 @@ impl Backend { .await; } + // Record the ngit-compatible `nostr.repo` marker, + // so the next scan detects the repository instead of offering to publish it again. + let coordinate = repo_addr(event.pubkey, repo_id.clone()); + match Nip19Coordinate::new(coordinate, servers.clone()).to_bech32() { + Ok(naddr) => { + let path = path.clone(); + cx.background_spawn(async move { + if let Err(error) = signed_git::set_nostr_repo(&path, &naddr) { + log::warn!( + "failed to record the NIP-34 marker for {}: {error}", + path.display() + ); + } + }) + .await; + } + Err(error) => log::warn!("failed to encode the repository coordinate: {error}"), + } + Announcement::from_event(&event).ok_or_else(|| anyhow!("failed to parse announcement")) }) } diff --git a/docs/local-repo-nip34-detection.md b/docs/local-repo-nip34-detection.md deleted file mode 100644 index 1511fdb..0000000 --- a/docs/local-repo-nip34-detection.md +++ /dev/null @@ -1,317 +0,0 @@ -# Local repository NIP-34 detection - -Status: Phases 1–4 implemented. Phase 5 optional and pending. - -## Motivation - -`LocalReposStore::rescan` (`crates/signed_state/src/local_repos.rs`) walks the configured scan -roots with `find_git_repos` (`crates/signed_git/src/scan.rs`) and returns every directory that -contains a `.git` entry. It has no idea whether the repository was already bound to NIP-34 by -another tool (nak, ngit) or by Signed itself. - -Today the sidebar works around this by matching the repository folder name against the signed-in -user's own announcements (`crates/workspace/src/views/sidebar/mod.rs`, in `refresh`). That is -fragile: it only recognises repositories the user already announced, it depends on the folder name -happening to sanitize to the identifier, and it never notices repositories initialized by other -tooling. - -The goal is for every scanned repository to carry a **NIP-34 binding** (or none), so the UI can -label it, link it to its announcement, and stop offering to publish something that is already -published. - -## Decisions taken - -1. **Open as the announced repository.** When a local repository's detected binding resolves to a - coordinate that matches a known announcement, clicking it opens the announced repository (with - the local worktree attached), not a local-only detail view. -2. **Cloned is its own visible state.** A repository cloned from a `nostr://` remote but never - initialized locally is a distinct state from both a plain repository and an initialized one. - -## Detection signals - -nak and ngit use completely different on-disk conventions. There is no shared marker, so both must -be recognised. Everything below is verified against ngit v3.0.1 and nak `master`. - -| # | Signal | Exact location | Meaning | Tool | Strength | -|---|--------|----------------|---------|------|----------| -| 1 | `nip34.json` | `/nip34.json` | Repo initialized. JSON fields: `identifier`, `name`, `description`, `owner`, `grasp-servers[]`, `earliest-unique-commit` | nak | Strong; yields owner + identifier | -| 2 | `nip34.json` line | `/info/exclude` | Corroborates #1 (nak hides the file this way) | nak | Corroborating | -| 3 | `refs/heads/nip34/state/HEAD` and `refs/heads/nip34/state/` | refs | nak materialized a kind-30618 state | nak | Strong | -| 4 | Remote `nip34/grasp/` | `.git/config`: `remote.nip34/grasp/.url` = `https:////.git` | nak `gitSetupRemotes` | nak | Strong; owner + id from the URL | -| 5 | `nostr.repo` = `naddr1…` (kind 30617) | **local** git config | ngit bound the repo to a coordinate | ngit | Strong; yields the coordinate | -| 6 | Remote URL `nostr://…` | `.git/config` | ngit init, or a plain `git clone nostr://…` | ngit | Medium; init **or** clone | -| 7 | `nostr-cache.lmdb` | `/nostr-cache.lmdb` | ngit has run here (also on clone) | ngit | Weak; touched only | -| 8 | `nostr.repo-relay-only`, `nostr.nostate`, `nostr.private` | local git config | ngit auxiliary flags | ngit | Weak | -| 9 | Grasp-shaped remote `https:////.git` (or `grasp://…`) | `.git/config` | Some client registered a grasp remote | unknown | Medium | -| 10 | `maintainers.yaml` | `/maintainers.yaml` | ngit multi-maintainer config | ngit | Weak | - -Notes: - -- ngit has **no** `nip34.json`, and nak has **no** `nostr.repo` config key. The two conventions are - disjoint, so seeing both is essentially impossible; if it happens, prefer #1/#5 (a real binding) - for the coordinate and record both evidence flags. -- `nostr.repo` is written and read at **local** scope by ngit, so detection must read the local - config only, never the merged/global view. -- The grasp URL shape mirrors nak's `IsGraspURL`: exactly two `/` in the path (two segments), total - path length ≥ 65, and the first 63 characters after the leading `/` decode as an `npub`. The - identifier segment conventionally ends in `.git`. -- Signed's own clone URLs use the `grasp://` scheme (see `transport_url` in - `crates/signed_git/src/remote.rs`), so the shape check must accept `grasp://` too. -- A disk-only check cannot prove a repository was *announced*; ngit explicitly has a - "coordinate set, no announcement on relays" state. Detection answers "is this repository bound - to NIP-34", and the relay lookup stays a separate layer. - -## Classification - -```mermaid -flowchart TD - A[Scanned repo] --> B{nip34.json parses?} - B -- yes --> INIT[NIP-34 initialized
nak, owner+id known] - B -- no --> C{nostr.repo decodes
as kind-30617 naddr?} - C -- yes --> INIT2[NIP-34 initialized
ngit, coordinate known] - C -- no --> D{nip34/grasp remote
or nip34/state refs?} - D -- yes --> INIT3[NIP-34 initialized
nak, id from remote URL] - D -- no --> E{nostr:// remote only?} - E -- yes --> CLONE[NIP-34 clone
derive owner+id from URL] - E -- no --> F{lmdb / aux config /
grasp-shaped remote only?} - F -- yes --> TOOL[Nostr tooling seen
binding unclear] - F -- no --> PLAIN[Plain local repository] -``` - -Precedence, in order: - -1. #1 `nip34.json` parses → `Initialized`, owner + identifier known (nak). -2. #5 `nostr.repo` decodes as a kind-30617 `naddr` → `Initialized`, coordinate known (ngit). -3. #3 or #4, without #1/#2 → `Initialized` (nak); derive owner + identifier from the - `nip34/grasp/` remote URL when present. -4. Only #6 `nostr://` remote → `Cloned`; derive owner + identifier from the URL when parseable. -5. Only #7, #8, #9 or #10 → `ToolingOnly`. -6. Nothing → `None`. - -## Data model - -Detection lives in `signed_git` next to the other git plumbing (`scan.rs`, `remote.rs`). It reports -raw on-disk facts plus the nostr identity it can recover; mapping to `RepoAddr` and matching against -announcements happens in `signed_state`, where `RepoAddr` and the announcement list live. - -New file `crates/signed_git/src/nip34.rs`: - -```rust -use std::path::Path; - -use nostr::PublicKey; - -/// The kind of NIP-34 relationship a local repository has on disk. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Nip34Kind { - /// Bound to a NIP-34 coordinate (nak `nip34.json` or ngit `nostr.repo`). - Initialized, - /// Cloned from a `nostr://` remote but never initialized locally. - Cloned, - /// Nostr tooling touched the repository but no binding is recoverable. - ToolingOnly, -} - -/// `nip34_grasp_remote` is the nak-specific `nip34/grasp/` remote name (#4), -/// while `grasp_remote` covers any grasp-shaped remote URL (#9). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct GraspSignals { - pub nip34_json: bool, - pub nip34_excluded: bool, - pub nostr_repo_config: bool, - pub nostr_remote: bool, - pub grasp_remote: bool, - pub nip34_grasp_remote: bool, - pub nip34_state_refs: bool, - pub nostr_cache: bool, - pub nostr_aux_config: bool, - pub maintainers_yaml: bool, -} - -#[derive(Debug, Clone)] -pub struct Nip34Binding { - pub kind: Nip34Kind, - pub signals: GraspSignals, - /// Coordinate owner and identifier, from #1 or #5. - pub owner: Option, - pub identifier: Option, - pub grasp_urls: Vec, -} - -/// Inspect a repository's on-disk state. -/// -/// `None` for a plain repository. Best-effort: unreadable or malformed input is -/// treated as a missing signal, never an error, so a bad repository cannot fail a scan. -pub fn detect_nip34(repo_path: &Path) -> Option; - -/// Whether `url` has the grasp URL shape, `[https|http|grasp]:////.git`. -pub fn is_grasp_url(url: &str) -> bool; -``` - -Implementation notes: - -- Use **gix** (`gix::open`, `config::File::from_path_no_includes`, remote config sections, - `references().prefixed`), not `git` subprocesses: the scan walks many repositories on a - background thread. -- Worktree root via `repo.workdir()`; `.git`-relative paths (`info/exclude`, - `nostr-cache.lmdb`) via `repo.common_dir()`. -- Read `nostr.repo` from the **local** config file only (`repo.common_dir().join("config")`), - mirroring ngit's own scope. -- Parse `nip34.json` with `serde_json`. The `owner` field is an npub in nak's writer but its - validator accepts hex too, so use `PublicKey::parse` (bech32 or hex). -- Decode ngit's `naddr` with the nostr crate's NIP-19 coordinate decoder (`Nip19Coordinate`), and - require kind 30617. -- Add `serde` and `serde_json` to `crates/signed_git/Cargo.toml` (both are already - workspace dependencies). - -`crates/signed_git/src/scan.rs` returns richer entries: - -```rust -pub struct LocalRepo { - pub path: PathBuf, - /// `None` for a plain repository. - pub nip34: Option, -} - -pub fn find_git_repos(root: &Path) -> Vec; -``` - -The existing dedup rules (nested repositories, canonicalize, sort) are unchanged; `detect_nip34` -runs per kept path. Export `LocalRepo`, `Nip34Binding`, `Nip34Kind`, `GraspSignals` from -`signed_git/src/lib.rs`. - -## Action plan - -### Phase 1 — `signed_git` detection (no app behavior change) - -Implemented. - -- [x] `crates/signed_git/Cargo.toml`: add `serde.workspace = true`, `serde_json.workspace = true`. -- [x] `crates/signed_git/src/nip34.rs`: implement `detect_nip34`, `is_grasp_url`, the enums and - structs above. Keep every file/config read fallible-but-ignored: a missing or malformed - input clears only its own flag. -- [x] `crates/signed_git/src/lib.rs`: add `mod nip34;` and re-export the public items. -- [x] Tests in `crates/signed_git/src/nip34.rs` (see Testing). - -### Phase 2 — thread `LocalRepo` through the state layer - -Implemented. - -- [x] `crates/signed_git/src/scan.rs`: change `find_git_repos` to `Vec`; in the walk, - `detect_nip34` each kept path. -- [x] `crates/signed_git/src/tests.rs`: update `find_git_repos_*` expectations to the new type - (compare `.path`). -- [x] `crates/signed_state/src/local_repos.rs`: `repos: Arc>`; `remove(&path)` - filters on `.path`; the background scan already returns the richer vector unchanged. -- [x] `crates/signed_state/src/checkouts.rs` (`run_refresh`): iterate `.path` instead of bare - paths when collecting `scanned`. -- [x] `crates/signed_state/src/lib.rs`: re-export `LocalRepo`, `Nip34Binding`, `Nip34Kind` and - `GraspSignals`. -- [x] `crates/signed_state/src/local_repos.rs`: `local_repo_addr(&LocalRepo) -> Option` - resolves a binding when both owner and identifier are known. -- [x] `crates/workspace/src/views/sidebar/mod.rs`: minimal adaptation of the existing folder-name - dedupe to the new entry type so the tree compiles; the badge/dedupe rewrite is Phase 3. - -### Phase 3 — derive the local list and link it to announcements - -Implemented. The matching lives in `signed_state` (per the data-model note above), so the sidebar -stays a thin renderer. - -- [x] `crates/signed_state/src/local_repos.rs`: `ResolvedLocalRepo` and - `resolve_local_repos(repos, known, own)` resolve each scanned repository's `RepoAddr` against - the known announcements: - - a binding matching one of the user's **own** announcements is dropped, since it is already - listed as an announcement row; - - a binding matching any other known announcement is kept and linked to it; - - every other repository is kept unchanged. -- [x] `crates/signed_git/src/nip34.rs`: `Nip34Binding` derives `PartialEq` so the sidebar can - detect changes to the resolved list. -- [x] `crates/workspace/src/views/sidebar/mod.rs`: the local list is `Arc>`; - `refresh` calls `resolve_local_repos` instead of the folder-name dedupe. A matched entry's - click opens the announced repository, the rest open the local detail view. -- [x] Badge rendering in `render_local_row`, derived from `Nip34Binding::signals`: - - `Initialized` → "NIP-34 · nak" / "NIP-34 · ngit" - - `Cloned` → "NIP-34 clone" (decision 2, its own visible state) - - `ToolingOnly` → "Nostr tooling" (muted) - - plain → unchanged warning icon. - -A matched entry opens the announced repository; Phase 4 attaches its local worktree. - -### Phase 4 — detail view: open as announced, gate the publish CTA - -Implemented. - -- [x] `crates/signed_state/src/repo.rs`: `RepoStore::from_worktree(addr, announcement, path, cx)` - builds the announced store and attaches the local path. `RepoStore` gained a `nip34` field - carrying the detected binding, and `new_local` now takes it. -- [x] `crates/workspace/src/views/repo/mod.rs`: `RepoDetailView::new_local_announced(...)` builds the - announced store with the local worktree, then `new_common`. `new_local` gained an - `Option` parameter. -- [x] `crates/workspace/src/views/repo/mod.rs` (`load_repo`): a store with a local path now loads the - worktree from that path even when it is announced, instead of always using the cached mirror. - This is what actually attaches the local worktree; previously the announced branch ignored - `RepoStore::path` and cloned into the mirror. -- [x] `crates/workspace/src/views/sidebar/mod.rs`: local-entry clicks route through - `open_local_announced` when an announcement matched, and `open_local_repo` otherwise. -- [x] `crates/workspace/src/views/repo/mod.rs` (`render_local_header`): an `Initialized` binding - suppresses the "Initialize on Nostr" call to action and shows the owner and identifier - instead. `Cloned` and `ToolingOnly` keep the publish path. - -### Phase 5 — optional: mark Signed's own publications - -Signed's `publish_local_repo` (`crates/signed_state/src/backend.rs`) currently pushes by URL and -writes no on-disk marker, so a repository Signed itself published is not detected on the next scan. -Decide separately whether to write a marker on publish: - -- ngit-compatible and least intrusive: `git config --local nostr.repo `. -- nak-compatible: write `nip34.json` and add it to `.git/info/exclude`. - -Do not write both. This is a behavior change to a third-party convention and should be a -deliberate, separate decision. - -## Edge cases - -- Bare repositories are never scanned (no `.git` entry to match), so their absence as a worktree is - not a problem. Linked worktrees have a `.git` file and are scanned; `gix::open` resolves them and - `info/exclude`, `config` and `nostr-cache.lmdb` live in the shared common dir. -- Submodules are already filtered out by the nested-path rule in `scan.rs`. -- Detection must be cheap and side-effect-free: no network, no writes, no `git` subprocesses. -- Multiple grasp servers produce multiple `nip34/grasp/*` remotes; use the first parseable one for - the coordinate and keep all of them in `grasp_urls`. -- Offline: matching against announcements may find nothing, but the disk badge still shows. Disk - state is authoritative for "bound"; relay state only adds "and announced". -- The scan runs on wasm with empty roots (`init` passes `Vec::new()`), so detection code must not - assume a non-empty root list; no `cfg` gymnastics are needed since it is never reached. - -## Testing - -Unit tests in `crates/signed_git/src/nip34.rs` (use `tempfile` and a small local `git` helper): - -- `nip34.json` with an npub owner → `Initialized`, owner + identifier parsed. -- malformed `nip34.json` → falls back to no #1 signal, does not panic. -- `nostr.repo` set to a kind-30617 `naddr` → `Initialized` with the matching coordinate. -- `origin` = `nostr://npub…/relay/identifier` and no `nostr.repo` → `Cloned`. -- remote `nip34/grasp/` = `https:////.git` → nak remote signal, owner + id - recovered from the URL. -- `refs/heads/nip34/state/HEAD` present and `nip34.json` in `.git/info/exclude` → nak state signals. -- `.git/nostr-cache.lmdb` alone → `ToolingOnly`. -- plain repository → `None`. -- `is_grasp_url`: accept `https://host/npub1…/repo.git` and `grasp://host/npub1…/repo.git`; reject - `https://host/repo.git` (no owner), a first segment that is not a valid `npub`, and an unrelated - scheme such as `ssh://`. - -Integration tests in `crates/signed_state/src/local_repos.rs` (plain `#[test]`, no GPUI harness): - -- a repository bound to the user's own announcement is dropped from the local list; -- one bound to another owner's announcement is kept and linked to it; -- one with an unmatched binding is kept with its binding and no announcement; -- a plain repository is kept with no binding and no announcement. - -Final verification: `cargo clippy -p signed_git -p signed_state -p workspace --all-targets` and -`cargo test -p signed_git -p signed_state`. - -## Out of scope - -- Proving a repository is announced on relays. That stays the announcement layer's job. -- Writing markers for Signed-published repositories is Phase 5 and optional. -- Migrating or rewriting other tools' markers (we only read them). -- 2.54.0 From 7d2c3fd0c52d9cd0a3080d1558cb44bddee57a53 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 14 Sep 2026 10:41:30 +0700 Subject: [PATCH 7/8] update nav item --- Cargo.lock | 154 ++++++++++++---------- crates/signed_state/src/local_repos.rs | 36 ++++- crates/signed_ui/src/pixel_avatar.rs | 43 +++--- crates/workspace/src/views/sidebar/mod.rs | 91 ++++++++----- 4 files changed, 201 insertions(+), 123 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a364b65..8a40acd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -913,9 +913,9 @@ dependencies = [ [[package]] name = "bytemuck_derive" -version = "1.12.0" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", @@ -1222,7 +1222,7 @@ dependencies = [ [[package]] name = "collections" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "gpui_util", "indexmap", @@ -1511,9 +1511,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.1" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" dependencies = [ "cfg-if", ] @@ -1694,7 +1694,7 @@ dependencies = [ [[package]] name = "derive_refineable" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "proc-macro2", "quote", @@ -1865,7 +1865,7 @@ dependencies = [ "cc", "memchr", "rustc_version", - "toml 1.1.5+spec-1.1.0", + "toml 1.1.6+spec-1.1.0", "vswhom", "winreg", ] @@ -3539,7 +3539,7 @@ dependencies = [ [[package]] name = "gpui" version = "0.2.2" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "accesskit", "anyhow", @@ -3747,7 +3747,7 @@ dependencies = [ [[package]] name = "gpui_apple" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "anyhow", "block", @@ -3764,13 +3764,14 @@ dependencies = [ "log", "metal", "objc", + "objc2 0.6.4", "parking_lot", ] [[package]] name = "gpui_linux" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "accesskit", "accesskit_unix", @@ -3816,7 +3817,7 @@ dependencies = [ [[package]] name = "gpui_macos" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "accesskit", "accesskit_macos", @@ -3848,6 +3849,7 @@ dependencies = [ "objc2 0.6.4", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", + "objc2-screen-capture-kit", "objc2-user-notifications", "parking_lot", "pathfinder_geometry", @@ -3862,7 +3864,7 @@ dependencies = [ [[package]] name = "gpui_macros" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -3873,7 +3875,7 @@ dependencies = [ [[package]] name = "gpui_platform" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "console_error_panic_hook", "gpui", @@ -3886,7 +3888,7 @@ dependencies = [ [[package]] name = "gpui_shared_string" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "schemars", "serde", @@ -3896,7 +3898,7 @@ dependencies = [ [[package]] name = "gpui_util" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "anyhow", "log", @@ -3906,7 +3908,7 @@ dependencies = [ [[package]] name = "gpui_web" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "anyhow", "console_error_panic_hook", @@ -3919,6 +3921,10 @@ dependencies = [ "parking_lot", "raw-window-handle", "scheduler", + "smallvec", + "unicode-properties", + "unicode-script", + "unicode-segmentation", "uuid", "wasm-bindgen", "wasm-bindgen-futures", @@ -3930,7 +3936,7 @@ dependencies = [ [[package]] name = "gpui_wgpu" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "anyhow", "bytemuck", @@ -3956,7 +3962,7 @@ dependencies = [ [[package]] name = "gpui_windows" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "accesskit", "accesskit_windows", @@ -3983,9 +3989,9 @@ dependencies = [ [[package]] name = "granit-parser" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65ec0d45986cd51c847c75c5b69a00852c4fc84d0e5e79f041173f73437d0cdf" +checksum = "48aa83cc6ac4dc610adf5501a5392b4bcc543b2c1f24eaf77469a96e31ec9abe" dependencies = [ "arraydeque", "smallvec", @@ -4260,7 +4266,7 @@ dependencies = [ [[package]] name = "http_client" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "anyhow", "async-compression", @@ -4280,7 +4286,7 @@ dependencies = [ [[package]] name = "http_client_tls" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "log", "rustls", @@ -4723,9 +4729,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.35" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" +checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" dependencies = [ "defmt", "jiff-core", @@ -4740,18 +4746,19 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" dependencies = [ "defmt", + "log", ] [[package]] name = "jiff-static" -version = "0.2.35" +version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" +checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" dependencies = [ "jiff-core", "proc-macro2", @@ -4980,9 +4987,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.23" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d8f1ea3f21fd3405dcaf6c9b5c1630af9afc422d9073ea39c5f6d6c772e08ed" +checksum = "6480ccc157a1389bb2e4891b24751b0f798ba640d22386f23143fbcc89da195a" dependencies = [ "libc", ] @@ -5070,9 +5077,9 @@ checksum = "ff9840bcc50b71349309900da0ce7279aa336ae71d73250b07998932c7d97c25" [[package]] name = "lru-slab" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" [[package]] name = "lsp-types" @@ -5236,7 +5243,7 @@ dependencies = [ [[package]] name = "media" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "anyhow", "bindgen", @@ -5488,7 +5495,7 @@ dependencies = [ [[package]] name = "nostr" version = "0.45.4" -source = "git+https://github.com/rust-nostr/nostr#5c669a498e5f8dd1ec5713b11fdb92bcd858ad73" +source = "git+https://github.com/rust-nostr/nostr#b230cecf9dbb38e0228e6fff4544ed9d261326fc" dependencies = [ "aes", "base64 0.22.1", @@ -5514,7 +5521,7 @@ dependencies = [ [[package]] name = "nostr-connect" version = "0.45.1" -source = "git+https://github.com/rust-nostr/nostr#5c669a498e5f8dd1ec5713b11fdb92bcd858ad73" +source = "git+https://github.com/rust-nostr/nostr#b230cecf9dbb38e0228e6fff4544ed9d261326fc" dependencies = [ "async-utility", "futures-core", @@ -5528,7 +5535,7 @@ dependencies = [ [[package]] name = "nostr-database" version = "0.45.1" -source = "git+https://github.com/rust-nostr/nostr#5c669a498e5f8dd1ec5713b11fdb92bcd858ad73" +source = "git+https://github.com/rust-nostr/nostr#b230cecf9dbb38e0228e6fff4544ed9d261326fc" dependencies = [ "nostr", "opaquerr", @@ -5537,7 +5544,7 @@ dependencies = [ [[package]] name = "nostr-gossip" version = "0.45.0" -source = "git+https://github.com/rust-nostr/nostr#5c669a498e5f8dd1ec5713b11fdb92bcd858ad73" +source = "git+https://github.com/rust-nostr/nostr#b230cecf9dbb38e0228e6fff4544ed9d261326fc" dependencies = [ "nostr", "opaquerr", @@ -5546,7 +5553,7 @@ dependencies = [ [[package]] name = "nostr-gossip-memory" version = "0.45.0" -source = "git+https://github.com/rust-nostr/nostr#5c669a498e5f8dd1ec5713b11fdb92bcd858ad73" +source = "git+https://github.com/rust-nostr/nostr#b230cecf9dbb38e0228e6fff4544ed9d261326fc" dependencies = [ "indexmap", "lru", @@ -5558,7 +5565,7 @@ dependencies = [ [[package]] name = "nostr-lmdb" version = "0.45.2" -source = "git+https://github.com/rust-nostr/nostr#5c669a498e5f8dd1ec5713b11fdb92bcd858ad73" +source = "git+https://github.com/rust-nostr/nostr#b230cecf9dbb38e0228e6fff4544ed9d261326fc" dependencies = [ "async-utility", "flatbuffers", @@ -5573,7 +5580,7 @@ dependencies = [ [[package]] name = "nostr-memory" version = "0.45.1" -source = "git+https://github.com/rust-nostr/nostr#5c669a498e5f8dd1ec5713b11fdb92bcd858ad73" +source = "git+https://github.com/rust-nostr/nostr#b230cecf9dbb38e0228e6fff4544ed9d261326fc" dependencies = [ "btreecap", "nostr", @@ -5584,7 +5591,7 @@ dependencies = [ [[package]] name = "nostr-sdk" version = "0.45.2" -source = "git+https://github.com/rust-nostr/nostr#5c669a498e5f8dd1ec5713b11fdb92bcd858ad73" +source = "git+https://github.com/rust-nostr/nostr#b230cecf9dbb38e0228e6fff4544ed9d261326fc" dependencies = [ "async-utility", "async-wsocket", @@ -6071,6 +6078,18 @@ dependencies = [ "objc2-metal 0.3.2", ] +[[package]] +name = "objc2-screen-capture-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74b7c5390f477482f001bc354d6571a70db7e4f8d5288e860c45521fbce11394" +dependencies = [ + "block2 0.6.2", + "objc2 0.6.4", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-user-notifications" version = "0.3.2" @@ -6311,7 +6330,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "perf" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "collections", "serde", @@ -6618,7 +6637,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.13+spec-1.1.0", + "toml_edit 0.25.15+spec-1.1.0", ] [[package]] @@ -7099,7 +7118,7 @@ dependencies = [ [[package]] name = "refineable" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "derive_refineable", ] @@ -7182,7 +7201,7 @@ dependencies = [ [[package]] name = "reqwest_client" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "anyhow", "bytes", @@ -7560,7 +7579,7 @@ dependencies = [ [[package]] name = "scheduler" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "async-task", "backtrace", @@ -8120,9 +8139,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.0" +version = "1.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" +checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" [[package]] name = "smol" @@ -8276,7 +8295,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "sum_tree" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "heapless 0.9.3", "log", @@ -8722,18 +8741,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.13.2" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cf0ded5c4e56918d8f8a339e1bb67d038d3bc6d144ac407904015ba2e4cde9b" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" @@ -8848,9 +8858,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.1.5+spec-1.1.0" +version = "1.1.6+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12c0ba9680044b4ce98d391a62094047eada0d64860b80166c39f4a6b5640785" +checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" dependencies = [ "indexmap", "serde_core", @@ -8895,9 +8905,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.13+spec-1.1.0" +version = "0.25.15+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" dependencies = [ "indexmap", "toml_datetime 1.1.1+spec-1.1.0", @@ -9085,9 +9095,9 @@ dependencies = [ [[package]] name = "tree-sitter-cmake" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "164e0c4f4236ec5ceff14824a5528615cf462e100467e49826442ff57d327061" +checksum = "d22893fac54133fdb93497efc45713d53a96d93b035288c7a8ab0c2af77c0ddd" dependencies = [ "cc", "tree-sitter-language", @@ -9522,9 +9532,9 @@ dependencies = [ [[package]] name = "unicode-properties" -version = "0.1.4" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" [[package]] name = "unicode-script" @@ -9660,7 +9670,7 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] name = "util_macros" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "perf", "quote", @@ -11427,7 +11437,7 @@ checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" [[package]] name = "zlog" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "anyhow", "chrono", @@ -11444,7 +11454,7 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "ztracing" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" dependencies = [ "tracing", "tracing-subscriber", @@ -11455,7 +11465,7 @@ dependencies = [ [[package]] name = "ztracing_macro" version = "0.1.0" -source = "git+https://github.com/zed-industries/zed#6ad3c7f278e513875e0bbde5ee935f6c9a342b9c" +source = "git+https://github.com/zed-industries/zed#7960b2a7c9568e90fbe0727332149e5b2a5fd57a" [[package]] name = "zune-core" diff --git a/crates/signed_state/src/local_repos.rs b/crates/signed_state/src/local_repos.rs index ac2607d..2a072e3 100644 --- a/crates/signed_state/src/local_repos.rs +++ b/crates/signed_state/src/local_repos.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use anyhow::Error; -use gpui::{App, AppContext, Context, Entity, Global, Task}; +use gpui::{App, AppContext, Context, Entity, Global, SharedString, Task}; use signed_core::{Announcement, RepoAddr, repo_addr}; use signed_git::{LocalRepo, Nip34Binding, find_git_repos}; @@ -126,6 +126,16 @@ pub struct ResolvedLocalRepo { pub announcement: Option, } +impl ResolvedLocalRepo { + /// The repository's directory name, or `Untitled` when the path has none. + 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")) + } +} + /// Resolve the scanned repositories against the known announcements. pub fn resolve_local_repos( repos: &[LocalRepo], @@ -253,4 +263,28 @@ mod tests { assert!(resolved[0].nip34.is_none()); assert!(resolved[0].announcement.is_none()); } + + #[test] + fn the_name_is_the_directory_name() { + let repo = LocalRepo { + path: PathBuf::from("/tmp/my-repo"), + nip34: None, + }; + + let resolved = resolve_local_repos(&[repo], &[], &[]); + + assert_eq!(resolved[0].name(), SharedString::from("my-repo")); + } + + #[test] + fn a_path_without_a_directory_name_is_untitled() { + let repo = LocalRepo { + path: PathBuf::from("/"), + nip34: None, + }; + + let resolved = resolve_local_repos(&[repo], &[], &[]); + + assert_eq!(resolved[0].name(), SharedString::from("Untitled")); + } } diff --git a/crates/signed_ui/src/pixel_avatar.rs b/crates/signed_ui/src/pixel_avatar.rs index f39a529..18a56f0 100644 --- a/crates/signed_ui/src/pixel_avatar.rs +++ b/crates/signed_ui/src/pixel_avatar.rs @@ -1,7 +1,7 @@ use gpui::prelude::*; use gpui::{App, Pixels, StyleRefinement, Window, div, px}; use gpui_base::StyledExt; -use gpui_component::{ActiveTheme, Colorize}; +use gpui_component::{ActiveTheme, Colorize, Sizable, Size}; /// Number of rows and columns in the pixel grid. const GRID_SIZE: usize = 8; @@ -10,34 +10,36 @@ const FILL_PROBABILITY: f32 = 0.42; /// Probability that a filled cell uses the accent shade instead of the main color. const ACCENT_PROBABILITY: f32 = 0.25; /// Minimum number of filled left-half cells. -/// A sparse roll still yields a recognizable shape. -/// Each left-half cell is mirrored to a right-half one. const MIN_FILLED: usize = 5; -/// Side length of the avatar in pixels, no setter. -const AVATAR_SIZE: Pixels = px(16.); - /// A deterministic, offline pixel-art avatar. -/// An 8×8 grid with horizontal mirror symmetry. -/// Seeded from a stable string such as the repository id and owner public key. -/// The same seed always renders the same avatar. #[derive(IntoElement)] pub struct PixelAvatar { seed: u64, + size: Size, style: StyleRefinement, } impl PixelAvatar { /// Create an avatar seeded from `seed`. + /// /// The seed should be a stable string unique to the entity the avatar represents. pub fn new(seed: impl AsRef) -> Self { Self { seed: fnv1a(seed.as_ref().as_bytes()), + size: Size::XSmall, style: StyleRefinement::default(), } } } +impl Sizable for PixelAvatar { + fn with_size(mut self, size: impl Into) -> Self { + self.size = size.into(); + self + } +} + impl Styled for PixelAvatar { fn style(&mut self) -> &mut StyleRefinement { &mut self.style @@ -48,16 +50,17 @@ impl RenderOnce for PixelAvatar { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let pattern = pattern(self.seed); + let mut cells = Vec::new(); let hue = self.seed as f32 / u64::MAX as f32; let main = theme.blue.hue(hue); + let shade = if theme.is_dark() { main.lightness((main.l * 1.6).min(0.95)) } else { main.lightness((main.l * 0.45).max(0.18)) }; - let mut cells = Vec::new(); for row in 0..GRID_SIZE { for col in 0..GRID_SIZE { let value = pattern[row * GRID_SIZE + col]; @@ -80,7 +83,7 @@ impl RenderOnce for PixelAvatar { .grid() .grid_cols(GRID_SIZE as u16) .grid_rows(GRID_SIZE as u16) - .size(AVATAR_SIZE) + .size(side_length(self.size)) .flex_shrink_0() .overflow_hidden() .bg(main.opacity(0.16)) @@ -88,9 +91,16 @@ impl RenderOnce for PixelAvatar { } } -/// Generate the 8×8 cell pattern for `seed`. -/// Cells are `0` for empty, `1` for main color and `2` for accent shade. -/// The right half mirrors the left half. +fn side_length(size: Size) -> Pixels { + match size { + Size::XSmall => px(16.), + Size::Small => px(24.), + Size::Medium => px(48.), + Size::Large => px(80.), + Size::Size(size) => size, + } +} + fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] { let mut rng = PixelRng::new(seed); let mut pattern = [0u8; GRID_SIZE * GRID_SIZE]; @@ -106,18 +116,19 @@ fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] { } } - // Sparse rolls can come out nearly empty. - // Top the pattern up to the minimum fill, scanning from a seeded starting cell. if filled < MIN_FILLED { let half = GRID_SIZE * GRID_SIZE / 2; let start = (rng.next() % half as u64) as usize; + for offset in 0..half { if filled >= MIN_FILLED { break; } + let ix = (start + offset) % half; let row = ix / (GRID_SIZE / 2); let col = ix % (GRID_SIZE / 2); + if pattern[row * GRID_SIZE + col] == 0 { set_cell(&mut pattern, row, col, 1); filled += 1; diff --git a/crates/workspace/src/views/sidebar/mod.rs b/crates/workspace/src/views/sidebar/mod.rs index 5f2df34..4f0804d 100644 --- a/crates/workspace/src/views/sidebar/mod.rs +++ b/crates/workspace/src/views/sidebar/mod.rs @@ -10,9 +10,8 @@ use dock::{ }; use gpui::prelude::*; use gpui::{ - AnyElement, App, Context, Div, Entity, EventEmitter, FocusHandle, Focusable, Hsla, ObjectFit, - Render, SharedString, Subscription, WeakEntity, Window, div, img, px, relative, uniform_list, - white, + AnyElement, App, Context, Div, Entity, EventEmitter, FocusHandle, Focusable, ObjectFit, Render, + SharedString, Subscription, WeakEntity, Window, div, img, px, relative, uniform_list, white, }; use gpui_base::Button as BaseButton; use gpui_component::button::{Button, ButtonVariants}; @@ -37,8 +36,8 @@ mod settings_dialog; use self::onboarding_dialog::OnboardingState; -/// The tool that bound a repository, `"nak"` or `"ngit"`. -fn local_tool(binding: &Nip34Binding) -> Option<&'static str> { +/// The platform that bound a repository, `"nak"` or `"ngit"`. +fn local_platform(binding: &Nip34Binding) -> Option<&'static str> { let signals = &binding.signals; if signals.nip34_json || signals.nip34_grasp_remote || signals.nip34_state_refs { @@ -485,34 +484,43 @@ impl SidebarPanel { entry: &ResolvedLocalRepo, cx: &mut Context, ) -> impl IntoElement { - let name = entry - .path - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or("Untitled".into()); - let avatar = PixelAvatar::new(entry.path.to_string_lossy()); - - let suffix: AnyElement = match entry.nip34.as_ref().map(|binding| binding.kind) { - Some(Nip34Kind::Initialized) => { - let label = match entry.nip34.as_ref().and_then(local_tool) { - Some(tool) => format!("NIP-34 · {tool}"), - None => "NIP-34".to_owned(), - }; - local_badge(&label, cx.theme().muted_foreground) - } - Some(Nip34Kind::Cloned) => local_badge("NIP-34 clone", cx.theme().muted_foreground), - Some(Nip34Kind::ToolingOnly) => { - local_badge("Nostr tooling", cx.theme().muted_foreground) - } - None => Icon::new(IconName::TriangleAlert) - .small() - .text_color(cx.theme().warning) - .into_any_element(), - }; + let name = entry.name(); + let avatar = local_avatar(entry, cx); let id = format!("local-repo:{}", entry.path.display()); let entry = entry.clone(); + let suffix: AnyElement = match entry.nip34.as_ref() { + Some(binding) => { + let (label, tooltip) = match binding.kind { + Nip34Kind::Initialized => { + let platform = local_platform(binding).unwrap_or("Grasp"); + let tooltip = match platform { + "nak" => "Initialized with nak", + "ngit" => "Initialized with ngit", + _ => "Initialized for NIP-34", + }; + (platform, tooltip) + } + Nip34Kind::Cloned => ("Cloned", "Cloned buts not initialized"), + Nip34Kind::ToolingOnly => ("Tooling", "Grasp tooling only"), + }; + + Button::new(id.clone()) + .xsmall() + .child(div().text_size(px(10.)).child(label)) + .tooltip(tooltip) + .secondary() + .into_any_element() + } + None => Button::new(id.clone()) + .xsmall() + .icon(IconName::TriangleAlert) + .tooltip("Not published yet") + .ghost() + .into_any_element(), + }; + NavItem::new(id, name, avatar) .suffix(suffix) .on_click(cx.listener(move |this, _ev, window, cx| { @@ -644,12 +652,27 @@ pub(super) fn server_host(relay: &RelayUrl) -> SharedString { .unwrap_or_else(|| SharedString::from(relay.to_string())) } -fn local_badge(label: &str, color: Hsla) -> AnyElement { +/// The repository's pixel avatar, with the bound owner's avatar at its bottom right. +fn local_avatar(entry: &ResolvedLocalRepo, cx: &App) -> AnyElement { + let avatar = PixelAvatar::new(entry.path.to_string_lossy()); + + let Some(owner) = entry.nip34.as_ref().and_then(|binding| binding.owner) else { + return avatar.into_any_element(); + }; + + let store = ProfileStore::global(cx); + let profile = store.read(cx).get(&owner); + div() - .flex_shrink_0() - .text_xs() - .text_color(color) - .child(SharedString::from(label.to_owned())) + .relative() + .child(avatar) + .child( + div().absolute().bottom_neg_0p5().right_neg_0p5().child( + UserAvatar::new(profile.name()) + .picture(profile.picture()) + .size(px(14.)), + ), + ) .into_any_element() } -- 2.54.0 From ec459d6507d6533b372a54977b50d92e5d30b894 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Mon, 14 Sep 2026 11:03:02 +0700 Subject: [PATCH 8/8] . --- crates/workspace/src/views/repo/mod.rs | 49 ++++++++++++++------------ 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/crates/workspace/src/views/repo/mod.rs b/crates/workspace/src/views/repo/mod.rs index fe61c68..9007ea3 100644 --- a/crates/workspace/src/views/repo/mod.rs +++ b/crates/workspace/src/views/repo/mod.rs @@ -2017,30 +2017,33 @@ pub(super) fn repo_display_name(store: &RepoStore) -> SharedString { /// The owner and identifier a local repository is already bound to. fn bound_repo_label(binding: &Nip34Binding, cx: &App) -> AnyElement { - let owner = binding - .owner - .and_then(|owner| owner.to_bech32().ok()) - .map(|npub| middle_truncate(&npub, 12, 8)) - .unwrap_or_else(|| "a NIP-34 coordinate".to_owned()); + let store = ProfileStore::global(cx); + let profile = binding.owner.map(|pk| store.read(cx).get(&pk)); - let mut label = v_flex().flex_shrink_0().items_end().gap_1().child( - div() - .text_xs() - .text_color(cx.theme().muted_foreground) - .child(SharedString::from(format!("Bound to {owner}"))), - ); - - if let Some(identifier) = binding.identifier.as_deref() { - label = label.child( - div() - .text_xs() - .font_semibold() - .text_color(cx.theme().muted_foreground) - .child(SharedString::from(identifier.to_owned())), - ); - } - - label.into_any_element() + h_flex() + .flex_shrink_0() + .gap_2() + .text_sm() + .child("Initialized by") + .text_color(cx.theme().muted_foreground) + .when_some(profile, |this, profile| { + this.child( + h_flex() + .gap_1() + .text_color(cx.theme().foreground) + .child(UserAvatar::new(profile.name()).picture(profile.picture())) + .child(profile.name()), + ) + }) + .when_some(binding.identifier.as_deref(), |this, ident| { + this.child( + div() + .text_xs() + .font_semibold() + .child(SharedString::from(format!("/{ident}"))), + ) + }) + .into_any_element() } impl BasePanel for RepoDetailView { -- 2.54.0