Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a87030e929 | ||
|
|
272ddf2674 | ||
|
|
fa50e9f153 | ||
|
|
da22d26019 |
@@ -81,6 +81,8 @@ Both `cx.spawn` and `cx.background_spawn` return a `Task<R>`, which is a future
|
||||
|
||||
A task which doesn't do anything but provide a value can be created with `Task::ready(value)`.
|
||||
|
||||
Prefer keeping a task in a field over `.detach()` when the work belongs to a view or store. A detached task outlives the view that started it (for example, a repository panel the user has closed), while a task stored in a field is cancelled when that struct drops. A finished `Task` held in a container is not reaped by GPUI - it stays alive until its handle is dropped - so if the container can accumulate many runs, either drop the finished handles before pushing a new one, or hold a single `Option<Task<_>>` and replace it.
|
||||
|
||||
## Elements
|
||||
|
||||
The `Render` trait is used to render some state into an element tree that is laid out using flexbox layout. An `Entity<T>` where `T` implements `Render` is sometimes called a "view".
|
||||
|
||||
@@ -7,19 +7,28 @@
|
||||
### Added
|
||||
|
||||
- Show an avatar in each panel's tab, using the repository owner's profile picture when set and a pixel avatar otherwise
|
||||
- Add a Tab Bar setting to hide the previous/next tab buttons, hidden by default
|
||||
- Add an Event Fetching Strategy setting, fetching a repository's activity from its announced relays only (Curated) or from every maintainer's relays as well (Uncensored, the default)
|
||||
|
||||
### Changed
|
||||
|
||||
- Migrate the GPUI foundation to the published `gpui-pre` crates and GPUI Kit 0.6, off the zed and gpui-component git pins
|
||||
- Use the pixel avatar as the single fallback for a missing picture, sized and rounded to match the other avatars
|
||||
- Redesign the dock tab bar, using muted grey active tab, added close buttons, double-click to zoom, and removed panel toolbar
|
||||
- Connect to bootstrap relays on demand instead of at startup
|
||||
- Fetch profile metadata in batches of 100 authors, applying every requested profile in a single database query
|
||||
- Prefetch the 500 most recent profiles at startup instead of 200
|
||||
|
||||
### Fixed
|
||||
|
||||
- Render every avatar at one consistent size, where a surrounding border had shrunk pictures by two pixels and the pixel avatar ignored an explicit size
|
||||
- Date repositories from their repository state event, so the explore list and open repository views show the latest push instead of the announcement date
|
||||
- Fix background tasks outliving their view, so a closed repository panel or pull request view stops fetching and publishing on its own
|
||||
|
||||
### Removed
|
||||
|
||||
- Remove cover note support, the kind-1624 GitWorkshop and `ngit` extension outside the NIP-34
|
||||
|
||||
### Deprecated
|
||||
|
||||
## v0.1.0-alpha - 2026/09/14
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ members = ["crates/*", "desktop"]
|
||||
default-members = ["desktop"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0-alpha"
|
||||
version = "0.2.0-alpha"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
|
||||
@@ -18,6 +18,16 @@ pub enum AppearanceMode {
|
||||
Dark,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum EventFetchingStrategy {
|
||||
/// Only the relays declared in the repository announcement.
|
||||
Curated,
|
||||
/// Repository relays plus every maintainer's NIP-65 relays.
|
||||
#[default]
|
||||
Uncensored,
|
||||
}
|
||||
|
||||
/// Fields mirror the gpui-component `Theme` surface customized at startup.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
@@ -141,6 +151,7 @@ pub struct CreateRepositorySettings {
|
||||
#[serde(default)]
|
||||
pub struct Settings {
|
||||
pub appearance: AppearanceMode,
|
||||
pub event_fetching: EventFetchingStrategy,
|
||||
pub theme: ThemeSettings,
|
||||
pub tab_bar: TabBarSettings,
|
||||
pub grasp_servers: GraspServersSettings,
|
||||
@@ -157,6 +168,7 @@ mod tests {
|
||||
fn json_roundtrip_preserves_everything() {
|
||||
let settings = Settings {
|
||||
appearance: AppearanceMode::Dark,
|
||||
event_fetching: EventFetchingStrategy::Curated,
|
||||
theme: ThemeSettings {
|
||||
radius: 8.0,
|
||||
..Default::default()
|
||||
@@ -178,9 +190,19 @@ mod tests {
|
||||
serde_json::from_str(r#"{"appearance": "dark", "theme": {"radius": 4.0}}"#).unwrap();
|
||||
assert_eq!(settings.appearance, AppearanceMode::Dark);
|
||||
assert_eq!(settings.theme.radius, 4.0);
|
||||
// Unset fields fall back to their defaults, including the fetching strategy.
|
||||
assert_eq!(settings.event_fetching, EventFetchingStrategy::Uncensored);
|
||||
// The rest of the theme and the other groups keep their defaults.
|
||||
assert_eq!(settings.theme.light_theme, "Signed Light");
|
||||
assert_eq!(settings.grasp_servers, GraspServersSettings::default());
|
||||
assert_eq!(settings.create_repository.default_folder, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_fetching_uses_snake_case() {
|
||||
let json = serde_json::to_string(&EventFetchingStrategy::Curated).unwrap();
|
||||
assert_eq!(json, r#""curated""#);
|
||||
let parsed: EventFetchingStrategy = serde_json::from_str(r#""uncensored""#).unwrap();
|
||||
assert_eq!(parsed, EventFetchingStrategy::Uncensored);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
use nostr::prelude::*;
|
||||
|
||||
/// GitWorkshop and `ngit` cover-note extension, kind 1624.
|
||||
///
|
||||
/// A markdown note attached to an issue, patch or PR by its author or a maintainer,
|
||||
/// not part of the NIP-34 draft, read support for interop.
|
||||
pub const COVER_NOTE_KIND: Kind = Kind::Custom(1624);
|
||||
@@ -2,7 +2,7 @@ use std::time::Duration;
|
||||
|
||||
use nostr::prelude::*;
|
||||
|
||||
use crate::{COVER_NOTE_KIND, RepoAddr};
|
||||
use crate::RepoAddr;
|
||||
|
||||
/// Kinds that make up the activity of a repository.
|
||||
pub const ACTIVITY_KINDS: [Kind; 9] = [
|
||||
@@ -18,19 +18,18 @@ pub const ACTIVITY_KINDS: [Kind; 9] = [
|
||||
];
|
||||
|
||||
/// Kinds that notify a user when they tag them via their `p` tag.
|
||||
pub const NOTIFICATION_KINDS: [Kind; 9] = [
|
||||
pub const NOTIFICATION_KINDS: [Kind; 8] = [
|
||||
Kind::GitIssue,
|
||||
Kind::GitPullRequest,
|
||||
Kind::GitPatch,
|
||||
Kind::GitPullRequestUpdate,
|
||||
COVER_NOTE_KIND,
|
||||
Kind::GitStatusOpen,
|
||||
Kind::GitStatusApplied,
|
||||
Kind::GitStatusClosed,
|
||||
Kind::GitStatusDraft,
|
||||
];
|
||||
|
||||
/// Git root kinds that make a comment or cover note count as git activity.
|
||||
/// Git root kinds that make a comment count as git activity.
|
||||
const GIT_ROOT_KINDS: [Kind; 4] = [
|
||||
Kind::GitIssue,
|
||||
Kind::GitPatch,
|
||||
@@ -38,6 +37,15 @@ const GIT_ROOT_KINDS: [Kind; 4] = [
|
||||
Kind::GitRepoAnnouncement,
|
||||
];
|
||||
|
||||
/// Kinds that carry repository data: announcements, states, activity and deletions.
|
||||
pub fn is_repo_kind(kind: Kind) -> bool {
|
||||
kind == Kind::GitRepoAnnouncement
|
||||
|| kind == Kind::RepoState
|
||||
|| kind == Kind::EventDeletion
|
||||
|| kind == Kind::RequestToVanish
|
||||
|| ACTIVITY_KINDS.contains(&kind)
|
||||
}
|
||||
|
||||
/// Value of the first tag named `name` on `event`.
|
||||
fn tag_value<'a>(event: &'a Event, name: &str) -> Option<&'a str> {
|
||||
event
|
||||
@@ -140,13 +148,7 @@ pub fn notifications(me: PublicKey) -> Vec<Filter> {
|
||||
/// A comment on an unrelated kind is matched too, so results must be filtered
|
||||
/// through [`is_git_activity`] before display.
|
||||
pub fn authored_activity(me: PublicKey) -> Filter {
|
||||
Filter::new()
|
||||
.kinds(
|
||||
ACTIVITY_KINDS
|
||||
.into_iter()
|
||||
.chain(std::iter::once(COVER_NOTE_KIND)),
|
||||
)
|
||||
.author(me)
|
||||
Filter::new().kinds(ACTIVITY_KINDS).author(me)
|
||||
}
|
||||
|
||||
/// Whether a kind-1111 comment targets a git root, checked via its `K` tag.
|
||||
@@ -155,12 +157,6 @@ fn is_git_comment(event: &Event) -> bool {
|
||||
&& tag_kind(event, "K").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
|
||||
}
|
||||
|
||||
/// Whether a kind-1624 cover note targets a git root, checked via its `k` tag.
|
||||
fn is_git_cover_note(event: &Event) -> bool {
|
||||
event.kind == COVER_NOTE_KIND
|
||||
&& tag_kind(event, "k").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
|
||||
}
|
||||
|
||||
/// Whether a status event references a git root, checked via its `k` tag.
|
||||
fn is_git_status(event: &Event) -> bool {
|
||||
tag_kind(event, "k").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
|
||||
@@ -175,7 +171,7 @@ pub fn is_git_activity(event: &Event) -> bool {
|
||||
| Kind::GitStatusApplied
|
||||
| Kind::GitStatusClosed
|
||||
| Kind::GitStatusDraft => is_git_status(event),
|
||||
kind => kind == COVER_NOTE_KIND && is_git_cover_note(event),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,6 +180,11 @@ pub fn all_announcements() -> Filter {
|
||||
Filter::new().kind(Kind::GitRepoAnnouncement)
|
||||
}
|
||||
|
||||
/// All repository state events, carrying each repository's refs and last push time.
|
||||
pub fn all_states() -> Filter {
|
||||
Filter::new().kind(Kind::RepoState)
|
||||
}
|
||||
|
||||
/// How far back deletion requests are fetched and stored.
|
||||
const DELETIONS_LOOKBACK: Duration = Duration::from_secs(3 * 365 * 86_400);
|
||||
|
||||
@@ -262,17 +263,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_and_cover_note_activity_depend_on_the_lowercase_k_tag() {
|
||||
fn status_activity_depends_on_the_lowercase_k_tag() {
|
||||
let status = signed(
|
||||
&keys(1),
|
||||
Kind::GitStatusClosed,
|
||||
vec![kind_tag("k", Kind::GitPullRequest)],
|
||||
);
|
||||
let cover = signed(
|
||||
&keys(1),
|
||||
COVER_NOTE_KIND,
|
||||
vec![kind_tag("k", Kind::GitPatch)],
|
||||
);
|
||||
let unrelated = signed(
|
||||
&keys(1),
|
||||
Kind::GitStatusClosed,
|
||||
@@ -280,7 +276,6 @@ mod tests {
|
||||
);
|
||||
|
||||
assert!(is_git_activity(&status));
|
||||
assert!(is_git_activity(&cover));
|
||||
assert!(!is_git_activity(&unrelated));
|
||||
assert!(!is_git_activity(&signed(
|
||||
&keys(1),
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::time::Duration;
|
||||
use nostr::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{COVER_NOTE_KIND, RepoAddr, activity_subject};
|
||||
use crate::{RepoAddr, activity_subject};
|
||||
|
||||
/// Window before `now` that an advanced cutoff retreats to.
|
||||
const ADVANCE_WINDOW: Duration = Duration::from_secs(3 * 24 * 60 * 60);
|
||||
@@ -121,14 +121,11 @@ impl InboxItem {
|
||||
/// - patch (1617): its `e` parent patch, else itself
|
||||
/// - NIP-22 comment (1111): uppercase `E` root pointer
|
||||
/// - PR update (1619): uppercase `E`
|
||||
/// - statuses (1630-1633) / cover note (1624): NIP-10 root `e`
|
||||
/// - statuses (1630-1633): NIP-10 root `e`
|
||||
pub fn notification_root<L>(event: &Event, lookup: &L) -> Option<EventId>
|
||||
where
|
||||
L: Fn(EventId) -> Option<Event>,
|
||||
{
|
||||
if event.kind == COVER_NOTE_KIND {
|
||||
return nip10_root_id(event).map(|root| resolve_thread_root(root, lookup));
|
||||
}
|
||||
match event.kind {
|
||||
Kind::GitIssue | Kind::GitPullRequest => Some(event.id),
|
||||
Kind::GitPatch => Some(match first_e_id(event) {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
pub mod addr;
|
||||
pub mod annotations;
|
||||
pub mod deletions;
|
||||
pub mod filters;
|
||||
pub mod inbox;
|
||||
@@ -8,7 +7,6 @@ pub mod state;
|
||||
pub mod status;
|
||||
|
||||
pub use addr::{RepoAddr, identifier_from_name, repo_addr};
|
||||
pub use annotations::COVER_NOTE_KIND;
|
||||
pub use deletions::Deletions;
|
||||
pub use filters::{
|
||||
NOTIFICATION_KINDS, authored_activity, is_git_activity, notification_comments, notifications,
|
||||
|
||||
+158
-137
@@ -21,15 +21,8 @@ use crate::repos::RepoListStore;
|
||||
pub const USER_KEYRING: &str = "Signed Safe Storage";
|
||||
/// Timeout for NIP-46 signer responses.
|
||||
pub const NOSTR_CONNECT_TIMEOUT: u64 = 60;
|
||||
|
||||
/// Relays connected at startup, before any user-specific relay config is known.
|
||||
pub const BOOTSTRAP_RELAYS: [&str; 4] = [
|
||||
"wss://relay.primal.net",
|
||||
"wss://relay.ditto.pub",
|
||||
"wss://index.ngit.dev",
|
||||
"wss://profiles.nostr1.com",
|
||||
];
|
||||
|
||||
pub const BOOTSTRAP_RELAYS: [&str; 2] = ["wss://relay.ditto.pub", "wss://index.ngit.dev"];
|
||||
/// Relays used to index the user's NIP-65 relay list.
|
||||
pub const INDEXER_RELAYS: [&str; 2] = ["wss://indexer.coracle.social", "wss://user.kindpag.es"];
|
||||
|
||||
@@ -42,20 +35,15 @@ pub enum BackendEvent {
|
||||
PassphraseRequired,
|
||||
/// The signer changed on login, logout or account switch.
|
||||
SignerChanged,
|
||||
/// New events were received from a relay and stored in the database.
|
||||
///
|
||||
/// Batched: [`Backend`]'s notification pump coalesces everything a
|
||||
/// relay delivers within one debounce window into a single event,
|
||||
/// instead of emitting per-event and making every subscriber debounce
|
||||
/// the same burst independently.
|
||||
NostrUpdate(Vec<Update>),
|
||||
/// Kind-0 metadata arrived for these authors; re-read them from the store.
|
||||
ProfileUpdates(Vec<PublicKey>),
|
||||
/// Repository events arrived: announcements, states, activity and deletions.
|
||||
RepoUpdates(Vec<Update>),
|
||||
Synced,
|
||||
SyncProgress {
|
||||
total: u64,
|
||||
current: u64,
|
||||
},
|
||||
/// An event built locally was signed, broadcast and stored.
|
||||
Published(Box<Event>),
|
||||
Error(String),
|
||||
}
|
||||
|
||||
@@ -100,14 +88,16 @@ impl Backend {
|
||||
|
||||
let pump: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
let mut notifications = pump_client.notifications();
|
||||
let mut pending: Vec<Update> = Vec::new();
|
||||
let mut pending_profiles: HashSet<PublicKey> = HashSet::new();
|
||||
let mut pending_repos: Vec<Update> = Vec::new();
|
||||
let mut seen: HashSet<EventId> = HashSet::new();
|
||||
|
||||
'outer: loop {
|
||||
match notifications.next().await {
|
||||
Some(ClientNotification::Event { event, .. }) => {
|
||||
pending.push(Update::from_event(&event));
|
||||
match next_update(&mut notifications, &mut seen).await {
|
||||
Some(UpdateEvent::Profile(author)) => {
|
||||
pending_profiles.insert(author);
|
||||
}
|
||||
Some(_) => continue,
|
||||
Some(UpdateEvent::Repo(update)) => pending_repos.push(update),
|
||||
None => break,
|
||||
}
|
||||
|
||||
@@ -123,28 +113,33 @@ impl Backend {
|
||||
let timer = cx.background_executor().timer(deadline - now);
|
||||
futures::pin_mut!(timer);
|
||||
|
||||
let next = notifications.next();
|
||||
let next = next_update(&mut notifications, &mut seen);
|
||||
futures::pin_mut!(next);
|
||||
|
||||
match futures::future::select(next, timer).await {
|
||||
futures::future::Either::Left((
|
||||
Some(ClientNotification::Event { event, .. }),
|
||||
_,
|
||||
)) => {
|
||||
pending.push(Update::from_event(&event));
|
||||
futures::future::Either::Left((Some(UpdateEvent::Profile(author)), _)) => {
|
||||
pending_profiles.insert(author);
|
||||
}
|
||||
futures::future::Either::Left((Some(UpdateEvent::Repo(update)), _)) => {
|
||||
pending_repos.push(update);
|
||||
}
|
||||
futures::future::Either::Left((Some(_), _)) => continue,
|
||||
futures::future::Either::Left((None, _)) => break 'outer,
|
||||
futures::future::Either::Right(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let batch = std::mem::take(&mut pending);
|
||||
let profiles: Vec<PublicKey> = pending_profiles.drain().collect();
|
||||
let repos = std::mem::take(&mut pending_repos);
|
||||
|
||||
if let Err(e) =
|
||||
this.update(cx, |_this, cx| cx.emit(BackendEvent::NostrUpdate(batch)))
|
||||
{
|
||||
log::warn!("failed to emit nostr update: {e}");
|
||||
if let Err(e) = this.update(cx, |_this, cx| {
|
||||
if !profiles.is_empty() {
|
||||
cx.emit(BackendEvent::ProfileUpdates(profiles));
|
||||
}
|
||||
if !repos.is_empty() {
|
||||
cx.emit(BackendEvent::RepoUpdates(repos));
|
||||
}
|
||||
}) {
|
||||
log::warn!("failed to emit backend update: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,9 +149,10 @@ impl Backend {
|
||||
pump.detach();
|
||||
|
||||
cx.defer(move |cx| {
|
||||
if let Err(error) = weak.update(cx, |this, cx| this.bootstrap(cx)) {
|
||||
log::warn!("backend dropped before bootstrap could run: {error}");
|
||||
}
|
||||
weak.update(cx, |this, cx| {
|
||||
this.restore_session(cx);
|
||||
})
|
||||
.ok();
|
||||
});
|
||||
|
||||
Self {
|
||||
@@ -170,42 +166,6 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
|
||||
fn bootstrap(&mut self, cx: &mut Context<Self>) {
|
||||
let client = self.client.clone();
|
||||
|
||||
let task = cx.background_spawn(async move {
|
||||
for url in BOOTSTRAP_RELAYS {
|
||||
client.add_relay(url).await?;
|
||||
}
|
||||
|
||||
for url in INDEXER_RELAYS {
|
||||
client
|
||||
.add_relay(url)
|
||||
.capabilities(RelayCapabilities::DISCOVERY)
|
||||
.await?;
|
||||
}
|
||||
|
||||
client.connect().await;
|
||||
|
||||
Ok::<(), Error>(())
|
||||
});
|
||||
|
||||
let notify_task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
match task.await {
|
||||
Ok(()) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.restore_session(cx);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| cx.emit(BackendEvent::error(e.to_string())))?;
|
||||
}
|
||||
}
|
||||
Ok::<(), Error>(())
|
||||
});
|
||||
notify_task.detach();
|
||||
}
|
||||
|
||||
/// Restore the saved session from the Keyring.
|
||||
///
|
||||
/// - Emits [`BackendEvent::SignerRequired`] when no credential is stored.
|
||||
@@ -230,7 +190,9 @@ impl Backend {
|
||||
let result = async {
|
||||
if content.starts_with("nsec1") {
|
||||
let keys = Keys::new(SecretKey::parse(&content)?);
|
||||
this.update(cx, |this, cx| this.set_signer(keys, cx))?;
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(keys, cx);
|
||||
})?;
|
||||
} else if content.starts_with("bunker://") {
|
||||
let (base, keys) = extract_master_key(&content);
|
||||
let uri = NostrConnectUri::parse(base)?;
|
||||
@@ -241,14 +203,19 @@ impl Backend {
|
||||
None,
|
||||
)?;
|
||||
signer.auth_url_handler(SignedAuthUrlHandler);
|
||||
this.update(cx, |this, cx| this.set_signer(signer, cx))?;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_signer(signer, cx);
|
||||
})?;
|
||||
} else if content.starts_with("ncryptsec1") {
|
||||
this.update(cx, |this, cx| {
|
||||
this.passphrase_required = true;
|
||||
cx.emit(BackendEvent::PassphraseRequired);
|
||||
})?;
|
||||
} else {
|
||||
this.update(cx, |_this, cx| cx.emit(BackendEvent::SignerRequired))?;
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::SignerRequired);
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok::<_, Error>(())
|
||||
@@ -446,9 +413,6 @@ impl Backend {
|
||||
let client = self.client.clone();
|
||||
|
||||
// Initialize directly at the user's chosen destination.
|
||||
// No mirror is pre-populated: `GitCache::ensure_clone` lazily clones
|
||||
// from the grasp server the first time the repo detail view needs it,
|
||||
// exactly like every other repository.
|
||||
let destination = {
|
||||
let dir_name = signed_git::sanitize_path_component(&name);
|
||||
let dir_name = if dir_name.is_empty() {
|
||||
@@ -513,9 +477,7 @@ impl Backend {
|
||||
let builder = announcement.into_event_builder();
|
||||
let event = builder.finalize_async(&signer).await?;
|
||||
let output = client.send_event(&event).broadcast().await?;
|
||||
let event = require_relay_accepted(output, event)?;
|
||||
this.update(cx, |this, cx| this.announce_published(event.clone(), cx))?;
|
||||
event
|
||||
require_relay_accepted(output, event)?
|
||||
};
|
||||
|
||||
// The state event is the push authorization. Stage it on each
|
||||
@@ -570,14 +532,10 @@ impl Backend {
|
||||
// Fan the state out to the relays once a git server holds the objects.
|
||||
// Staging already stored the event locally, publishing makes it
|
||||
// visible to the other relays and clients.
|
||||
if let Some(state_event) = &outcome.state_event {
|
||||
if let Err(e) = client.send_event(state_event).broadcast().await {
|
||||
log::warn!("failed to broadcast repository state: {e}");
|
||||
}
|
||||
this.update(cx, |this, cx| {
|
||||
this.announce_published(state_event.clone(), cx)
|
||||
})
|
||||
.ok();
|
||||
if let Some(state_event) = &outcome.state_event
|
||||
&& let Err(e) = client.send_event(state_event).broadcast().await
|
||||
{
|
||||
log::warn!("failed to broadcast repository state: {e}");
|
||||
}
|
||||
|
||||
let announcement = Announcement::from_event(&event)
|
||||
@@ -666,9 +624,7 @@ impl Backend {
|
||||
let builder = announcement.into_event_builder();
|
||||
let event = builder.finalize_async(&signer).await?;
|
||||
let output = client.send_event(&event).broadcast().await?;
|
||||
let event = require_relay_accepted(output, event)?;
|
||||
this.update(cx, |this, cx| this.announce_published(event.clone(), cx))?;
|
||||
event
|
||||
require_relay_accepted(output, event)?
|
||||
};
|
||||
|
||||
let refs = state.refs.clone();
|
||||
@@ -725,12 +681,10 @@ impl Backend {
|
||||
|
||||
// Fan the state out to the relays once a git server holds the objects.
|
||||
// Staging already stored the event locally, publishing makes it visible to the other relays and clients.
|
||||
if let Some(state_event) = &outcome.state_event {
|
||||
if let Err(e) = client.send_event(state_event).broadcast().await {
|
||||
log::warn!("failed to broadcast repository state: {e}");
|
||||
}
|
||||
this.update(cx, |this, cx| this.announce_published(state_event.clone(), cx))
|
||||
.ok();
|
||||
if let Some(state_event) = &outcome.state_event
|
||||
&& let Err(e) = client.send_event(state_event).broadcast().await
|
||||
{
|
||||
log::warn!("failed to broadcast repository state: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -907,14 +861,10 @@ impl Backend {
|
||||
// Fan the state out to the relays once a git server holds the objects.
|
||||
// Staging already stored the event locally, publishing notifies
|
||||
// the repository views and other relays and clients.
|
||||
if let Some(state_event) = &outcome.state_event {
|
||||
if let Err(e) = client.send_event(state_event).broadcast().await {
|
||||
log::warn!("failed to broadcast repository state: {e}");
|
||||
}
|
||||
this.update(cx, |this, cx| {
|
||||
this.announce_published(state_event.clone(), cx)
|
||||
})
|
||||
.ok();
|
||||
if let Some(state_event) = &outcome.state_event
|
||||
&& let Err(e) = client.send_event(state_event).broadcast().await
|
||||
{
|
||||
log::warn!("failed to broadcast repository state: {e}");
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
@@ -1086,7 +1036,7 @@ impl Backend {
|
||||
)
|
||||
.await?;
|
||||
|
||||
for url in user_grasp_list_servers(client.clone(), public_key).await? {
|
||||
for url in user_grasp_list_servers(&client, public_key).await? {
|
||||
client.add_relay(url).and_connect().await.ok();
|
||||
}
|
||||
|
||||
@@ -1205,6 +1155,21 @@ impl Backend {
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Sync filters through the SDK's NIP-65 gossip targeting.
|
||||
pub fn sync_auto(&mut self, filters: Vec<Filter>, cx: &mut Context<Self>) {
|
||||
let client = self.client.clone();
|
||||
|
||||
cx.spawn(async move |_this, _cx| {
|
||||
for filter in filters {
|
||||
if let Err(e) = client.sync(filter).await {
|
||||
log::warn!("gossip relay fetch failed: {e}");
|
||||
}
|
||||
}
|
||||
Ok::<(), Error>(())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
pub fn subscribe_bootstrap(&mut self, filters: Vec<Filter>, cx: &mut Context<Self>) {
|
||||
let client = self.client.clone();
|
||||
|
||||
@@ -1222,14 +1187,15 @@ impl Backend {
|
||||
.detach();
|
||||
}
|
||||
|
||||
pub fn sync_bootstrap(&mut self, filter: Filter, cx: &mut Context<Self>) {
|
||||
/// Sync several bootstrap filters in order, within a single task.
|
||||
pub fn sync_bootstraps(&mut self, filters: Vec<Filter>, cx: &mut Context<Self>) {
|
||||
let client = self.client.clone();
|
||||
let (tx, mut rx) = SyncProgress::channel();
|
||||
|
||||
self.sync_progress = Some((0, 0));
|
||||
cx.notify();
|
||||
|
||||
let progress_task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
cx.spawn(async move |this, cx| {
|
||||
let mut last_percent: u64 = 0;
|
||||
|
||||
while rx.changed().await.is_ok() {
|
||||
@@ -1254,23 +1220,29 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
});
|
||||
progress_task.detach();
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})
|
||||
.detach();
|
||||
|
||||
let sync = cx.background_spawn(async move {
|
||||
let opts = SyncOptions::default().progress(tx);
|
||||
sync_bootstrap_only(&client, filter, opts).await
|
||||
let mut first_error = None;
|
||||
|
||||
for filter in filters {
|
||||
let opts = SyncOptions::default().progress(tx.clone());
|
||||
if let Err(error) = sync_bootstrap_only(&client, filter, opts).await {
|
||||
first_error.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
|
||||
match first_error {
|
||||
Some(error) => Err(error),
|
||||
None => Ok(()),
|
||||
}
|
||||
});
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
cx.spawn(async move |this, cx| {
|
||||
match sync.await {
|
||||
Ok(summary) => {
|
||||
log::debug!(
|
||||
"sync done: {} received, {} sent",
|
||||
summary.received.len(),
|
||||
summary.sent.len()
|
||||
);
|
||||
Ok(_) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.sync_progress = None;
|
||||
cx.emit(BackendEvent::Synced);
|
||||
@@ -1284,17 +1256,10 @@ impl Backend {
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
}
|
||||
|
||||
/// Emit [`BackendEvent::Published`] for cross-store invalidation.
|
||||
///
|
||||
/// Callers publish with `client.send_event(...)` directly, then call this
|
||||
/// so stores like `RepoListStore` refresh without re-querying the relays.
|
||||
pub fn announce_published(&self, event: Event, cx: &mut Context<Self>) {
|
||||
cx.emit(BackendEvent::Published(Box::new(event)));
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Publish a NIP-09 deletion for each of `events`, best-effort.
|
||||
@@ -1319,6 +1284,42 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
|
||||
/// A relay event the backend routes to a store group.
|
||||
enum UpdateEvent {
|
||||
Profile(PublicKey),
|
||||
Repo(Update),
|
||||
}
|
||||
|
||||
/// Await the next relay event from the notification stream.
|
||||
async fn next_update(
|
||||
notifications: &mut (impl futures::Stream<Item = ClientNotification> + Unpin),
|
||||
seen: &mut HashSet<EventId>,
|
||||
) -> Option<UpdateEvent> {
|
||||
loop {
|
||||
match notifications.next().await {
|
||||
Some(ClientNotification::Message { message, .. }) => {
|
||||
let RelayMessage::Event { event, .. } = *message else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let update = match event.kind {
|
||||
Kind::Metadata => UpdateEvent::Profile(event.pubkey),
|
||||
kind if filters::is_repo_kind(kind) => {
|
||||
UpdateEvent::Repo(Update::from_event(&event))
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
if seen.insert(event.id) {
|
||||
return Some(update);
|
||||
}
|
||||
}
|
||||
Some(_) => continue,
|
||||
None => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sign and send a single NIP-09 deletion request for `event`.
|
||||
async fn retract_event(
|
||||
client: &Client,
|
||||
@@ -1328,16 +1329,14 @@ async fn retract_event(
|
||||
let builder = EventDeletionRequest::new()
|
||||
.id(event.id)
|
||||
.into_event_builder();
|
||||
|
||||
let deletion = builder.finalize_async(signer).await?;
|
||||
client.send_event(&deletion).broadcast().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The event was accepted by at least one relay, or a descriptive error otherwise.
|
||||
///
|
||||
/// The SDK does not treat "accepted by zero relays" as an error on its own:
|
||||
/// [`SendEventOutput::success`] may be empty while the call still returns `Ok`.
|
||||
/// This turns that case into an error the caller can surface.
|
||||
pub(crate) fn require_relay_accepted(
|
||||
output: SendEventOutput,
|
||||
event: Event,
|
||||
@@ -1395,10 +1394,29 @@ async fn connect_repo_relays(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add and connect the startup relays.
|
||||
async fn ensure_bootstrap_relays(client: &Client) -> Result<(), Error> {
|
||||
for url in BOOTSTRAP_RELAYS {
|
||||
client.add_relay(url).and_connect().await?;
|
||||
}
|
||||
|
||||
for url in INDEXER_RELAYS {
|
||||
client
|
||||
.add_relay(url)
|
||||
.capabilities(RelayCapabilities::DISCOVERY)
|
||||
.and_connect()
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn subscribe_bootstrap_only(
|
||||
client: &Client,
|
||||
filters: Vec<Filter>,
|
||||
) -> Result<(), Error> {
|
||||
ensure_bootstrap_relays(client).await?;
|
||||
|
||||
let opts = SubscribeAutoCloseOptions::default()
|
||||
.exit_policy(ReqExitPolicy::ExitOnEOSE)
|
||||
.timeout(Some(Duration::from_secs(10)));
|
||||
@@ -1418,11 +1436,14 @@ pub(crate) async fn sync_bootstrap_only(
|
||||
filter: Filter,
|
||||
opts: SyncOptions,
|
||||
) -> Result<SyncSummary, Error> {
|
||||
ensure_bootstrap_relays(client).await?;
|
||||
|
||||
let output = client
|
||||
.sync(filter)
|
||||
.with(BOOTSTRAP_RELAYS)
|
||||
.opts(opts)
|
||||
.await?;
|
||||
|
||||
Ok(output.value)
|
||||
}
|
||||
|
||||
@@ -1495,7 +1516,7 @@ fn latest_grasp_list_servers(events: Vec<Event>) -> Vec<RelayUrl> {
|
||||
}
|
||||
|
||||
pub async fn user_grasp_list_servers(
|
||||
client: Client,
|
||||
client: &Client,
|
||||
user: PublicKey,
|
||||
) -> Result<Vec<RelayUrl>, Error> {
|
||||
let events: Vec<Event> = client
|
||||
|
||||
@@ -17,15 +17,9 @@ use crate::repos::RepoListStore;
|
||||
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
||||
|
||||
/// How often the statuses are recomputed against the local refs.
|
||||
///
|
||||
/// A commit lands in a checkout long before the remote reconciliation cadence,
|
||||
/// so this fast pass surfaces ready-to-push and ready-to-contribute checkouts
|
||||
/// within a second or two. It reads the tracking refs only, no network.
|
||||
const LOCAL_POLL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// How often a full pass refreshes the remotes while any repository panel is open.
|
||||
const STATUS_POLL: Duration = Duration::from_secs(15);
|
||||
|
||||
/// Remote refresh interval for the `ready to push` badges of the user's own repositories.
|
||||
const PUSH_POLL: Duration = Duration::from_secs(60);
|
||||
|
||||
@@ -46,10 +40,6 @@ pub struct CheckoutStatus {
|
||||
/// Commit the branch points at, for tip-based PR dedupe.
|
||||
pub head: String,
|
||||
/// What the branch is compared against.
|
||||
/// For ready-to-contribute statuses, the announced HEAD branch.
|
||||
/// The fallbacks are `main`, then the first local branch.
|
||||
/// For ready-to-push statuses, the remote-tracking ref.
|
||||
/// Unpushed commits are counted against it.
|
||||
///
|
||||
/// It is `refs/remotes/origin/<branch>`, else `origin/HEAD` for new branches.
|
||||
pub base: String,
|
||||
@@ -67,11 +57,6 @@ struct Remembered {
|
||||
}
|
||||
|
||||
/// Global store of local-checkout associations and per-checkout statuses.
|
||||
///
|
||||
/// Readers (the sidebar rows, the repository panels) observe this store and
|
||||
/// derive what they display from their own snapshots, so publishing needs no
|
||||
/// fine-grained entities: the store notifies when a slice changed and each
|
||||
/// reader re-derives only what it shows.
|
||||
pub struct CheckoutsStore {
|
||||
/// Checkout paths per announced repository.
|
||||
by_repo: HashMap<RepoAddr, Vec<PathBuf>>,
|
||||
@@ -144,6 +129,7 @@ impl CheckoutsStore {
|
||||
this.statuses.clear();
|
||||
this.push_statuses.clear();
|
||||
cx.notify();
|
||||
|
||||
this.refresh(cx);
|
||||
}
|
||||
}));
|
||||
@@ -282,9 +268,6 @@ impl CheckoutsStore {
|
||||
}
|
||||
|
||||
/// Re-resolve the associations and the requested statuses.
|
||||
///
|
||||
/// Requests arriving while a pass runs fold into a follow-up, requests
|
||||
/// arriving while the debounce timer is pending are dropped.
|
||||
pub fn refresh(&mut self, cx: &mut Context<Self>) {
|
||||
if self.debounce_pending || self.refresh.request() != RefreshRequest::Schedule {
|
||||
return;
|
||||
@@ -300,12 +283,6 @@ impl CheckoutsStore {
|
||||
}
|
||||
|
||||
/// One full resolve and apply cycle, the debounced entry point.
|
||||
///
|
||||
/// Re-resolves the associations from the settings, the scan and the
|
||||
/// announcements, then recomputes the requested statuses against freshly
|
||||
/// fetched remotes. Full passes run on every input change and on the
|
||||
/// remote reconciliation cadence ([`Self::local_tick`]); they also restart
|
||||
/// the fast local pass.
|
||||
fn run_refresh(&mut self, cx: &mut Context<Self>) {
|
||||
self.debounce_pending = false;
|
||||
self.refresh.begin();
|
||||
@@ -431,10 +408,6 @@ impl CheckoutsStore {
|
||||
}
|
||||
|
||||
/// Schedule the fast local status pass, unless one is already pending.
|
||||
///
|
||||
/// Every [`LOCAL_POLL`] the pass recomputes the requested statuses against
|
||||
/// the local refs, with no network, so a new commit in a checkout surfaces in
|
||||
/// a second or two instead of at the next remote reconciliation.
|
||||
fn schedule_local_pass(&mut self, cx: &mut Context<Self>) {
|
||||
if self.local_pending {
|
||||
return;
|
||||
@@ -452,10 +425,6 @@ impl CheckoutsStore {
|
||||
}
|
||||
|
||||
/// The fast local status pass.
|
||||
///
|
||||
/// Recomputes the statuses against the local refs; when the remote
|
||||
/// reconciliation cadence elapsed, it runs a full pass instead so pushes
|
||||
/// made elsewhere do not linger as `to push`.
|
||||
fn local_tick(&mut self, cx: &mut Context<Self>) {
|
||||
// Nothing watched: the chain idles out until a new request restarts it.
|
||||
if self.status_requested.is_empty() && self.push_requested.is_empty() {
|
||||
@@ -490,10 +459,6 @@ impl CheckoutsStore {
|
||||
}
|
||||
|
||||
/// Recompute the requested statuses against the tracking refs only.
|
||||
///
|
||||
/// The refs were last refreshed by a full pass. Comparing against them is
|
||||
/// enough to pick up new local commits, and skipping the network keeps
|
||||
/// this pass cheap enough to run every [`LOCAL_POLL`].
|
||||
fn run_local_statuses(&mut self, cx: &mut Context<Self>) {
|
||||
let associations = self.by_repo.clone();
|
||||
|
||||
@@ -635,10 +600,6 @@ fn checkout_status(path: &Path, announced_head: Option<&str>) -> Option<Checkout
|
||||
}
|
||||
|
||||
/// The `ready to push` status of one checkout of the user's own repository.
|
||||
///
|
||||
/// `fetch` refreshes the remote heads first, so a full pass sees pushes made
|
||||
/// elsewhere; the fast local pass skips it and compares against the tracking
|
||||
/// refs left by the last full pass, which is enough to detect local commits.
|
||||
fn checkout_push_status(path: &Path, fetch: bool) -> Option<CheckoutStatus> {
|
||||
if signed_git::worktree_dirty(path) {
|
||||
return None;
|
||||
@@ -649,8 +610,6 @@ fn checkout_push_status(path: &Path, fetch: bool) -> Option<CheckoutStatus> {
|
||||
let origin = signed_git::origin_url(path).ok().flatten()?;
|
||||
|
||||
if fetch {
|
||||
// Refresh the remote heads first.
|
||||
// Commits made elsewhere or pushed from another machine must not linger as `to push`.
|
||||
signed_git::fetch_repo_refs(path, &[origin], "+refs/heads/*:refs/remotes/origin/*").ok();
|
||||
}
|
||||
|
||||
@@ -678,10 +637,6 @@ fn checkout_push_status(path: &Path, fetch: bool) -> Option<CheckoutStatus> {
|
||||
}
|
||||
|
||||
/// Compute the requested statuses against the checkout paths of `associations`.
|
||||
///
|
||||
/// Shared by the full and the local pass. `fetch` refreshes the checkouts'
|
||||
/// remote heads first, so the full pass sees remote moves; the fast local
|
||||
/// pass reads the tracking refs only, which is enough to detect local commits.
|
||||
fn compute_statuses(
|
||||
associations: &HashMap<RepoAddr, Vec<PathBuf>>,
|
||||
requested: &[(RepoAddr, Option<String>)],
|
||||
@@ -737,12 +692,14 @@ pub fn pr_proposes_checkout(
|
||||
if pr.kind != Kind::GitPullRequest || !open || pr.pubkey != user {
|
||||
return false;
|
||||
}
|
||||
|
||||
let branch_matches = pr
|
||||
.tags
|
||||
.iter()
|
||||
.find(|t| t.kind() == "branch-name")
|
||||
.and_then(|t| t.content())
|
||||
.is_some_and(|name| name == checkout.branch);
|
||||
|
||||
// A renamed branch falls back to the proposed tip commit.
|
||||
let tip_matches = pr
|
||||
.tags
|
||||
@@ -750,6 +707,7 @@ pub fn pr_proposes_checkout(
|
||||
.find(|t| t.kind() == "c")
|
||||
.and_then(|t| t.content())
|
||||
.is_some_and(|tip| tip == checkout.head);
|
||||
|
||||
branch_matches || tip_matches
|
||||
}
|
||||
|
||||
|
||||
@@ -104,11 +104,16 @@ impl Inbox {
|
||||
|
||||
/// Sign the state with a random key and store it locally.
|
||||
fn persist(&mut self, cx: &mut Context<Self>) {
|
||||
let Some(me) = Backend::global(cx).read(cx).current_user() else {
|
||||
let backend = Backend::global(cx);
|
||||
let (me, client) = {
|
||||
let backend = backend.read(cx);
|
||||
(backend.current_user(), backend.client())
|
||||
};
|
||||
|
||||
let Some(me) = me else {
|
||||
return;
|
||||
};
|
||||
|
||||
let client = Backend::global(cx).read(cx).client();
|
||||
let state = self.state.clone();
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
|
||||
|
||||
@@ -5,14 +5,20 @@ use std::time::{Duration, Instant};
|
||||
use anyhow::Error;
|
||||
use flume::{Receiver, Sender};
|
||||
use gpui::{
|
||||
App, AppContext, AsyncApp, Context, Entity, Global, SharedString, Subscription, Task,
|
||||
WeakEntity,
|
||||
App, AppContext, AsyncApp, Context, Entity, Global, SharedString, Subscription, WeakEntity,
|
||||
};
|
||||
use nostr_sdk::prelude::*;
|
||||
use utils::shorten_pubkey;
|
||||
|
||||
use crate::backend::{Backend, BackendEvent, sync_bootstrap_only};
|
||||
|
||||
/// How long to wait for more requests before firing a batched fetch.
|
||||
const BATCH_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
/// Max authors per profile request, keeping each filter within relay limits.
|
||||
const REQUEST_CHUNK: usize = 100;
|
||||
/// Recent profiles prefetched at startup and read back from the cache.
|
||||
const WARM_LIMIT: usize = 500;
|
||||
|
||||
/// A user profile as plain data for the UI, from the kind-0 metadata.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Profile {
|
||||
@@ -62,9 +68,6 @@ impl Profile {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long to wait for more requests before firing a batched sync.
|
||||
const BATCH_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Global profile cache.
|
||||
///
|
||||
/// Profiles are fetched in batches and kept as plain data.
|
||||
@@ -92,40 +95,26 @@ impl ProfileStore {
|
||||
|
||||
pub(crate) fn new(cx: &mut Context<Self>) -> Self {
|
||||
let backend = Backend::global(cx);
|
||||
let entity = cx.entity().downgrade();
|
||||
let client = backend.read(cx).client();
|
||||
|
||||
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| match event {
|
||||
BackendEvent::NostrUpdate(updates) => {
|
||||
for update in updates
|
||||
.iter()
|
||||
.filter(|update| update.kind == Kind::Metadata)
|
||||
{
|
||||
this.apply_author(update.author, cx);
|
||||
}
|
||||
let (sender, receiver) = flume::unbounded::<PublicKey>();
|
||||
|
||||
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
|
||||
if let BackendEvent::ProfileUpdates(authors) = event {
|
||||
this.apply_authors(authors.clone(), cx);
|
||||
}
|
||||
BackendEvent::Published(event) if event.kind == Kind::Metadata => {
|
||||
let metadata = Metadata::from_json(&event.content).unwrap_or_default();
|
||||
this.profiles
|
||||
.insert(event.pubkey, Profile::new(event.pubkey, metadata));
|
||||
cx.notify();
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
|
||||
// Fetch requests are queued on a channel, batched into one sync per debounce window.
|
||||
let client = backend.read(cx).client();
|
||||
let (sender, receiver) = flume::unbounded::<PublicKey>();
|
||||
let entity = cx.entity().downgrade();
|
||||
|
||||
cx.spawn(async move |_this, cx| {
|
||||
Self::handle_requests(entity, &client, &receiver, cx).await
|
||||
cx.spawn(async move |this, cx| {
|
||||
if let Err(e) = Self::handle_requests(this, &client, &receiver, cx).await {
|
||||
log::error!("Failed to handle requests: {e}");
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
let weak = cx.entity().downgrade();
|
||||
cx.defer(move |cx| {
|
||||
if let Err(error) = weak.update(cx, |this, cx| this.load(cx)) {
|
||||
log::warn!("profile store dropped before initial load could run: {error}");
|
||||
}
|
||||
entity.update(cx, |this, cx| this.load(cx)).ok();
|
||||
});
|
||||
|
||||
Self {
|
||||
@@ -160,11 +149,9 @@ impl ProfileStore {
|
||||
let client = backend.read(cx).client();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
let filter = Filter::new().kind(Kind::Metadata).limit(200);
|
||||
let filter = Filter::new().kind(Kind::Metadata).limit(WARM_LIMIT);
|
||||
let events = client.database().query(filter).await?;
|
||||
|
||||
// Parse off the main thread.
|
||||
// Only plain profiles cross back.
|
||||
let profiles: Vec<Profile> = events
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
@@ -176,7 +163,7 @@ impl ProfileStore {
|
||||
Ok::<_, Error>(profiles)
|
||||
});
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
cx.spawn(async move |this, cx| {
|
||||
let profiles = work.await?;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
@@ -186,53 +173,13 @@ impl ProfileStore {
|
||||
cx.notify();
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
Ok::<_, Error>(())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn apply_author(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
||||
let backend = Backend::global(cx);
|
||||
let client = backend.read(cx).client();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
let filter = Filter::new().kind(Kind::Metadata).author(public_key);
|
||||
let events = client.database().query(filter).await?;
|
||||
|
||||
// Parse off the main thread.
|
||||
// Only the profile crosses back.
|
||||
let profile = events
|
||||
.into_iter()
|
||||
.max_by_key(|e| e.created_at)
|
||||
.map(|event| {
|
||||
let metadata = Metadata::from_json(event.content).unwrap_or_default();
|
||||
Profile::new(event.pubkey, metadata)
|
||||
});
|
||||
|
||||
Ok::<_, Error>(profile)
|
||||
});
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
let profile = work.await?;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
if let Some(profile) = profile {
|
||||
this.profiles.insert(profile.public_key(), profile);
|
||||
cx.notify();
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
}
|
||||
|
||||
/// Re-read the latest metadata of every requested author from the local database.
|
||||
///
|
||||
/// Used after a sync, which produces no NostrUpdate events.
|
||||
fn apply_seen(&mut self, cx: &mut Context<Self>) {
|
||||
let authors: Vec<PublicKey> = self.seen.borrow().iter().copied().collect();
|
||||
|
||||
/// Re-read the latest metadata of `authors` from the local database in one query.
|
||||
fn apply_authors(&mut self, authors: Vec<PublicKey>, cx: &mut Context<Self>) {
|
||||
if authors.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -243,9 +190,9 @@ impl ProfileStore {
|
||||
let work = cx.background_spawn(async move {
|
||||
let filter = Filter::new().kind(Kind::Metadata).authors(authors);
|
||||
let events = client.database().query(filter).await?;
|
||||
|
||||
// Pick the latest metadata per author off the main thread.
|
||||
let mut latest: HashMap<PublicKey, (Timestamp, Metadata)> = HashMap::new();
|
||||
|
||||
for event in events {
|
||||
match latest.get(&event.pubkey) {
|
||||
Some((ts, _)) if *ts >= event.created_at => {}
|
||||
@@ -269,7 +216,7 @@ impl ProfileStore {
|
||||
Ok::<_, Error>(profiles)
|
||||
});
|
||||
|
||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
cx.spawn(async move |this, cx| {
|
||||
let profiles = work.await?;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
@@ -279,14 +226,18 @@ impl ProfileStore {
|
||||
cx.notify();
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
Ok::<_, Error>(())
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Sync metadata for requested authors in batches, debounced to collect requests.
|
||||
///
|
||||
/// After each batch, the seen profiles are re-read from the database on the main thread.
|
||||
/// Re-read the latest metadata of every requested author from the local database.
|
||||
fn apply_seen(&mut self, cx: &mut Context<Self>) {
|
||||
let authors: Vec<PublicKey> = self.seen.borrow().iter().copied().collect();
|
||||
self.apply_authors(authors, cx);
|
||||
}
|
||||
|
||||
/// Fetch metadata for requested authors in batches, debounced to collect requests.
|
||||
async fn handle_requests(
|
||||
this: WeakEntity<ProfileStore>,
|
||||
client: &Client,
|
||||
@@ -305,15 +256,20 @@ impl ProfileStore {
|
||||
|
||||
// The channel has no async timeout, race the receive against a timer.
|
||||
let deadline = Instant::now() + BATCH_TIMEOUT;
|
||||
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
|
||||
if now >= deadline {
|
||||
break;
|
||||
}
|
||||
|
||||
let timer = cx.background_executor().timer(deadline - now);
|
||||
futures::pin_mut!(timer);
|
||||
|
||||
let recv = receiver.recv_async();
|
||||
futures::pin_mut!(recv);
|
||||
|
||||
match futures::future::select(recv, timer).await {
|
||||
futures::future::Either::Left((Ok(public_key), _)) => {
|
||||
batch.insert(public_key);
|
||||
@@ -323,18 +279,21 @@ impl ProfileStore {
|
||||
}
|
||||
}
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::Metadata)
|
||||
.authors(batch.drain().collect::<Vec<PublicKey>>());
|
||||
let authors: Vec<PublicKey> = batch.drain().collect();
|
||||
|
||||
// Negentropy-sync with the bootstrap relays.
|
||||
// Synced events are written to the database directly, no NostrUpdate.
|
||||
// Re-apply from the database afterwards.
|
||||
match sync_bootstrap_only(client, filter, SyncOptions::default()).await {
|
||||
Ok(_) => {
|
||||
this.update(cx, |this, cx| this.apply_seen(cx)).ok();
|
||||
for chunk in authors.chunks(REQUEST_CHUNK) {
|
||||
let opts = SyncOptions::default();
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::Metadata)
|
||||
.authors(chunk.iter().copied());
|
||||
|
||||
if let Err(e) = sync_bootstrap_only(client, filter, opts).await {
|
||||
log::warn!("profile fetch failed: {e}");
|
||||
}
|
||||
Err(e) => log::warn!("profile sync failed: {e}"),
|
||||
}
|
||||
|
||||
if this.update(cx, |this, cx| this.apply_seen(cx)).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,6 @@ impl RefreshGate {
|
||||
self.running
|
||||
}
|
||||
|
||||
/// A new refresh request arrived.
|
||||
///
|
||||
/// Folded into a follow-up run while one is in flight, otherwise the
|
||||
/// caller starts the run itself.
|
||||
pub fn request(&mut self) -> RefreshRequest {
|
||||
if self.running {
|
||||
self.dirty = true;
|
||||
|
||||
+222
-183
@@ -4,14 +4,16 @@ use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Error, bail};
|
||||
use bitcoin_hashes::sha1::Hash as Sha1Hash;
|
||||
use gpui::{App, AppContext, AsyncApp, Context, SharedString, Subscription, Task, WeakEntity};
|
||||
use gpui::{App, AppContext, Context, SharedString, Subscription, Task};
|
||||
use nostr::event::IntoEventBuilder;
|
||||
use nostr_sdk::prelude::*;
|
||||
use settings::{EventFetchingStrategy, SettingsStore};
|
||||
use signed_core::{
|
||||
Announcement, Deletions, RepoAddr, RepoStatus, filters, parse_state, pull_request_patch,
|
||||
pull_request_patches,
|
||||
};
|
||||
use signed_git::Nip34Binding;
|
||||
use signed_nostr::UniversalSigner;
|
||||
|
||||
use crate::backend::{
|
||||
Backend, BackendEvent, grasp_base_url, grasp06_prs_url, pr_clone_urls, require_relay_accepted,
|
||||
@@ -19,7 +21,6 @@ use crate::backend::{
|
||||
};
|
||||
use crate::checkouts::CheckoutsStore;
|
||||
use crate::git_store::ensure_repo_mirror;
|
||||
use crate::refresh::{RefreshGate, RefreshRequest};
|
||||
use crate::repos::RepoListStore;
|
||||
|
||||
/// Maximum size of one patch event.
|
||||
@@ -30,7 +31,6 @@ const MAX_PATCH_EVENT_BYTES: usize = 60 * 1024;
|
||||
/// Per-repository store.
|
||||
///
|
||||
/// Holds the announcement, state, issues, patches, PRs, comments and resolved statuses.
|
||||
/// Always derived from the local database.
|
||||
pub struct RepoStore {
|
||||
/// NIP-34 address. `None` while the repository is local-only.
|
||||
addr: Option<RepoAddr>,
|
||||
@@ -84,7 +84,12 @@ pub struct RepoStore {
|
||||
///
|
||||
/// The per-root fetches cover NIP-22 comments and statuses without an `a` tag.
|
||||
root_fetches: HashSet<EventId>,
|
||||
refresh: RefreshGate,
|
||||
/// Maintainers already synced through gossip in Uncensored mode.
|
||||
///
|
||||
/// Avoids re-running the maintainer Auto sync on every refresh.
|
||||
synced_maintainers: HashSet<PublicKey>,
|
||||
/// In-flight tasks, cancelled when the store drops.
|
||||
tasks: Vec<Task<Result<(), Error>>>,
|
||||
/// Backend subscription of an announced repository. `None` while local-only.
|
||||
_subscription: Option<Subscription>,
|
||||
}
|
||||
@@ -132,7 +137,8 @@ impl RepoStore {
|
||||
cloning: false,
|
||||
repo_relays: HashSet::new(),
|
||||
root_fetches: HashSet::new(),
|
||||
refresh: RefreshGate::default(),
|
||||
synced_maintainers: HashSet::new(),
|
||||
tasks: Vec::new(),
|
||||
_subscription: Some(subscription),
|
||||
}
|
||||
}
|
||||
@@ -160,7 +166,8 @@ impl RepoStore {
|
||||
cloning: false,
|
||||
repo_relays: HashSet::new(),
|
||||
root_fetches: HashSet::new(),
|
||||
refresh: RefreshGate::default(),
|
||||
synced_maintainers: HashSet::new(),
|
||||
tasks: Vec::new(),
|
||||
_subscription: None,
|
||||
}
|
||||
}
|
||||
@@ -201,34 +208,22 @@ impl RepoStore {
|
||||
};
|
||||
|
||||
let relevant = match event {
|
||||
BackendEvent::NostrUpdate(updates) => updates.iter().any(|update| {
|
||||
// Deletions may target any event of this repository.
|
||||
BackendEvent::RepoUpdates(updates) => updates.iter().any(|update| {
|
||||
let deletion =
|
||||
update.kind == Kind::EventDeletion || update.kind == Kind::RequestToVanish;
|
||||
|
||||
let coordinate = update.coordinate.as_ref() == Some(addr);
|
||||
let author = update.author == addr.public_key;
|
||||
let kind = update.kind == Kind::GitRepoAnnouncement;
|
||||
// NIP-22 comments carry no `a` tag.
|
||||
// Coordinate matching fails for them.
|
||||
// Any comment may reference this repository's roots.
|
||||
|
||||
let authored = (update.kind == Kind::GitRepoAnnouncement
|
||||
|| update.kind == Kind::RepoState)
|
||||
&& author;
|
||||
|
||||
let comment = update.kind == Kind::Comment;
|
||||
// Status events may omit their `a` tag, NIP-34.
|
||||
// Any status event may reference a root of this repository.
|
||||
let status = RepoStatus::from_kind(update.kind).is_some();
|
||||
|
||||
deletion || coordinate || (author && kind) || comment || status
|
||||
deletion || coordinate || authored || comment || status
|
||||
}),
|
||||
BackendEvent::Published(event) => {
|
||||
let kind = event.kind == Kind::GitRepoAnnouncement;
|
||||
let author = event.pubkey == addr.public_key;
|
||||
let coordinate = event.tags.coordinates().into_iter().any(|c| c == *addr);
|
||||
// Locally published deletions may target any event of this repository.
|
||||
// Refresh so they take effect immediately, like relay deletions.
|
||||
let deletion =
|
||||
event.kind == Kind::EventDeletion || event.kind == Kind::RequestToVanish;
|
||||
|
||||
coordinate || (kind && author) || deletion
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
|
||||
@@ -256,8 +251,6 @@ impl RepoStore {
|
||||
/// Announcement, state, activity and deletions targeting it.
|
||||
fn repo_filters(addr: &RepoAddr) -> Vec<Filter> {
|
||||
let mut filters = vec![
|
||||
// Announcement and state share author and identifier.
|
||||
// They combine into one filter, one fewer negentropy reconciliation per relay.
|
||||
Filter::new()
|
||||
.kinds([Kind::GitRepoAnnouncement, Kind::RepoState])
|
||||
.author(addr.public_key)
|
||||
@@ -287,9 +280,71 @@ impl RepoStore {
|
||||
self.repo_relays.extend(new.iter().cloned());
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
let filters = Self::repo_filters(&addr);
|
||||
|
||||
backend.update(cx, |backend, cx| {
|
||||
backend.connect_repo_relays(new, Self::repo_filters(&addr), cx);
|
||||
backend.connect_repo_relays(new, filters, cx);
|
||||
});
|
||||
}
|
||||
|
||||
/// Filters the SDK resolves through NIP-65 gossip in Uncensored mode.
|
||||
fn maintainer_filters(addr: &RepoAddr, maintainers: &[PublicKey]) -> Vec<Filter> {
|
||||
let mut pubkeys = maintainers.to_vec();
|
||||
// NIP-34 events tag the announcement author,
|
||||
// which may not be a maintainer for subordinate forks.
|
||||
if !pubkeys.contains(&addr.public_key) {
|
||||
pubkeys.push(addr.public_key);
|
||||
}
|
||||
|
||||
vec![
|
||||
// Announcement and state events, including co-maintainer states.
|
||||
Filter::new()
|
||||
.kinds([Kind::GitRepoAnnouncement, Kind::RepoState])
|
||||
.authors(pubkeys.clone())
|
||||
.identifier(addr.identifier.clone()),
|
||||
// Activity tagging a maintainer, resolved to their read relays.
|
||||
Filter::new()
|
||||
.kinds(filters::ACTIVITY_KINDS)
|
||||
.coordinate(addr)
|
||||
.pubkeys(pubkeys.clone()),
|
||||
// Activity authored by a maintainer, resolved to their write relays.
|
||||
Filter::new()
|
||||
.kinds(filters::ACTIVITY_KINDS)
|
||||
.coordinate(addr)
|
||||
.authors(pubkeys.clone()),
|
||||
// Deletions authored by a maintainer.
|
||||
Filter::new()
|
||||
.kinds([Kind::EventDeletion, Kind::RequestToVanish])
|
||||
.authors(pubkeys),
|
||||
]
|
||||
}
|
||||
|
||||
/// In Uncensored mode, sync the maintainer-shaped filters through the SDK's NIP-65 gossip targeting
|
||||
fn sync_maintainer_relays(&mut self, maintainers: &[PublicKey], cx: &mut Context<Self>) {
|
||||
let strategy = SettingsStore::try_global(cx)
|
||||
.map(|store| store.read(cx).settings().event_fetching)
|
||||
.unwrap_or_default();
|
||||
if strategy != EventFetchingStrategy::Uncensored {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(addr) = self.addr.clone() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if !maintainers
|
||||
.iter()
|
||||
.any(|public_key| !self.synced_maintainers.contains(public_key))
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.synced_maintainers.extend(maintainers.iter().copied());
|
||||
|
||||
let filters = Self::maintainer_filters(&addr, maintainers);
|
||||
let backend = Backend::global(cx);
|
||||
|
||||
backend.update(cx, |backend, cx| {
|
||||
backend.sync_auto(filters, cx);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -306,18 +361,10 @@ impl RepoStore {
|
||||
}
|
||||
|
||||
/// Re-query the local database and update all fields.
|
||||
///
|
||||
/// Runs immediately. The backend pump already batches the relay events that
|
||||
/// trigger a refresh, so no per-store debounce is needed.
|
||||
pub fn refresh(&mut self, cx: &mut Context<Self>) {
|
||||
if self.addr.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.refresh.request() != RefreshRequest::Schedule {
|
||||
return;
|
||||
}
|
||||
|
||||
self.run_refresh(cx);
|
||||
}
|
||||
|
||||
@@ -326,8 +373,6 @@ impl RepoStore {
|
||||
return;
|
||||
};
|
||||
|
||||
self.refresh.begin();
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
let client = backend.read(cx).client();
|
||||
|
||||
@@ -345,11 +390,10 @@ impl RepoStore {
|
||||
|
||||
let deletions = Deletions::from_events(deletion_events);
|
||||
|
||||
// Parse and sort off the main thread.
|
||||
// Only plain data crosses back into the entity.
|
||||
let all_announcements = announcements
|
||||
.into_iter()
|
||||
.filter(|e| !deletions.is_deleted(e));
|
||||
|
||||
let announcement = latest(all_announcements)
|
||||
.as_ref()
|
||||
.and_then(Announcement::from_event);
|
||||
@@ -374,8 +418,6 @@ impl RepoStore {
|
||||
}
|
||||
}
|
||||
|
||||
// NIP-22 comments reference their root via an `E` or `e` tag.
|
||||
// Not the repository's `a` tag, so query them by the root events.
|
||||
let mut seen_comments: HashSet<EventId> = comments.iter().map(|e| e.id).collect();
|
||||
let db = client.database();
|
||||
|
||||
@@ -393,8 +435,6 @@ impl RepoStore {
|
||||
}
|
||||
}
|
||||
|
||||
// Status events may omit their `a` tag.
|
||||
// Query them by the root events they reference too.
|
||||
let mut seen_statuses: HashSet<EventId> = statuses.iter().map(|e| e.id).collect();
|
||||
let db = client.database();
|
||||
|
||||
@@ -417,9 +457,6 @@ impl RepoStore {
|
||||
sort_newest_first(&mut pull_requests);
|
||||
sort_oldest_first(&mut comments);
|
||||
|
||||
// Resolve every root's status once here.
|
||||
// Render paths do HashMap lookups instead of per-root status scans.
|
||||
// Those scans are quadratic, with an allocation per pair.
|
||||
let maintainers = announcement
|
||||
.as_ref()
|
||||
.map(Announcement::effective_maintainers)
|
||||
@@ -454,7 +491,7 @@ impl RepoStore {
|
||||
))
|
||||
});
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let task = cx.spawn(async move |this, cx| {
|
||||
let (
|
||||
announcement,
|
||||
state,
|
||||
@@ -469,33 +506,20 @@ impl RepoStore {
|
||||
Ok(data) => data,
|
||||
Err(e) => {
|
||||
return this.update(cx, |this, cx| {
|
||||
this.refresh.abort();
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let again = this.update(cx, |this, cx| {
|
||||
// Compare before moving the freshly queried data in, so a pass
|
||||
// that found nothing new does not notify observers. The store
|
||||
// is polled in bursts while a sync is in flight; notifying on
|
||||
// every identical pass would re-render the repository panel
|
||||
// several times for no visible change.
|
||||
//
|
||||
// The first pass is the exception: it must notify even when it
|
||||
// found nothing, so views can leave their loading state and show
|
||||
// the empty result.
|
||||
//
|
||||
// Keep the open-time hint until that first pass has confirmed what
|
||||
// the database holds; afterwards the database is the truth,
|
||||
// including a deletion.
|
||||
this.update(cx, |this, cx| {
|
||||
let keep_hint = announcement.is_none() && !this.loaded;
|
||||
|
||||
let first_pass = !this.loaded;
|
||||
|
||||
let head_changed = state
|
||||
.as_ref()
|
||||
.is_some_and(|(_, head)| this.head.as_deref() != head.as_deref());
|
||||
|
||||
let changed = first_pass
|
||||
|| (!keep_hint && this.announcement != announcement)
|
||||
|| head_changed
|
||||
@@ -510,14 +534,23 @@ impl RepoStore {
|
||||
}
|
||||
|
||||
// The announcement may list relays for this repository's activity.
|
||||
// Connect to any we have not fetched from yet.
|
||||
let relays = this
|
||||
.announcement
|
||||
.as_ref()
|
||||
.map(|a| a.relays.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
this.connect_announced_relays(&relays, cx);
|
||||
|
||||
// Uncensored mode also covers the maintainers' NIP-65 relays.
|
||||
let maintainers = this
|
||||
.announcement
|
||||
.as_ref()
|
||||
.map(Announcement::effective_maintainers)
|
||||
.unwrap_or_default();
|
||||
|
||||
this.sync_maintainer_relays(&maintainers, cx);
|
||||
|
||||
if let Some((_, head)) = state {
|
||||
this.head = head;
|
||||
}
|
||||
@@ -531,10 +564,6 @@ impl RepoStore {
|
||||
this.open_pr_count = open_pr_count;
|
||||
this.loaded = true;
|
||||
|
||||
// Comments and statuses without an `a` tag.
|
||||
// None are addressed to the repository.
|
||||
// Fetch them by the root events they reference.
|
||||
// Use the bootstrap relays and the relays this repository announced.
|
||||
let roots = this
|
||||
.issues
|
||||
.iter()
|
||||
@@ -551,13 +580,13 @@ impl RepoStore {
|
||||
|
||||
if !new_roots.is_empty() {
|
||||
this.root_fetches.extend(new_roots.iter().copied());
|
||||
// Batch the per-root filters.
|
||||
// One filter per root costs a negentropy reconciliation per relay.
|
||||
|
||||
let mut root_filters = filters::comments_for(new_roots.clone());
|
||||
root_filters.push(filters::statuses_for(new_roots.iter().copied()));
|
||||
|
||||
let announced: Vec<RelayUrl> = this.repo_relays.iter().cloned().collect();
|
||||
let backend = Backend::global(cx);
|
||||
|
||||
backend.update(cx, |backend, cx| {
|
||||
backend.subscribe_bootstrap(root_filters.clone(), cx);
|
||||
backend.connect_repo_relays(announced, root_filters, cx);
|
||||
@@ -567,19 +596,12 @@ impl RepoStore {
|
||||
if changed {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
this.refresh.finish()
|
||||
})?;
|
||||
|
||||
// Requests that arrived while the refresh was running.
|
||||
// They are coalesced into one follow-up refresh.
|
||||
if again {
|
||||
this.update(cx, |this, cx| this.refresh(cx))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.detach();
|
||||
});
|
||||
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
/// Resolve the status of a root event, an issue, patch or PR, per NIP-34.
|
||||
@@ -588,25 +610,16 @@ impl RepoStore {
|
||||
}
|
||||
|
||||
/// Number of open issues.
|
||||
///
|
||||
/// Issues whose resolved status is [`RepoStatus::Open`].
|
||||
/// Issues without status events default to open.
|
||||
pub fn issue_count(&self) -> usize {
|
||||
self.open_issue_count
|
||||
}
|
||||
|
||||
/// Number of open pull requests.
|
||||
///
|
||||
/// Only root PR events count, PR updates do not.
|
||||
/// They must resolve to [`RepoStatus::Open`].
|
||||
pub fn pull_request_count(&self) -> usize {
|
||||
self.open_pr_count
|
||||
}
|
||||
|
||||
/// Whether `user` is the author or owner of this repository.
|
||||
///
|
||||
/// The author is the public key of the repository address.
|
||||
/// Only the author may manage pull requests, close, reopen or merge.
|
||||
pub fn is_author(&self, user: &PublicKey) -> bool {
|
||||
self.addr
|
||||
.as_ref()
|
||||
@@ -721,9 +734,12 @@ impl RepoStore {
|
||||
};
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
let signer = backend.read(cx).signer();
|
||||
let (signer, client, user) = {
|
||||
let backend = backend.read(cx);
|
||||
(backend.signer(), backend.client(), backend.current_user())
|
||||
};
|
||||
|
||||
let Some(user) = backend.read(cx).current_user() else {
|
||||
let Some(user) = user else {
|
||||
self.last_error = Some("Sign in to open a pull request".into());
|
||||
cx.notify();
|
||||
return;
|
||||
@@ -758,12 +774,12 @@ impl RepoStore {
|
||||
.collect()
|
||||
};
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
// The PR references the root patch event.
|
||||
// Viewers can then find the patch without carrying it inline.
|
||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
// The PR references the root patch,
|
||||
// viewers can then find the patch without carrying it inline.
|
||||
let root_patch = match publish_patch_series(
|
||||
&this,
|
||||
cx,
|
||||
&client,
|
||||
&signer,
|
||||
&addr,
|
||||
owner,
|
||||
euc.as_deref(),
|
||||
@@ -788,11 +804,14 @@ impl RepoStore {
|
||||
// Resolve the servers from the author's latest kind-10317 grasp list.
|
||||
// The settings defaults stand in when no list is published or the query fails.
|
||||
let author_servers = {
|
||||
let query = this.update(cx, |_this, cx| {
|
||||
let client = Backend::global(cx).read(cx).client();
|
||||
user_grasp_list_servers(client, user)
|
||||
})?;
|
||||
match cx.background_spawn(query).await {
|
||||
let query_client = client.clone();
|
||||
let published = cx
|
||||
.background_spawn(
|
||||
async move { user_grasp_list_servers(&query_client, user).await },
|
||||
)
|
||||
.await;
|
||||
|
||||
match published {
|
||||
Ok(published) if !published.is_empty() => published,
|
||||
_ => defaults,
|
||||
}
|
||||
@@ -826,24 +845,17 @@ impl RepoStore {
|
||||
};
|
||||
|
||||
let builder = this.update(cx, |this, _cx| {
|
||||
// NIP-34 PRs carry at least one clone URL.
|
||||
// The tip commit is downloadable from it.
|
||||
// The author's `/prs/` URLs come first.
|
||||
// They are author-controlled and most likely alive.
|
||||
// The announced mirrors follow.
|
||||
// The list is fixed before signing.
|
||||
// The pushed ref name embeds the event id.
|
||||
// Every candidate URL is listed up front.
|
||||
// Dead URLs are inert, the linked patch stays the source of truth.
|
||||
let prs_urls: Vec<Url> = author_targets
|
||||
.iter()
|
||||
.filter_map(|(url, _)| Url::parse(url).ok())
|
||||
.collect();
|
||||
|
||||
let base_clone = this
|
||||
.announcement
|
||||
.as_ref()
|
||||
.map(|a| a.clone.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let clone = pr_clone_urls(prs_urls, base_clone);
|
||||
|
||||
let builder = GitPullRequest {
|
||||
@@ -868,8 +880,6 @@ impl RepoStore {
|
||||
})?;
|
||||
|
||||
// Sign before publishing.
|
||||
// The tip is pushed to the grasp servers under `refs/nostr/<event-id>`.
|
||||
// Nak's convention, readers fetch that ref for the commit behind the `c` tag.
|
||||
let event = cx
|
||||
.background_spawn({
|
||||
let signer = signer.clone();
|
||||
@@ -880,20 +890,22 @@ impl RepoStore {
|
||||
if let Some(path) = push_from.as_ref() {
|
||||
let tip = current_commit.to_string();
|
||||
let reference = format!("refs/nostr/{}", event.id.to_hex());
|
||||
|
||||
let (pushed, failures) = cx
|
||||
.background_spawn({
|
||||
let path = path.clone();
|
||||
let tip = tip.clone();
|
||||
let reference = reference.clone();
|
||||
// Author servers first, then the announced base grasp servers.
|
||||
// The extra targets are best-effort redundancy.
|
||||
let targets: Vec<(String, String)> = author_targets
|
||||
.into_iter()
|
||||
.chain(base_targets)
|
||||
.collect();
|
||||
|
||||
async move {
|
||||
let mut failures = Vec::new();
|
||||
let mut pushed = 0;
|
||||
|
||||
for (url, label) in &targets {
|
||||
match signed_git::push_commit_ref(
|
||||
&path, url, &tip, &reference,
|
||||
@@ -902,6 +914,7 @@ impl RepoStore {
|
||||
Err(e) => failures.push(format!("{label}: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
(pushed, failures)
|
||||
}
|
||||
})
|
||||
@@ -918,8 +931,6 @@ impl RepoStore {
|
||||
}
|
||||
}
|
||||
|
||||
let client = this.update(cx, |_this, cx| Backend::global(cx).read(cx).client())?;
|
||||
|
||||
let publish_result: Result<Event, Error> = async {
|
||||
let output = client.send_event(&event).broadcast().await?;
|
||||
require_relay_accepted(output, event)
|
||||
@@ -936,11 +947,6 @@ impl RepoStore {
|
||||
}
|
||||
};
|
||||
|
||||
this.update(cx, |_this, cx| {
|
||||
Backend::global(cx)
|
||||
.update(cx, |backend, cx| backend.announce_published(pr_event.clone(), cx))
|
||||
})?;
|
||||
|
||||
// A draft PR carries a kind-1633 status event, NIP-34.
|
||||
// Publish it right after the PR event so viewers never show it open.
|
||||
if draft {
|
||||
@@ -950,8 +956,8 @@ impl RepoStore {
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.detach();
|
||||
});
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
/// Generate the patch between `merge_base` and `compare_ref` in `repo_path`,
|
||||
@@ -1015,8 +1021,12 @@ impl RepoStore {
|
||||
self.last_warning = None;
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
let (user, client, signer) = {
|
||||
let backend = backend.read(cx);
|
||||
(backend.current_user(), backend.client(), backend.signer())
|
||||
};
|
||||
|
||||
let Some(user) = backend.read(cx).current_user() else {
|
||||
let Some(user) = user else {
|
||||
self.last_error = Some("Sign in to update the pull request".into());
|
||||
cx.notify();
|
||||
return;
|
||||
@@ -1070,19 +1080,21 @@ impl RepoStore {
|
||||
self.not_announced(cx);
|
||||
return;
|
||||
};
|
||||
|
||||
let owner = addr.public_key;
|
||||
let euc = self.announcement.as_ref().and_then(|a| a.euc.clone());
|
||||
let root = root.clone();
|
||||
|
||||
let clone: Vec<Url> = self
|
||||
.announcement
|
||||
.as_ref()
|
||||
.map(|a| a.clone.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||
if let Err(e) = publish_patch_series(
|
||||
&this,
|
||||
cx,
|
||||
&client,
|
||||
&signer,
|
||||
&addr,
|
||||
owner,
|
||||
euc.as_deref(),
|
||||
@@ -1098,7 +1110,7 @@ impl RepoStore {
|
||||
});
|
||||
}
|
||||
|
||||
let builder = this.update(cx, |_this, _cx| {
|
||||
let builder = {
|
||||
let builder = GitPullRequestUpdate {
|
||||
repository: addr.clone(),
|
||||
pull_request_event: root.id,
|
||||
@@ -1115,13 +1127,7 @@ impl RepoStore {
|
||||
Some(euc) => builder.tag(Tag::parse(["r", euc]).expect("valid r tag")),
|
||||
None => builder,
|
||||
}
|
||||
})?;
|
||||
|
||||
let (client, signer) = this.update(cx, |_this, cx| {
|
||||
let backend = Backend::global(cx);
|
||||
let backend = backend.read(cx);
|
||||
(backend.client(), backend.signer())
|
||||
})?;
|
||||
};
|
||||
|
||||
let publish_result: Result<Event, Error> = async {
|
||||
let event = builder.finalize_async(&signer).await?;
|
||||
@@ -1130,25 +1136,16 @@ impl RepoStore {
|
||||
}
|
||||
.await;
|
||||
|
||||
match publish_result {
|
||||
Ok(event) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
Backend::global(cx).update(cx, |backend, cx| {
|
||||
backend.announce_published(event.clone(), cx)
|
||||
})
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
return this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
if let Err(e) = publish_result {
|
||||
return this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.detach();
|
||||
});
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
/// Set the status of a root event.
|
||||
@@ -1274,7 +1271,7 @@ impl RepoStore {
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
/// The latest announcement of this repository,
|
||||
@@ -1581,24 +1578,16 @@ impl RepoStore {
|
||||
}
|
||||
.await;
|
||||
|
||||
match publish_result {
|
||||
Ok(event) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
Backend::global(cx)
|
||||
.update(cx, |backend, cx| backend.announce_published(event, cx))
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
})?;
|
||||
}
|
||||
if let Err(e) = publish_result {
|
||||
this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
self.tasks.push(task);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1668,8 +1657,8 @@ fn patch_current_commit(patch: &str) -> Option<&str> {
|
||||
/// Returns the root event, the one a PR references.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn publish_patch_series(
|
||||
this: &WeakEntity<RepoStore>,
|
||||
cx: &mut AsyncApp,
|
||||
client: &Client,
|
||||
signer: &UniversalSigner,
|
||||
addr: &RepoAddr,
|
||||
owner: PublicKey,
|
||||
euc: Option<&str>,
|
||||
@@ -1677,12 +1666,6 @@ async fn publish_patch_series(
|
||||
first_marker: &str,
|
||||
reply_to: Option<EventId>,
|
||||
) -> Result<Event, Error> {
|
||||
let (client, signer) = this.update(cx, |_this, cx| {
|
||||
let backend = Backend::global(cx);
|
||||
let backend = backend.read(cx);
|
||||
(backend.client(), backend.signer())
|
||||
})?;
|
||||
|
||||
let mut root: Option<Event> = None;
|
||||
let mut previous = reply_to;
|
||||
|
||||
@@ -1695,6 +1678,7 @@ async fn publish_patch_series(
|
||||
};
|
||||
|
||||
let mut tags = vec![Tag::coordinate(addr.clone(), None), Tag::public_key(owner)];
|
||||
|
||||
if ix == 0 {
|
||||
if let Ok(tag) = Tag::parse(["t", first_marker]) {
|
||||
tags.push(tag);
|
||||
@@ -1709,28 +1693,25 @@ async fn publish_patch_series(
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Some(euc) = euc
|
||||
&& let Ok(tag) = Tag::parse(["r", euc])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Ok(tag) = Tag::parse(["commit", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
if let Ok(tag) = Tag::parse(["r", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
let builder = EventBuilder::new(Kind::GitPatch, part.clone()).tags(tags);
|
||||
|
||||
let event = builder.finalize_async(&signer).await?;
|
||||
let event = builder.finalize_async(signer).await?;
|
||||
let output = client.send_event(&event).broadcast().await?;
|
||||
let event = require_relay_accepted(output, event)?;
|
||||
this.update(cx, |_this, cx| {
|
||||
Backend::global(cx).update(cx, |backend, cx| {
|
||||
backend.announce_published(event.clone(), cx)
|
||||
})
|
||||
})?;
|
||||
|
||||
if root.is_none() {
|
||||
root = Some(event.clone());
|
||||
@@ -1769,9 +1750,11 @@ fn comment_builder(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
use super::{comment_builder, patch_current_commit};
|
||||
use super::{RepoStore, comment_builder, patch_current_commit};
|
||||
|
||||
#[test]
|
||||
fn parses_format_patch_header() {
|
||||
@@ -1817,4 +1800,60 @@ mod tests {
|
||||
// Signed's own `references_root` must keep matching the comment.
|
||||
assert!(signed_core::references_root(&event, &root.id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maintainer_filters_name_owner_and_maintainers() {
|
||||
let owner = Keys::generate().public_key();
|
||||
let maintainer = Keys::generate().public_key();
|
||||
let addr = Coordinate::new(Kind::GitRepoAnnouncement, owner).identifier("my-repo");
|
||||
|
||||
// The owner is not among the maintainers, as on a subordinate fork.
|
||||
let filters = RepoStore::maintainer_filters(&addr, &[maintainer]);
|
||||
assert_eq!(filters.len(), 4);
|
||||
|
||||
let expected = HashSet::from([owner, maintainer]);
|
||||
|
||||
// Gossip only resolves pubkeys from `authors` and the lowercase `#p` tag.
|
||||
let named = |filter: &Filter| -> HashSet<PublicKey> {
|
||||
let authors = filter.authors.iter().flatten().copied();
|
||||
let p_tag = filter
|
||||
.generic_tags
|
||||
.get(&SingleLetterTag::LOWERCASE_P)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|value| PublicKey::from_hex(value).ok());
|
||||
authors.chain(p_tag).collect()
|
||||
};
|
||||
|
||||
// Announcement and state events, scoped to the repository identifier.
|
||||
let announcement = &filters[0];
|
||||
assert_eq!(named(announcement), expected);
|
||||
assert!(
|
||||
announcement
|
||||
.generic_tags
|
||||
.contains_key(&SingleLetterTag::LOWERCASE_D)
|
||||
);
|
||||
|
||||
// Activity filters, scoped to the repository coordinate.
|
||||
for filter in &filters[1..3] {
|
||||
assert_eq!(named(filter), expected);
|
||||
assert!(
|
||||
filter
|
||||
.generic_tags
|
||||
.contains_key(&SingleLetterTag::LOWERCASE_A)
|
||||
);
|
||||
}
|
||||
|
||||
// Deletions, named by author only.
|
||||
let deletions = &filters[3];
|
||||
assert_eq!(
|
||||
deletions
|
||||
.authors
|
||||
.clone()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.collect::<HashSet<_>>(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -47,6 +47,8 @@ pub struct RepoListStore {
|
||||
///
|
||||
/// Used for the Popular ranking of the explore list.
|
||||
pub counts: Arc<HashMap<RepoAddr, RepoActivityCounts>>,
|
||||
/// Own repositories whose state events were fetched from their announced relays.
|
||||
state_synced_repos: HashSet<RepoAddr>,
|
||||
refresh: RefreshGate,
|
||||
_subscription: Subscription,
|
||||
}
|
||||
@@ -66,33 +68,11 @@ impl RepoListStore {
|
||||
|
||||
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
|
||||
let relevant = match event {
|
||||
BackendEvent::NostrUpdate(updates) => updates.iter().any(|update| {
|
||||
// Deletions may target anything we list, always refresh.
|
||||
if update.kind == Kind::EventDeletion || update.kind == Kind::RequestToVanish {
|
||||
true
|
||||
} else if filters::ACTIVITY_KINDS.contains(&update.kind) {
|
||||
// Activity events are addressed to repos via `a` tags.
|
||||
// Their author is not the repo owner, always refresh.
|
||||
true
|
||||
} else {
|
||||
let is_announcement = update.kind == Kind::GitRepoAnnouncement;
|
||||
let is_repo_state = update.kind == Kind::RepoState;
|
||||
is_announcement || is_repo_state
|
||||
}
|
||||
}),
|
||||
BackendEvent::Published(event) => {
|
||||
let announcement = event.kind == Kind::GitRepoAnnouncement;
|
||||
|
||||
// Locally published deletions are already in the local database.
|
||||
// Refresh so they take effect immediately, like relay deletions.
|
||||
let deletion =
|
||||
event.kind == Kind::EventDeletion || event.kind == Kind::RequestToVanish;
|
||||
|
||||
announcement || deletion
|
||||
BackendEvent::SignerChanged => {
|
||||
this.state_synced_repos.clear();
|
||||
true
|
||||
}
|
||||
// Only a completed sync refreshes the list.
|
||||
// Progress ticks would re-scan the whole database several times
|
||||
// per sync to reveal entries incrementally.
|
||||
BackendEvent::RepoUpdates(_) => true,
|
||||
BackendEvent::Synced => true,
|
||||
_ => false,
|
||||
};
|
||||
@@ -114,6 +94,7 @@ impl RepoListStore {
|
||||
announcements: Arc::new(Vec::new()),
|
||||
last_activity: Arc::new(HashMap::new()),
|
||||
counts: Arc::new(HashMap::new()),
|
||||
state_synced_repos: HashSet::new(),
|
||||
refresh: RefreshGate::default(),
|
||||
_subscription: subscription,
|
||||
}
|
||||
@@ -132,12 +113,42 @@ impl RepoListStore {
|
||||
let backend = Backend::global(cx);
|
||||
|
||||
backend.update(cx, |backend, cx| {
|
||||
backend.sync_bootstrap(filters::all_announcements(), cx);
|
||||
// Deletion requests, NIP-09/62, must be known before any announcement is shown.
|
||||
backend.sync_bootstrap(filters::deletions(), cx);
|
||||
backend.sync_bootstraps(
|
||||
vec![
|
||||
filters::all_announcements(),
|
||||
filters::all_states(),
|
||||
// Deletion requests, NIP-09/62, must be known before any announcement is shown.
|
||||
filters::deletions(),
|
||||
],
|
||||
cx,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Fetch the state events of the user's own repositories.
|
||||
fn sync_own_repo_states(&mut self, cx: &mut Context<Self>) {
|
||||
let backend = Backend::global(cx);
|
||||
let Some(me) = backend.read(cx).current_user() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let pending: Vec<(RepoAddr, Vec<RelayUrl>)> = self
|
||||
.announcements
|
||||
.iter()
|
||||
.filter(|announcement| announcement.owner == me && !announcement.relays.is_empty())
|
||||
.map(|announcement| (announcement.addr(), announcement.relays.clone()))
|
||||
.filter(|(addr, _)| !self.state_synced_repos.contains(addr))
|
||||
.collect();
|
||||
|
||||
for (addr, relays) in pending {
|
||||
self.state_synced_repos.insert(addr.clone());
|
||||
|
||||
backend.update(cx, |backend, cx| {
|
||||
backend.connect_repo_relays(relays, vec![filters::state(&addr)], cx);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-query the local database.
|
||||
///
|
||||
/// Runs immediately. The backend pump already batches the relay events that
|
||||
@@ -189,9 +200,6 @@ impl RepoListStore {
|
||||
let mut announcements: Vec<Announcement> = by_repo.into_values().collect();
|
||||
announcements.sort_by_key(|a| std::cmp::Reverse(a.created_at));
|
||||
|
||||
// Last activity per repository.
|
||||
// State updates count, and all NIP-34 activity events.
|
||||
// The activity events are patches, PRs, issues and statuses.
|
||||
let mut last_activity: HashMap<RepoAddr, Timestamp> = announcements
|
||||
.iter()
|
||||
.map(|a| (a.addr(), a.created_at))
|
||||
@@ -217,6 +225,7 @@ impl RepoListStore {
|
||||
let activity_filter = Filter::new()
|
||||
.kinds(filters::ACTIVITY_KINDS)
|
||||
.since(Timestamp::now() - ACTIVITY_WINDOW);
|
||||
|
||||
for event in client.database().query(activity_filter).await? {
|
||||
if deletions.is_deleted(&event) {
|
||||
continue;
|
||||
@@ -225,8 +234,6 @@ impl RepoListStore {
|
||||
if addr.kind != Kind::GitRepoAnnouncement {
|
||||
continue;
|
||||
}
|
||||
// Skip events for repos we do not list.
|
||||
// The map cannot grow beyond the number of announcements.
|
||||
let Some(entry) = last_activity.get_mut(&addr) else {
|
||||
continue;
|
||||
};
|
||||
@@ -239,13 +246,12 @@ impl RepoListStore {
|
||||
let mut counts: HashMap<RepoAddr, RepoActivityCounts> = HashMap::new();
|
||||
let count_filter =
|
||||
Filter::new().kinds([Kind::GitIssue, Kind::GitPullRequest, Kind::GitPatch]);
|
||||
|
||||
for event in client.database().query(count_filter).await? {
|
||||
if deletions.is_deleted(&event) {
|
||||
continue;
|
||||
}
|
||||
for addr in event.tags.coordinates() {
|
||||
// Skip events for repos we do not list.
|
||||
// The map cannot grow beyond the number of announcements.
|
||||
if addr.kind != Kind::GitRepoAnnouncement || !last_activity.contains_key(&addr)
|
||||
{
|
||||
continue;
|
||||
@@ -278,6 +284,7 @@ impl RepoListStore {
|
||||
this.announcements = Arc::new(announcements);
|
||||
this.last_activity = Arc::new(last_activity);
|
||||
this.counts = Arc::new(counts);
|
||||
this.sync_own_repo_states(cx);
|
||||
cx.notify();
|
||||
|
||||
this.refresh.finish()
|
||||
|
||||
@@ -303,6 +303,7 @@ pub struct CommitDiffView {
|
||||
loading: bool,
|
||||
error: Option<SharedString>,
|
||||
pane: Entity<DiffPane>,
|
||||
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
|
||||
}
|
||||
|
||||
impl CommitDiffView {
|
||||
@@ -336,6 +337,7 @@ impl CommitDiffView {
|
||||
loading: true,
|
||||
error: None,
|
||||
pane,
|
||||
tasks: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -383,7 +385,7 @@ impl CommitDiffView {
|
||||
Ok(())
|
||||
});
|
||||
|
||||
task.detach();
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
|
||||
|
||||
@@ -11,7 +11,7 @@ use gpui::{
|
||||
use gpui_component::button::{Button, ButtonVariants};
|
||||
use gpui_component::{ActiveTheme, Icon, IconName, IconNamed, Sizable, StyledExt, h_flex, v_flex};
|
||||
use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp};
|
||||
use signed_core::{COVER_NOTE_KIND, InboxItem, InboxReadState, RepoAddr, filters};
|
||||
use signed_core::{InboxItem, InboxReadState, RepoAddr};
|
||||
use signed_state::{
|
||||
Backend, BackendEvent, ProfileStore, RefreshGate, RefreshRequest, RepoListStore, query_inbox,
|
||||
};
|
||||
@@ -157,21 +157,8 @@ impl InboxView {
|
||||
|
||||
fn handle_backend_event(&mut self, event: &BackendEvent, cx: &mut Context<Self>) {
|
||||
match event {
|
||||
BackendEvent::NostrUpdate(updates) => {
|
||||
let relevant = updates.iter().any(|update| {
|
||||
let is_notification = filters::NOTIFICATION_KINDS.contains(&update.kind);
|
||||
let is_comment = update.kind == Kind::Comment;
|
||||
let is_event_deletion = update.kind == Kind::EventDeletion;
|
||||
let is_request_to_vanish = update.kind == Kind::RequestToVanish;
|
||||
|
||||
is_notification || is_comment || is_event_deletion || is_request_to_vanish
|
||||
});
|
||||
|
||||
if relevant {
|
||||
self.refresh(cx);
|
||||
}
|
||||
}
|
||||
BackendEvent::Synced | BackendEvent::Published(_) => self.refresh(cx),
|
||||
BackendEvent::RepoUpdates(_) => self.refresh(cx),
|
||||
BackendEvent::Synced => self.refresh(cx),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -200,12 +187,16 @@ impl InboxView {
|
||||
self.refresh.begin();
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
let Some(me) = backend.read(cx).current_user() else {
|
||||
let (me, client) = {
|
||||
let backend = backend.read(cx);
|
||||
(backend.current_user(), backend.client())
|
||||
};
|
||||
|
||||
let Some(me) = me else {
|
||||
self.refresh.abort();
|
||||
return;
|
||||
};
|
||||
|
||||
let client = backend.read(cx).client();
|
||||
let state = self.state.clone();
|
||||
|
||||
let work = cx.background_spawn(async move { query_inbox(&client, me, &state).await });
|
||||
@@ -570,10 +561,6 @@ fn sub_activity(event: &Event, me: Option<PublicKey>, cx: &App) -> AnyElement {
|
||||
}
|
||||
|
||||
fn activity_phrase(kind: Kind) -> &'static str {
|
||||
if kind == COVER_NOTE_KIND {
|
||||
return "added a note";
|
||||
}
|
||||
|
||||
match kind {
|
||||
Kind::GitIssue => "opened an issue",
|
||||
Kind::GitPullRequest => "opened a PR",
|
||||
|
||||
@@ -79,8 +79,7 @@ pub struct PullRequestDetailView {
|
||||
pane: Entity<DiffPane>,
|
||||
commit_item_sizes: Rc<Vec<Size<Pixels>>>,
|
||||
commit_scroll_handle: VirtualListScrollHandle,
|
||||
/// The dock caches item panels, so without this observer a panel opened
|
||||
/// before the store loaded would stay on its placeholder.
|
||||
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
|
||||
_subscription: Subscription,
|
||||
}
|
||||
|
||||
@@ -124,6 +123,7 @@ impl PullRequestDetailView {
|
||||
pane,
|
||||
commit_item_sizes: Rc::new(Vec::new()),
|
||||
commit_scroll_handle: VirtualListScrollHandle::new(),
|
||||
tasks: Vec::new(),
|
||||
_subscription: subscription,
|
||||
}
|
||||
}
|
||||
@@ -327,7 +327,7 @@ impl PullRequestDetailView {
|
||||
Ok(())
|
||||
});
|
||||
|
||||
task.detach();
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
/// Open the diff of `commit_id` in the bottom dock of the area.
|
||||
|
||||
@@ -68,6 +68,7 @@ pub struct NewPullRequestView {
|
||||
pane: Entity<DiffPane>,
|
||||
scroll_handle: VirtualListScrollHandle,
|
||||
item_sizes: Rc<Vec<Size<Pixels>>>,
|
||||
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
@@ -323,6 +324,7 @@ impl NewPullRequestView {
|
||||
pane,
|
||||
scroll_handle: VirtualListScrollHandle::new(),
|
||||
item_sizes: Rc::new(Vec::new()),
|
||||
tasks: Vec::new(),
|
||||
_subscriptions: subscriptions,
|
||||
}
|
||||
}
|
||||
@@ -390,7 +392,8 @@ impl NewPullRequestView {
|
||||
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
/// Branches and the current branch are read off the UI thread, then applied.
|
||||
@@ -419,7 +422,8 @@ impl NewPullRequestView {
|
||||
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
fn apply_checkout(
|
||||
@@ -636,7 +640,8 @@ impl NewPullRequestView {
|
||||
|
||||
Ok(())
|
||||
});
|
||||
task.detach();
|
||||
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -830,7 +835,7 @@ impl NewPullRequestView {
|
||||
Ok(())
|
||||
});
|
||||
|
||||
task.detach();
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
@@ -911,7 +916,7 @@ impl NewPullRequestView {
|
||||
Ok(())
|
||||
});
|
||||
|
||||
task.detach();
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
fn open_commit_diff(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context<Self>) {
|
||||
|
||||
@@ -215,15 +215,19 @@ pub fn load_user_grasp_servers(
|
||||
cx: &mut App,
|
||||
) {
|
||||
let backend = Backend::global(cx);
|
||||
let Some(user) = backend.read(cx).current_user() else {
|
||||
let (user, client) = {
|
||||
let backend = backend.read(cx);
|
||||
(backend.current_user(), backend.client())
|
||||
};
|
||||
|
||||
let Some(user) = user else {
|
||||
state.update(cx, |state, _| state.loading_servers = false);
|
||||
return;
|
||||
};
|
||||
let client = backend.read(cx).client();
|
||||
let handle = window.window_handle();
|
||||
|
||||
cx.spawn(async move |cx| {
|
||||
let result = signed_state::user_grasp_list_servers(client, user).await;
|
||||
let result = signed_state::user_grasp_list_servers(&client, user).await;
|
||||
|
||||
let _ = cx.update_window(handle, |_, _window, cx| {
|
||||
state.update(cx, |state, _| {
|
||||
|
||||
@@ -79,16 +79,12 @@ impl SidebarPanel {
|
||||
let signer_changed = matches!(event, BackendEvent::SignerChanged);
|
||||
let signer_required = matches!(event, BackendEvent::SignerRequired);
|
||||
|
||||
if !signer_changed && !signer_required {
|
||||
return;
|
||||
}
|
||||
|
||||
if signer_required {
|
||||
this.banner = pick_banner();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
if this.refresh(cx) || signer_required {
|
||||
if this.refresh(cx) || signer_changed {
|
||||
cx.notify();
|
||||
}
|
||||
}));
|
||||
@@ -131,16 +127,14 @@ impl SidebarPanel {
|
||||
let user = backend.read(cx).current_user();
|
||||
|
||||
let (announcements, local_repos, scanning) = {
|
||||
let repo_list = RepoListStore::global(cx);
|
||||
let repo_list = repo_list.read(cx);
|
||||
let repo_list = RepoListStore::global(cx).read(cx);
|
||||
|
||||
let announcements = user
|
||||
.as_ref()
|
||||
.map(|user| repo_list.announcements_of(user))
|
||||
.unwrap_or_default();
|
||||
|
||||
let local = LocalReposStore::global(cx);
|
||||
let local = local.read(cx);
|
||||
let local = LocalReposStore::global(cx).read(cx);
|
||||
let local_repos =
|
||||
resolve_local_repos(&local.repos, &repo_list.announcements, &announcements);
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ use gpui_component::{
|
||||
ActiveTheme, IconName, IndexPath, Sizable, Theme, ThemeMode, ThemeRegistry, WindowExt, h_flex,
|
||||
v_flex,
|
||||
};
|
||||
use settings::{AppearanceMode, Settings, SettingsStore};
|
||||
use settings::{AppearanceMode, EventFetchingStrategy, Settings, SettingsStore};
|
||||
use signed_ui::{SelectOption, setting_block, setting_row};
|
||||
|
||||
use super::{normalize_server, server_host};
|
||||
@@ -52,6 +52,7 @@ fn theme_options(cx: &App) -> (Vec<SelectOption>, Vec<SelectOption>) {
|
||||
/// Created once when the dialog opens, so control state survives re-renders.
|
||||
struct SettingsControls {
|
||||
appearance: Entity<SelectState<Vec<SelectOption>>>,
|
||||
event_fetching: Entity<SelectState<Vec<SelectOption>>>,
|
||||
light_theme: Entity<SelectState<Vec<SelectOption>>>,
|
||||
dark_theme: Entity<SelectState<Vec<SelectOption>>>,
|
||||
font_size: Entity<InputState>,
|
||||
@@ -89,6 +90,23 @@ impl SettingsControls {
|
||||
)
|
||||
});
|
||||
|
||||
let event_fetching_options = vec![
|
||||
SelectOption::new("curated", "Curated"),
|
||||
SelectOption::new("uncensored", "Uncensored"),
|
||||
];
|
||||
let event_fetching_value = match settings.event_fetching {
|
||||
EventFetchingStrategy::Curated => "curated",
|
||||
EventFetchingStrategy::Uncensored => "uncensored",
|
||||
};
|
||||
let event_fetching = cx.new(|cx| {
|
||||
SelectState::new(
|
||||
event_fetching_options.clone(),
|
||||
selected_index(&event_fetching_options, event_fetching_value),
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let (light_options, dark_options) = theme_options(cx);
|
||||
let light_theme = cx.new(|cx| {
|
||||
SelectState::new(
|
||||
@@ -147,6 +165,19 @@ impl SettingsControls {
|
||||
}
|
||||
}));
|
||||
|
||||
subscriptions.push(cx.subscribe(&event_fetching, |_, event, cx| {
|
||||
if let SelectEvent::Confirm(Some(value)) = event {
|
||||
let strategy = match value.as_ref() {
|
||||
"curated" => EventFetchingStrategy::Curated,
|
||||
_ => EventFetchingStrategy::Uncensored,
|
||||
};
|
||||
let store = SettingsStore::global(cx);
|
||||
store.update(cx, |store, cx| {
|
||||
store.edit(|settings| settings.event_fetching = strategy, cx);
|
||||
});
|
||||
}
|
||||
}));
|
||||
|
||||
subscriptions.push(cx.subscribe(&light_theme, |_, event, cx| {
|
||||
if let SelectEvent::Confirm(Some(value)) = event {
|
||||
let store = SettingsStore::global(cx);
|
||||
@@ -252,6 +283,7 @@ impl SettingsControls {
|
||||
|
||||
Self {
|
||||
appearance,
|
||||
event_fetching,
|
||||
light_theme,
|
||||
dark_theme,
|
||||
font_size,
|
||||
@@ -294,6 +326,8 @@ fn settings_view(controls: &SettingsControls, cx: &mut App) -> impl IntoElement
|
||||
.child(Separator::horizontal())
|
||||
.child(grasp_servers_section(&settings, controls, cx))
|
||||
.child(Separator::horizontal())
|
||||
.child(event_fetching_section(controls, cx))
|
||||
.child(Separator::horizontal())
|
||||
.child(repositories_section(&settings, controls, cx))
|
||||
}
|
||||
|
||||
@@ -306,6 +340,16 @@ fn appearance_section(controls: &SettingsControls, cx: &App) -> impl IntoElement
|
||||
))
|
||||
}
|
||||
|
||||
/// Which relays repository activity is fetched from.
|
||||
fn event_fetching_section(controls: &SettingsControls, cx: &App) -> impl IntoElement {
|
||||
v_flex().w_full().gap_3().child(setting_row(
|
||||
cx,
|
||||
"Event Fetching Strategy",
|
||||
"Curated fetches events from relays in the repository's announcement. Uncensored also fetches from every maintainer's relays.",
|
||||
Select::new(&controls.event_fetching).w_full(),
|
||||
))
|
||||
}
|
||||
|
||||
fn theme_section(settings: &Settings, controls: &SettingsControls, cx: &App) -> impl IntoElement {
|
||||
v_flex()
|
||||
.gap_3()
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ product-name = "Signed"
|
||||
description = "Nostr Git client for browsing repositories and collaborating"
|
||||
identifier = "info.reya.signed"
|
||||
category = "DeveloperTool"
|
||||
version = "0.1.0-alpha"
|
||||
version = "0.2.0-alpha"
|
||||
out-dir = "../dist"
|
||||
before-packaging-command = "cargo build --release"
|
||||
resources = ["Cargo.toml", "src"]
|
||||
|
||||
Reference in New Issue
Block a user