Redesign for the v1 stable release #3

Merged
reya merged 30 commits from v1-redesign into master 2026-02-04 01:43:24 +00:00
10 changed files with 143 additions and 55 deletions
Showing only changes of commit a39725b1d3 - Show all commits

View File

@@ -16,7 +16,7 @@ use gpui::{
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use smallvec::{smallvec, SmallVec}; use smallvec::{smallvec, SmallVec};
use state::{tracker, NostrRegistry, GIFTWRAP_SUBSCRIPTION}; use state::{tracker, NostrRegistry, RelayState, GIFTWRAP_SUBSCRIPTION};
mod message; mod message;
mod room; mod room;
@@ -63,14 +63,17 @@ pub struct ChatRegistry {
/// Loading status of the registry /// Loading status of the registry
loading: bool, loading: bool,
/// Tracking the status of unwrapping gift wrap events.
tracking_flag: Arc<AtomicBool>,
/// Channel's sender for communication between nostr and gpui /// Channel's sender for communication between nostr and gpui
sender: Sender<NostrEvent>, sender: Sender<NostrEvent>,
/// Tracking the status of unwrapping gift wrap events.
tracking_flag: Arc<AtomicBool>,
/// Handle tracking asynchronous task
tracking: Option<Task<Result<(), Error>>>,
/// Handle notifications asynchronous task /// Handle notifications asynchronous task
notifications: Option<Task<Result<(), Error>>>, notifications: Option<Task<()>>,
/// Tasks for asynchronous operations /// Tasks for asynchronous operations
tasks: Vec<Task<()>>, tasks: Vec<Task<()>>,
@@ -112,7 +115,7 @@ impl ChatRegistry {
subscriptions.push( subscriptions.push(
// Observe the identity // Observe the identity
cx.observe(&identity, |this, state, cx| { cx.observe(&identity, |this, state, cx| {
if state.read(cx).has_public_key() { if state.read(cx).messaging_relays_state() == RelayState::Set {
// Handle nostr notifications // Handle nostr notifications
this.handle_notifications(cx); this.handle_notifications(cx);
// Track unwrapping progress // Track unwrapping progress
@@ -162,8 +165,9 @@ impl ChatRegistry {
Self { Self {
rooms: vec![], rooms: vec![],
loading: true, loading: true,
tracking_flag,
sender: tx.clone(), sender: tx.clone(),
tracking_flag,
tracking: None,
notifications: None, notifications: None,
tasks, tasks,
_subscriptions: subscriptions, _subscriptions: subscriptions,
@@ -181,7 +185,7 @@ impl ChatRegistry {
let status = self.tracking_flag.clone(); let status = self.tracking_flag.clone();
let tx = self.sender.clone(); let tx = self.sender.clone();
self.tasks.push(cx.background_spawn(async move { self.notifications = Some(cx.background_spawn(async move {
let initialized_at = Timestamp::now(); let initialized_at = Timestamp::now();
let subscription_id = SubscriptionId::new(GIFTWRAP_SUBSCRIPTION); let subscription_id = SubscriptionId::new(GIFTWRAP_SUBSCRIPTION);
@@ -229,7 +233,7 @@ impl ChatRegistry {
} }
}, },
Err(e) => { Err(e) => {
log::warn!("Failed to unwrap: {e}"); log::warn!("Failed to unwrap the gift wrap event: {e}");
} }
} }
} }
@@ -252,7 +256,7 @@ impl ChatRegistry {
let status = self.tracking_flag.clone(); let status = self.tracking_flag.clone();
let tx = self.sender.clone(); let tx = self.sender.clone();
self.notifications = Some(cx.background_spawn(async move { self.tracking = Some(cx.background_spawn(async move {
let loop_duration = Duration::from_secs(12); let loop_duration = Duration::from_secs(12);
let mut total_loops = 0; let mut total_loops = 0;
@@ -607,29 +611,44 @@ impl ChatRegistry {
device_signer: &Option<Arc<dyn NostrSigner>>, device_signer: &Option<Arc<dyn NostrSigner>>,
gift_wrap: &Event, gift_wrap: &Event,
) -> Result<UnwrappedGift, Error> { ) -> Result<UnwrappedGift, Error> {
if let Some(signer) = device_signer.as_ref() { // Try with the device signer first
let seal = signer if let Some(signer) = device_signer {
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content) if let Ok(unwrapped) = Self::try_unwrap_with(gift_wrap, signer).await {
.await?; return Ok(unwrapped);
};
};
let seal: Event = Event::from_json(seal)?; // Try with the user's signer
seal.verify_with_ctx(&SECP256K1)?; let user_signer = client.signer().await?;
let unwrapped = UnwrappedGift::from_gift_wrap(&user_signer, gift_wrap).await?;
let rumor = signer.nip44_decrypt(&seal.pubkey, &seal.content).await?;
let rumor = UnsignedEvent::from_json(rumor)?;
return Ok(UnwrappedGift {
sender: seal.pubkey,
rumor,
});
}
let signer = client.signer().await?;
let unwrapped = UnwrappedGift::from_gift_wrap(&signer, gift_wrap).await?;
Ok(unwrapped) Ok(unwrapped)
} }
/// Attempts to unwrap a gift wrap event with a given signer.
async fn try_unwrap_with(
gift_wrap: &Event,
signer: &Arc<dyn NostrSigner>,
) -> Result<UnwrappedGift, Error> {
// Get the sealed event
let seal = signer
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content)
.await?;
// Verify the sealed event
let seal: Event = Event::from_json(seal)?;
seal.verify_with_ctx(&SECP256K1)?;
// Get the rumor event
let rumor = signer.nip44_decrypt(&seal.pubkey, &seal.content).await?;
let rumor = UnsignedEvent::from_json(rumor)?;
Ok(UnwrappedGift {
sender: seal.pubkey,
rumor,
})
}
/// Stores an unwrapped event in local database with reference to original /// Stores an unwrapped event in local database with reference to original
async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Result<(), Error> { async fn set_rumor(client: &Client, id: EventId, rumor: &UnsignedEvent) -> Result<(), Error> {
let rumor_id = rumor.id.context("Rumor is missing an event id")?; let rumor_id = rumor.id.context("Rumor is missing an event id")?;

View File

@@ -2,6 +2,7 @@ use std::sync::Arc;
use common::TextUtils; use common::TextUtils;
use dock::panel::{Panel, PanelEvent}; use dock::panel::{Panel, PanelEvent};
use dock::ClosePanel;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
div, img, px, relative, AnyElement, App, AppContext, Context, Entity, EventEmitter, div, img, px, relative, AnyElement, App, AppContext, Context, Entity, EventEmitter,
@@ -51,6 +52,8 @@ impl ConnectPanel {
Ok(uri) => { Ok(uri) => {
this.persist_bunker(uri, cx); this.persist_bunker(uri, cx);
this.set_signer(signer, true, cx); this.set_signer(signer, true, cx);
// Close the current panel after setting the signer
window.dispatch_action(Box::new(ClosePanel), cx);
} }
Err(e) => { Err(e) => {
window.push_notification(Notification::error(e.to_string()), cx); window.push_notification(Notification::error(e.to_string()), cx);
@@ -94,7 +97,7 @@ impl Render for ConnectPanel {
.size_full() .size_full()
.items_center() .items_center()
.justify_center() .justify_center()
.gap_3() .gap_10()
.child( .child(
v_flex() v_flex()
.justify_center() .justify_center()

View File

@@ -77,11 +77,13 @@ impl Render for GreeterPanel {
.justify_center() .justify_center()
.child( .child(
v_flex() v_flex()
.gap_4() .gap_10()
.h_full()
.items_center() .items_center()
.justify_center() .justify_center()
.child( .child(
h_flex() h_flex()
.w_96()
.gap_2() .gap_2()
.child( .child(
svg() svg()
@@ -109,9 +111,11 @@ impl Render for GreeterPanel {
.child( .child(
v_flex() v_flex()
.gap_2() .gap_2()
.w_96()
.child( .child(
h_flex() h_flex()
.gap_1() .gap_1()
.w_full()
.text_sm() .text_sm()
.font_semibold() .font_semibold()
.text_color(cx.theme().text_muted) .text_color(cx.theme().text_muted)
@@ -120,6 +124,7 @@ impl Render for GreeterPanel {
) )
.child( .child(
v_flex() v_flex()
.w_full()
.items_start() .items_start()
.justify_start() .justify_start()
.gap_2() .gap_2()

View File

@@ -2,6 +2,7 @@ use std::time::Duration;
use anyhow::anyhow; use anyhow::anyhow;
use dock::panel::{Panel, PanelEvent}; use dock::panel::{Panel, PanelEvent};
use dock::ClosePanel;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
div, relative, AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, div, relative, AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle,
@@ -91,17 +92,19 @@ impl ImportPanel {
} }
if value.starts_with("ncryptsec1") { if value.starts_with("ncryptsec1") {
self.login_with_password(&value, &password, cx); self.login_with_password(&value, &password, window, cx);
return; return;
} }
if let Ok(secret) = SecretKey::parse(&value) { if let Ok(secret) = SecretKey::parse(&value) {
let keys = Keys::new(secret); let keys = Keys::new(secret);
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
// Update the signer
nostr.update(cx, |this, cx| { nostr.update(cx, |this, cx| {
this.set_signer(keys, true, cx); this.set_signer(keys, true, cx);
}); });
// Close the current panel after setting the signer
window.dispatch_action(Box::new(ClosePanel), cx);
} else { } else {
self.set_error("Invalid", cx); self.set_error("Invalid", cx);
} }
@@ -152,6 +155,8 @@ impl ImportPanel {
Ok(uri) => { Ok(uri) => {
this.persist_bunker(uri, cx); this.persist_bunker(uri, cx);
this.set_signer(signer, true, cx); this.set_signer(signer, true, cx);
// Close the current panel after setting the signer
window.dispatch_action(Box::new(ClosePanel), cx);
} }
Err(e) => { Err(e) => {
window.push_notification(Notification::error(e.to_string()), cx); window.push_notification(Notification::error(e.to_string()), cx);
@@ -163,7 +168,13 @@ impl ImportPanel {
.detach(); .detach();
} }
pub fn login_with_password(&mut self, content: &str, pwd: &str, cx: &mut Context<Self>) { pub fn login_with_password(
&mut self,
content: &str,
pwd: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
if pwd.is_empty() { if pwd.is_empty() {
self.set_error("Password is required", cx); self.set_error("Password is required", cx);
return; return;
@@ -185,16 +196,19 @@ impl ImportPanel {
} }
}); });
cx.spawn(async move |this, cx| { cx.spawn_in(window, async move |this, cx| {
let result = task.await; let result = task.await;
this.update(cx, |this, cx| { this.update_in(cx, |this, window, cx| {
match result { match result {
Ok(keys) => { Ok(keys) => {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
// Update the signer
nostr.update(cx, |this, cx| { nostr.update(cx, |this, cx| {
this.set_signer(keys, true, cx); this.set_signer(keys, true, cx);
}); });
// Close the current panel after setting the signer
window.dispatch_action(Box::new(ClosePanel), cx);
} }
Err(e) => { Err(e) => {
this.set_error(e.to_string(), cx); this.set_error(e.to_string(), cx);
@@ -270,11 +284,15 @@ impl Focusable for ImportPanel {
impl Render for ImportPanel { impl Render for ImportPanel {
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
const SECRET_WARN: &str = "* Coop doesn't store your secret key. \
It will be cleared when you close the app. \
To persist your identity, please connect via Nostr Connect.";
v_flex() v_flex()
.size_full() .size_full()
.items_center() .items_center()
.justify_center() .justify_center()
.gap_3() .gap_10()
.child( .child(
div() div()
.text_center() .text_center()
@@ -284,8 +302,8 @@ impl Render for ImportPanel {
) )
.child( .child(
v_flex() v_flex()
.w_112()
.gap_2() .gap_2()
.w_96()
.text_sm() .text_sm()
.child( .child(
v_flex() v_flex()
@@ -338,7 +356,15 @@ impl Render for ImportPanel {
.text_color(cx.theme().danger_foreground) .text_color(cx.theme().danger_foreground)
.child(error.clone()), .child(error.clone()),
) )
}), })
.child(
div()
.mt_2()
.italic()
.text_xs()
.text_color(cx.theme().text_muted)
.child(SharedString::from(SECRET_WARN)),
),
) )
} }
} }

View File

@@ -72,13 +72,18 @@ impl DeviceRegistry {
subscriptions.push( subscriptions.push(
// Observe the identity entity // Observe the identity entity
cx.observe(&identity, |this, state, cx| { cx.observe(&identity, |this, state, cx| {
if state.read(cx).has_public_key() { match state.read(cx).relay_list_state() {
if state.read(cx).relay_list_state() == RelayState::Set { RelayState::Initial => {
this.reset(cx);
}
RelayState::Set => {
this.get_announcement(cx); this.get_announcement(cx);
if state.read(cx).messaging_relays_state() == RelayState::Set {
this.get_messages(cx);
}
} }
if state.read(cx).messaging_relays_state() == RelayState::Set { _ => {}
this.get_messages(cx);
}
} }
}), }),
); );
@@ -193,7 +198,9 @@ impl DeviceRegistry {
let filter = Filter::new() let filter = Filter::new()
.kind(Kind::ApplicationSpecificData) .kind(Kind::ApplicationSpecificData)
.identifier(IDENTIFIER); .identifier(IDENTIFIER)
.author(public_key)
.limit(1);
if let Some(event) = client.database().query(filter).await?.first() { if let Some(event) = client.database().query(filter).await?.first() {
let content = signer.nip44_decrypt(&public_key, &event.content).await?; let content = signer.nip44_decrypt(&public_key, &event.content).await?;
@@ -206,6 +213,22 @@ impl DeviceRegistry {
} }
} }
/// Reset the device state
pub fn reset(&mut self, cx: &mut Context<Self>) {
self.requests.update(cx, |this, cx| {
this.clear();
cx.notify();
});
self.device_signer.update(cx, |this, cx| {
*this = None;
cx.notify();
});
self.state = DeviceState::Initial;
cx.notify();
}
/// Returns the device signer entity /// Returns the device signer entity
pub fn signer(&self, cx: &App) -> Option<Arc<dyn NostrSigner>> { pub fn signer(&self, cx: &App) -> Option<Arc<dyn NostrSigner>> {
self.device_signer.read(cx).clone() self.device_signer.read(cx).clone()
@@ -256,8 +279,8 @@ impl DeviceRegistry {
// Construct a filter to get dekey messages if available // Construct a filter to get dekey messages if available
if let Some(signer) = device_signer.as_ref() { if let Some(signer) = device_signer.as_ref() {
if let Ok(pubkey) = signer.get_public_key().await { if let Ok(pkey) = signer.get_public_key().await {
filters.push(Filter::new().kind(Kind::GiftWrap).pubkey(pubkey)); filters.push(Filter::new().kind(Kind::GiftWrap).pubkey(pkey));
} }
} }

View File

@@ -657,31 +657,35 @@ impl DockArea {
cx.subscribe_in( cx.subscribe_in(
view, view,
window, window,
move |_, panel, event, window, cx| match event { move |_this, panel, event, window, cx| match event {
PanelEvent::ZoomIn => { PanelEvent::ZoomIn => {
let panel = panel.clone(); let panel = panel.clone();
cx.spawn_in(window, async move |view, window| { cx.spawn_in(window, async move |view, window| {
_ = view.update_in(window, |view, window, cx| { view.update_in(window, |view, window, cx| {
view.set_zoomed_in(panel, window, cx); view.set_zoomed_in(panel, window, cx);
cx.notify(); cx.notify();
}); })
.ok();
}) })
.detach(); .detach();
} }
PanelEvent::ZoomOut => cx PanelEvent::ZoomOut => {
.spawn_in(window, async move |view, window| { cx.spawn_in(window, async move |view, window| {
_ = view.update_in(window, |view, window, cx| { _ = view.update_in(window, |view, window, cx| {
view.set_zoomed_out(window, cx); view.set_zoomed_out(window, cx);
}); });
}) })
.detach(), .detach();
}
PanelEvent::LayoutChanged => { PanelEvent::LayoutChanged => {
cx.spawn_in(window, async move |view, window| { cx.spawn_in(window, async move |view, window| {
_ = view.update_in(window, |view, window, cx| { view.update_in(window, |view, window, cx| {
view.update_toggle_button_tab_panels(window, cx) view.update_toggle_button_tab_panels(window, cx)
}); })
.ok();
}) })
.detach(); .detach();
// Emit layout changed event for dock
cx.emit(DockEvent::LayoutChanged); cx.emit(DockEvent::LayoutChanged);
} }
}, },

View File

@@ -5,6 +5,7 @@ use gpui::{
use ui::button::Button; use ui::button::Button;
use ui::popup_menu::PopupMenu; use ui::popup_menu::PopupMenu;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PanelEvent { pub enum PanelEvent {
ZoomIn, ZoomIn,
ZoomOut, ZoomOut,

View File

@@ -1113,7 +1113,7 @@ impl TabPanel {
fn on_action_close_panel( fn on_action_close_panel(
&mut self, &mut self,
_: &ClosePanel, _ev: &ClosePanel,
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {

View File

@@ -46,6 +46,12 @@ impl Identity {
} }
} }
/// Resets the relay states to their default values.
pub fn reset_relay_state(&mut self) {
self.relay_list = RelayState::default();
self.messaging_relays = RelayState::default();
}
/// Sets the state of the NIP-65 relays. /// Sets the state of the NIP-65 relays.
pub fn set_relay_list_state(&mut self, state: RelayState) { pub fn set_relay_list_state(&mut self, state: RelayState) {
self.relay_list = state; self.relay_list = state;

View File

@@ -429,6 +429,7 @@ impl NostrRegistry {
Ok(public_key) => { Ok(public_key) => {
identity.update(cx, |this, cx| { identity.update(cx, |this, cx| {
this.set_public_key(public_key); this.set_public_key(public_key);
this.reset_relay_state();
this.set_owned(owned); this.set_owned(owned);
cx.notify(); cx.notify();
})?; })?;