From 7721ddd6a856a977f12d44a2491954fbaac98e76 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Sun, 29 Nov 2026 18:48:34 +0700 Subject: [PATCH] feat: add repo commands to the `si` cli --- CHANGELOG.md | 2 +- Cargo.lock | 3 + crates/cli/Cargo.toml | 3 + crates/cli/src/main.rs | 591 ++++++++++++++++++------- crates/signed_app/src/app/mod.rs | 2 + crates/signed_app/src/identity/exit.rs | 2 +- crates/signed_state/src/backend.rs | 90 +++- crates/signed_state/src/lib.rs | 8 +- desktop/src/main.rs | 15 +- 9 files changed, 527 insertions(+), 189 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eeadfcd..82208b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Added -- Add a `si` command line interface with `whoami`, `signup`, `login` and `logout` that uses the same identity, data and keychain as the app without the app running +- Add a `si` command line interface that opens the desktop app and clones, publishes, syncs and deletes repositories with the app's identity, data and keychain, without the app running - Add a confirmation dialog before deleting a repository - Browse the files of a commit as of that commit from the Commits list, the short id on a row shows the commit's files in place of the worktree and the branch selector shows the commit until a branch or tag is picked again diff --git a/Cargo.lock b/Cargo.lock index 5fc6ec8..a3e8033 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7244,6 +7244,9 @@ dependencies = [ "gpui_platform", "nostr", "rpassword", + "settings", + "signed_core", + "signed_git", "signed_state", "tracing", "tracing-subscriber", diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 3679dcf..7f6fa4d 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -9,7 +9,10 @@ name = "si" path = "src/main.rs" [dependencies] +signed_core = { path = "../signed_core" } +signed_git = { path = "../signed_git" } signed_state = { path = "../signed_state" } +settings = { path = "../settings" } gpui.workspace = true gpui_platform.workspace = true diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 8ba30e5..4963834 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -1,11 +1,19 @@ use std::io::Write as _; use std::path::{Path, PathBuf}; +use std::process::Stdio; use anyhow::{Context as _, bail}; -use clap::{Parser, Subcommand}; +use clap::{Args, Parser, Subcommand}; use gpui::{App, AsyncApp, Entity, Subscription}; -use nostr::prelude::{PublicKey, ToBech32 as _}; -use signed_state::{Backend, BackendEvent}; +use nostr::nips::nip19::Nip19Coordinate; +use nostr::prelude::{PublicKey, RelayUrl, ToBech32 as _}; +use settings::{DEFAULT_GRASP_SERVERS, SettingsStore}; +use signed_core::{Announcement, RepoAddr}; +use signed_git::{GitCache, Repo}; +use signed_state::{Backend, BackendEvent, CheckoutsStore}; + +/// The desktop app's bundle identifier, the packager `identifier` in `desktop/Cargo.toml`. +const DESKTOP_BUNDLE_ID: &str = "info.reya.signed"; /// Command line interface for Signed. #[derive(Parser)] @@ -17,31 +25,71 @@ struct Cli { #[derive(Subcommand)] enum Command { - /// Create a new identity and store it on this device. - Signup { - /// Name published in the profile. - name: String, - /// Read the passphrase from this file instead of prompting. - #[arg(long, value_name = "PATH")] - passphrase_file: Option, - }, - /// Store an existing identity on this device. - Login { - /// Read the credential (nsec, ncryptsec or bunker URI) from this file instead of prompting. - #[arg(long, value_name = "PATH")] - credential_file: Option, - /// Read the passphrase from this file instead of prompting. - #[arg(long, value_name = "PATH")] - passphrase_file: Option, - }, - /// Print the identity stored on this device. - Whoami { - /// Read the passphrase from this file instead of prompting. - #[arg(long, value_name = "PATH")] - passphrase_file: Option, - }, - /// Remove the identity stored on this device. - Logout, + /// Launch the desktop app. + Desktop, + /// Clone a published repository into the current directory or a custom path. + Clone(CloneArgs), + /// Publish a local repository to Nostr. + Publish(PublishArgs), + /// Push the current branch of a published local repository to its grasp servers. + Sync(SyncArgs), + /// Delete a published repository from Nostr. + Delete(DeleteArgs), +} + +#[derive(Args)] +struct CloneArgs { + /// Repository address: `naddr1...`, `nostr:naddr1...` or `30617::`. + repo: String, + /// Destination directory, the repository's name in the current directory when omitted. + path: Option, +} + +#[derive(Args)] +struct PublishArgs { + /// Repository folder, the current directory when omitted. + path: Option, + /// Name of the repository, the folder's name when omitted. + #[arg(long)] + name: Option, + /// Description of the repository. + #[arg(long)] + description: Option, + /// Default branch, the checked out one when omitted. + #[arg(long)] + branch: Option, + /// Grasp server to publish to; the account's grasp list is used when omitted. + #[arg(long = "grasp-server", value_name = "URL")] + grasp_servers: Vec, + #[command(flatten)] + signing: Signing, +} + +#[derive(Args)] +struct SyncArgs { + /// Repository folder, the current directory when omitted. + path: Option, + #[command(flatten)] + signing: Signing, +} + +#[derive(Args)] +struct DeleteArgs { + /// Repository address, or the folder of a published local repository. + repo: String, + /// Delete without asking for confirmation. + #[arg(short, long)] + yes: bool, + #[command(flatten)] + signing: Signing, +} + +/// Options of the commands that sign events with the stored identity. +#[derive(Args)] +struct Signing { + /// Read the passphrase from this file instead of prompting. + #[arg(long, value_name = "PATH")] + passphrase_file: Option, } fn main() { @@ -76,26 +124,62 @@ fn main() { async fn run(command: Command, cx: &mut AsyncApp) -> anyhow::Result<()> { match command { - Command::Signup { - name, - passphrase_file, - } => signup(&name, passphrase_file.as_deref(), cx).await, - Command::Login { - credential_file, - passphrase_file, - } => login(credential_file.as_deref(), passphrase_file.as_deref(), cx).await, - Command::Whoami { passphrase_file } => whoami(passphrase_file.as_deref(), cx).await, - Command::Logout => logout(cx).await, + Command::Desktop => open_desktop(), + Command::Clone(args) => clone(args, cx).await, + Command::Publish(args) => publish(args, cx).await, + Command::Sync(args) => sync(args, cx).await, + Command::Delete(args) => delete(args, cx).await, } } +/// Launches the desktop app: the `signed` binary built next to this one, else the installed app. +fn open_desktop() -> anyhow::Result<()> { + let exe = std::env::current_exe().context("failed to locate this executable")?; + let extension = std::env::consts::EXE_EXTENSION; + + let sibling = if extension.is_empty() { + exe.with_file_name("signed") + } else { + exe.with_file_name(format!("signed.{extension}")) + }; + + if sibling.is_file() { + std::process::Command::new(&sibling) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .context("failed to launch the desktop app")?; + return Ok(()); + } + + if cfg!(target_os = "macos") { + // Launch Services finds the app by its bundle identifier wherever it is installed. + let status = std::process::Command::new("open") + .args(["-b", DESKTOP_BUNDLE_ID]) + .status() + .context("failed to launch the desktop app")?; + + if !status.success() { + bail!("the desktop app is not installed"); + } + + return Ok(()); + } + + bail!( + "the desktop app was not found next to {}; run `cargo run -p signed` instead", + exe.display() + ) +} + /// Opens the stores shared with the desktop app and starts forwarding the backend events. fn open( cx: &mut AsyncApp, ) -> anyhow::Result<(Entity, flume::Receiver, Subscription)> { cx.update(signed_state::init)?; - let backend = cx.update(|cx| Backend::global(cx)); + let backend = cx.update(|cx| Backend::global(cx)); let (sender, receiver) = flume::unbounded(); // The returned subscription keeps the forwarding alive; dropping it ends it. let subscription = cx.subscribe(&backend, move |_, event: &BackendEvent, _| { @@ -156,116 +240,351 @@ async fn restore( } } -/// Fails when the device already holds a credential, since a second one would shadow it on restore. -async fn require_signed_out( +/// Unlocks the identity the desktop app stored on this device. +async fn sign_in( backend: &Entity, receiver: &flume::Receiver, - cx: &AsyncApp, -) -> anyhow::Result<()> { + passphrase_file: Option<&Path>, + cx: &mut AsyncApp, +) -> anyhow::Result { match restore(backend, receiver, cx).await? { - Identity::SignedOut => Ok(()), - Identity::SignedIn(public_key) => { - bail!("this device already holds an identity ({public_key}); run `si logout` first") - } - Identity::PassphraseRequired => { - bail!("this device already holds an encrypted identity; run `si logout` first") - } - } -} - -async fn whoami(passphrase_file: Option<&Path>, cx: &mut AsyncApp) -> anyhow::Result<()> { - let (backend, receiver, _subscription) = open(cx)?; - - let public_key = match restore(&backend, &receiver, cx).await? { - Identity::SignedIn(public_key) => public_key, + Identity::SignedIn(public_key) => Ok(public_key), Identity::PassphraseRequired => { let passphrase = read_passphrase(passphrase_file)?; backend .update(cx, |backend, cx| { backend.restore_with_passphrase(&passphrase, cx) }) - .await? + .await } Identity::SignedOut => { - bail!("no identity on this device; run `si signup` or `si login` first") + bail!("no identity on this device; sign in with the desktop app first") + } + } +} + +/// Reads a repository's announcement and announced default branch, or `None` when no relay announces it. +async fn load_announcement( + backend: &Entity, + addr: &RepoAddr, + cx: &AsyncApp, +) -> anyhow::Result)>> { + let client = cx.update(|cx| backend.read(cx).client()); + let addr = addr.clone(); + + cx.background_executor() + .spawn(async move { Backend::load_announcement(&client, &addr).await }) + .await +} + +async fn clone(args: CloneArgs, cx: &mut AsyncApp) -> anyhow::Result<()> { + let repo = args.repo.trim(); + let addr = repo + .parse::() + .with_context(|| format!("`{repo}` is not a repository address"))?; + + let (backend, _receiver, _subscription) = open(cx)?; + + let (announcement, _head) = load_announcement(&backend, &addr, cx) + .await? + .with_context(|| format!("no announcement of {addr} was found"))?; + + let destination = match args.path { + Some(path) => path, + None => std::env::current_dir()?.join(folder_name(&announcement)), + }; + + let urls = announcement.clone.clone(); + let clone = { + let destination = destination.clone(); + cx.background_executor() + .spawn(async move { Repo::clone(&urls, &destination).map(|_| ()) }) + }; + clone.await?; + + let checkouts = cx.update(|cx| CheckoutsStore::global(cx)); + checkouts.update(cx, |checkouts, cx| { + checkouts.record(destination.clone(), addr.clone(), cx); + }); + + println!( + "cloned {} into {}", + announcement.name.as_deref().unwrap_or(&announcement.id), + destination.display() + ); + + Ok(()) +} + +/// The folder a repository is cloned into: its name or identifier, sanitized for the file system. +fn folder_name(announcement: &Announcement) -> String { + let name = announcement + .name + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + .unwrap_or(&announcement.id); + + let name = GitCache::sanitize_path_component(name); + + if name.is_empty() { + "repository".to_owned() + } else { + name + } +} + +async fn publish(args: PublishArgs, cx: &mut AsyncApp) -> anyhow::Result<()> { + let servers = args + .grasp_servers + .iter() + .map(|url| { + RelayUrl::parse(url.as_str()).with_context(|| format!("`{url}` is not a relay URL")) + }) + .collect::>>()?; + + let path = args.path.unwrap_or_else(|| PathBuf::from(".")); + let path = path + .canonicalize() + .with_context(|| format!("cannot find the repository folder {}", path.display()))?; + + let name = match args.name { + Some(name) => name, + None => path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .context("the repository folder has no name")?, + }; + + let (backend, receiver, _subscription) = open(cx)?; + let user = sign_in( + &backend, + &receiver, + args.signing.passphrase_file.as_deref(), + cx, + ) + .await?; + + let branch = match args.branch { + Some(branch) => Some(branch), + None => { + let path = path.clone(); + cx.background_executor() + .spawn(async move { + let repo = Repo::open(&path)?; + Ok::<_, anyhow::Error>(repo.current_branch()) + }) + .await? } }; - print_identity(public_key) -} + let servers = if servers.is_empty() { + account_grasp_servers(&backend, user, cx).await? + } else { + servers + }; -async fn signup( - name: &str, - passphrase_file: Option<&Path>, - cx: &mut AsyncApp, -) -> anyhow::Result<()> { - let (backend, receiver, _subscription) = open(cx)?; - - require_signed_out(&backend, &receiver, cx).await?; - - let passphrase = new_passphrase(passphrase_file)?; - let public_key = backend + let description = args.description.unwrap_or_default(); + let announcement = backend .update(cx, |backend, cx| { - backend.create_identity(name, &passphrase, cx) + backend.publish_local_repo(path, &name, &description, servers, branch, cx) }) .await?; - print_identity(public_key)?; - // The identity is stored already; wait so exiting does not drop the events still being sent. - loop { - match next_event(&receiver).await? { - BackendEvent::IdentityPublished(Ok(())) => return Ok(()), - BackendEvent::IdentityPublished(Err(message)) => bail!("{message}"), - _ => {} - } - } + let addr = announcement.addr(); + let naddr = + Nip19Coordinate::new(addr.clone().into(), announcement.relays.clone()).to_bech32()?; + + println!( + "published {}", + announcement.name.as_deref().unwrap_or(&announcement.id) + ); + println!("address: {addr}"); + println!("naddr: {naddr}"); + + Ok(()) } -async fn login( - credential_file: Option<&Path>, - passphrase_file: Option<&Path>, +/// The grasp servers the account published, or the configured defaults while it has none. +async fn account_grasp_servers( + backend: &Entity, + user: PublicKey, cx: &mut AsyncApp, -) -> anyhow::Result<()> { - let (backend, receiver, _subscription) = open(cx)?; +) -> anyhow::Result> { + let client = cx.update(|cx| backend.read(cx).client()); + let published = cx + .background_executor() + .spawn(async move { signed_state::user_grasp_list_servers(&client, user).await }) + .await; - require_signed_out(&backend, &receiver, cx).await?; - - let credential = read_credential(credential_file)?; - let credential = credential.trim(); - - let public_key = if credential.starts_with("nsec1") { - let passphrase = new_passphrase(passphrase_file)?; - backend - .update(cx, |backend, cx| { - backend.import_nsec(credential, &passphrase, cx) - }) - .await? - } else if credential.starts_with("ncryptsec1") { - let passphrase = read_passphrase(passphrase_file)?; - backend - .update(cx, |backend, cx| { - backend.import_ncryptsec(credential, &passphrase, cx) - }) - .await? - } else if credential.starts_with("bunker://") { - backend - .update(cx, |backend, cx| backend.import_bunker(credential, cx)) - .await? - } else { - bail!("the credential must be an nsec, ncryptsec or bunker:// URI"); + let mut urls = match published { + Ok(servers) if !servers.is_empty() => return Ok(servers), + Ok(_) => Vec::new(), + Err(error) => { + tracing::warn!("failed to load the account's grasp list: {error:#}"); + Vec::new() + } }; - print_identity(public_key) -} + if urls.is_empty() { + let defaults = cx.update(|cx| { + SettingsStore::global(cx) + .read(cx) + .settings() + .grasp_servers + .default_servers + .clone() + }); -async fn logout(cx: &mut AsyncApp) -> anyhow::Result<()> { - let (backend, receiver, _subscription) = open(cx)?; - - if let Identity::SignedOut = restore(&backend, &receiver, cx).await? { - bail!("no identity on this device"); + urls = if defaults.is_empty() { + DEFAULT_GRASP_SERVERS + .iter() + .map(|url| (*url).to_owned()) + .collect() + } else { + defaults + }; } - backend.update(cx, |backend, cx| backend.sign_out(cx)).await + Ok(urls + .iter() + .filter_map(|url| RelayUrl::parse(url).ok()) + .collect()) +} + +async fn sync(args: SyncArgs, cx: &mut AsyncApp) -> anyhow::Result<()> { + let (backend, receiver, _subscription) = open(cx)?; + + let path = args.path.unwrap_or_else(|| PathBuf::from(".")); + let path = path + .canonicalize() + .with_context(|| format!("cannot find the repository folder {}", path.display()))?; + let addr = local_addr(&path, cx).await?; + + let (announcement, head) = load_announcement(&backend, &addr, cx) + .await? + .with_context(|| format!("no announcement of {addr} was found"))?; + + let user = sign_in( + &backend, + &receiver, + args.signing.passphrase_file.as_deref(), + cx, + ) + .await?; + + if addr.public_key() != user { + bail!("only the repository's owner can sync it"); + } + + let (branch, commit) = { + let path = path.clone(); + cx.background_executor() + .spawn(async move { + let repo = Repo::open(&path)?; + let branch = repo + .current_branch() + .context("the checkout has a detached HEAD")?; + let commit = repo.head().context("the checkout has no commits")?; + Ok::<_, anyhow::Error>((branch, commit)) + }) + .await? + }; + + let outcome = backend + .update(cx, |backend, cx| { + backend.push_checkout_commit(announcement, path, head, commit.clone(), cx) + }) + .await?; + + println!( + "synced {branch} up to {}", + commit.get(..8).unwrap_or(&commit) + ); + + if let Some(warning) = outcome.partial_warning() { + eprintln!("warning: {warning}"); + } + + Ok(()) +} + +/// The address a local repository was published under, from its NIP-34 markers. +async fn local_addr(path: &Path, cx: &AsyncApp) -> anyhow::Result { + let binding = { + let path = path.to_path_buf(); + cx.background_executor() + .spawn(async move { + let repo = Repo::open(&path)?; + Ok::<_, anyhow::Error>(repo.nip34_binding()) + }) + .await? + }; + + binding + .and_then(|binding| Some(RepoAddr::new(binding.owner?, binding.identifier?))) + .with_context(|| { + format!( + "{} is not published to Nostr yet; run `si publish` first", + path.display() + ) + }) +} + +async fn delete(args: DeleteArgs, cx: &mut AsyncApp) -> anyhow::Result<()> { + let (backend, receiver, _subscription) = open(cx)?; + + let repo = args.repo.trim(); + let addr = match repo.parse::() { + Ok(addr) => addr, + Err(_) => { + let path = Path::new(repo); + + if !path.is_dir() { + bail!("`{repo}` is neither a repository address nor a local repository folder"); + } + + local_addr(path, cx).await? + } + }; + + sign_in( + &backend, + &receiver, + args.signing.passphrase_file.as_deref(), + cx, + ) + .await?; + + let question = format!( + "Delete {addr}? This removes its announcement, state and activity from Nostr and cannot be \ + undone" + ); + + if !args.yes && !confirm(&question)? { + bail!("aborted; pass --yes to delete without a prompt"); + } + + backend + .update(cx, |backend, cx| { + backend.delete_repository(addr.clone(), cx) + }) + .await?; + + println!("deleted {addr}"); + + Ok(()) +} + +/// Asks a yes/no question on the terminal, answering no when stdin is closed. +fn confirm(question: &str) -> anyhow::Result { + eprint!("{question} [y/N]: "); + std::io::stderr().flush()?; + + let mut answer = String::new(); + std::io::stdin().read_line(&mut answer)?; + + Ok(matches!(answer.trim(), "y" | "Y" | "yes")) } /// Reads one line from a file, without its line ending. @@ -281,33 +600,3 @@ fn read_passphrase(path: Option<&Path>) -> anyhow::Result { None => Ok(rpassword::prompt_password("Passphrase: ")?), } } - -/// Reads the passphrase for a new key, confirming it when it is typed. -fn new_passphrase(path: Option<&Path>) -> anyhow::Result { - let Some(path) = path else { - let passphrase = rpassword::prompt_password("Choose a passphrase: ")?; - if passphrase != rpassword::prompt_password("Confirm passphrase: ")? { - bail!("passphrases do not match"); - } - - return Ok(passphrase); - }; - - read_line(path) -} - -/// Reads the credential from `path`, or from the terminal without echoing it. -fn read_credential(path: Option<&Path>) -> anyhow::Result { - match path { - Some(path) => read_line(path), - None => Ok(rpassword::prompt_password( - "Credential (nsec, ncryptsec or bunker URI): ", - )?), - } -} - -fn print_identity(public_key: PublicKey) -> anyhow::Result<()> { - println!("npub: {}", public_key.to_bech32()?); - println!("hex: {public_key}"); - Ok(()) -} diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index 69d2835..00bb2c7 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -127,9 +127,11 @@ impl AppRoot { pub fn mount(window: &mut Window, cx: &mut App) -> Entity { let root = cx.new(|cx| Root::new(window, cx)); let content = cx.new(|cx| AppRoot::new(window, cx)); + root.update(cx, |root, cx| { root.set_content(content, cx); }); + root } diff --git a/crates/signed_app/src/identity/exit.rs b/crates/signed_app/src/identity/exit.rs index cd08ecb..d1ba7ec 100644 --- a/crates/signed_app/src/identity/exit.rs +++ b/crates/signed_app/src/identity/exit.rs @@ -58,7 +58,7 @@ impl Render for ExitDialog { .label("Exit") .variant(ButtonVariant::Destructive) .on_click(move |_, _, cx| { - backend.update(cx, |backend, cx| backend.sign_out(cx)).detach(); + backend.update(cx, |backend, cx| backend.sign_out(cx)); confirm_close.close(cx); }) .into_any_element(), diff --git a/crates/signed_state/src/backend.rs b/crates/signed_state/src/backend.rs index 34c0aab..8ba8311 100644 --- a/crates/signed_state/src/backend.rs +++ b/crates/signed_state/src/backend.rs @@ -11,7 +11,7 @@ use nostr::event::IntoEventBuilder; use nostr::nips::nip19::Nip19Coordinate; use nostr_connect::prelude::*; use nostr_sdk::prelude::*; -use signed_core::{Announcement, Filters, RepoAddr}; +use signed_core::{Announcement, Deletions, Filters, RepoAddr}; use signed_git::{GitCache, Repo}; use signed_nostr::{SignedAuthUrlHandler, UniversalSigner, Update}; @@ -41,8 +41,6 @@ pub enum BackendEvent { status: PushStepStatus, }, Error(String), - /// The relay list, profile and grasp list of a new identity were published; `Err` when no relay took them. - IdentityPublished(Result<(), String>), } impl BackendEvent { @@ -231,7 +229,7 @@ impl Backend { let task: Task> = cx.spawn(async move |this, cx| { let content = match user.await { Ok(Some((_username, secret))) => String::from_utf8(secret)?, - _ => { + Ok(None) => { this.update(cx, |this, cx| { if this.session == session { cx.emit(BackendEvent::SignerRequired); @@ -239,6 +237,17 @@ impl Backend { })?; return Ok(()); } + Err(error) => { + this.update(cx, |this, cx| { + if this.session == session { + cx.emit(BackendEvent::error(format!( + "failed to read the stored credential: {error}" + ))); + cx.emit(BackendEvent::SignerRequired); + } + })?; + return Ok(()); + } }; let result = async { @@ -552,19 +561,13 @@ impl Backend { .collect::>(); cx.spawn(async move |this, cx| { - let published = futures::future::try_join_all(publishes) - .await - .map(|_| ()) - .map_err(|error| { - format!("identity created, but publishing it failed: {error}") - }); - - this.update(cx, |_this, cx| { - if let Err(message) = &published { - cx.emit(BackendEvent::error(message.clone())); - } - cx.emit(BackendEvent::IdentityPublished(published)); - })?; + if let Err(error) = futures::future::try_join_all(publishes).await { + this.update(cx, |_this, cx| { + cx.emit(BackendEvent::error(format!( + "identity created, but publishing it failed: {error}" + ))); + })?; + } Ok::<(), anyhow::Error>(()) }) @@ -1086,6 +1089,45 @@ impl Backend { }) } + /// The latest announcement of `addr` and its latest state's `HEAD`, syncing the bootstrap relays when the database has neither. + pub async fn load_announcement( + client: &Client, + addr: &RepoAddr, + ) -> Result)>, Error> { + if let Some(found) = Self::stored_announcement(client, addr).await? { + return Ok(Some(found)); + } + + sync_bootstrap_only(client, addr.announcement_filter(), SyncOptions::default()).await?; + Self::stored_announcement(client, addr).await + } + + async fn stored_announcement( + client: &Client, + addr: &RepoAddr, + ) -> Result)>, Error> { + let db = client.database(); + let deletions = Deletions::from_events(db.query(Filters::deletions()).await?); + + let announcement = db + .query(addr.announcement_filter()) + .await? + .into_iter() + .filter(|event| !deletions.is_deleted(event)) + .max_by_key(|event| event.created_at) + .and_then(|event| Announcement::from_event(&event)); + + let head = db + .query(addr.state_filter()) + .await? + .into_iter() + .filter(|event| !deletions.is_deleted(event)) + .max_by_key(|event| event.created_at) + .and_then(|event| SyncState::parse(&event).head); + + Ok(announcement.map(|announcement| (announcement, head))) + } + fn bootstrap_user(&mut self, public_key: PublicKey, cx: &mut Context) { let client = self.client.clone(); @@ -1161,8 +1203,9 @@ impl Backend { self.passphrase_required } - pub fn sign_out(&mut self, cx: &mut Context) -> Task> { + pub fn sign_out(&mut self, cx: &mut Context) { self.supersede_session(); + // Nothing may be signed with the identity the user just left. self.signer.swap_inner(Keys::generate()); self.current_user = None; @@ -1173,11 +1216,6 @@ impl Backend { }); let delete = cx.delete_credentials(USER_KEYRING); - - cx.emit(BackendEvent::SignerChanged); - cx.emit(BackendEvent::SignerRequired); - cx.notify(); - cx.spawn(async move |this, cx| { if let Err(error) = delete.await { this.update(cx, |_this, cx| { @@ -1189,6 +1227,12 @@ impl Backend { Ok::<(), Error>(()) }) + .detach(); + + cx.emit(BackendEvent::SignerChanged); + cx.emit(BackendEvent::SignerRequired); + + cx.notify(); } fn sync_inbox(&mut self, cx: &mut Context) { diff --git a/crates/signed_state/src/lib.rs b/crates/signed_state/src/lib.rs index 8dcdaf3..6080eb7 100644 --- a/crates/signed_state/src/lib.rs +++ b/crates/signed_state/src/lib.rs @@ -34,12 +34,8 @@ pub use sync_status::{CheckoutSyncStatus, SyncEvent, SyncStatusDirectory, SyncSt pub fn init(cx: &mut App) -> anyhow::Result<()> { SettingsStore::set_global(cx.new(|_| SettingsStore::new(paths::settings_file())), cx); - let scan_paths = SettingsStore::global(cx) - .read(cx) - .settings() - .local_repos - .scan_paths - .clone(); + let settings = SettingsStore::global(cx); + let scan_paths = settings.read(cx).settings().local_repos.scan_paths.clone(); for dir in [paths::nostr_dir(), paths::repos_dir()] { if let Err(error) = std::fs::create_dir_all(dir) { diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 22cd993..1fc9b72 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use gpui::*; use gpui_platform::application; use settings::SettingsStore; +use signed_app::AppRoot; use ui::theme::{ActiveTheme as _, Theme}; actions!(signed, [Quit]); @@ -44,8 +45,6 @@ fn main() { .with_assets(AppAssets) .with_http_client(Arc::new(reqwest_client::ReqwestClient::new())) .run(move |cx| { - ui::init(cx); - cx.bind_keys([ KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("ctrl-q", Quit, None), @@ -54,16 +53,18 @@ fn main() { cx.on_action(|_: &Quit, cx| cx.quit()); cx.set_app_identity("build.signed.signed", "Signed"); + ui::init(cx); + metadata::init(cx); + if let Err(error) = signed_state::init(cx) { tracing::error!("failed to initialize application state: {error:#}"); cx.quit(); return; } - let appearance = SettingsStore::global(cx).read(cx).settings().appearance; - signed_app::AppRoot::apply_appearance_mode(appearance, cx); - - metadata::init(cx); + let settings = SettingsStore::global(cx); + let appearance = settings.read(cx).settings().appearance; + AppRoot::apply_appearance_mode(appearance, cx); let theme = cx.theme(); let bounds = Bounds::centered(None, size(px(1120.0), px(750.0)), cx); @@ -97,7 +98,7 @@ fn main() { }) .detach(); - signed_app::AppRoot::mount(window, cx) + AppRoot::mount(window, cx) }) { tracing::error!("failed to open window: {error}"); cx.quit();