Fetch real identity profiles and avatars through directory relays

An identity showed initials and often no name, while a client application's
icon was fetched, cached and rendered. Two reasons: profiles were fetched only
from Regent's configured relays — a members-only NIP-46 relay with no profiles
— and `Filter::limit(0)` caps the *stored* events a relay answers with to zero,
so that fetch received nothing at all even where profiles existed.

Discovery now goes through a measured directory set (directory.yabu.me,
purplepag.es, profiles.nostr1.com; `PROFILE_RELAYS`, overridable with
`REGENT_PROFILE_RELAYS`, else `REGENT_RELAYS` so an overridden run stays
offline). One REQ per author per relay: purplepag.es silently under-returns a
multi-author filter (8 of 20 keys batched, 15 of 20 per author), and its union
with the others is the same 15/20, so more relays buy availability, not
coverage. Three EOSE-capped waves on one ephemeral client — the identity's
kind-10002 and profile from the directory, then kind-0 from its own
write/unmarked relays, then the directory again if those served nothing — feed
one newest-wins map per kind. A relay is connected only when a wave will use it,
so a warm outbox opens no socket to the directory at all.

`profiles.json` keeps the outbox and its clocks: `write_relays` with the
kind-10002's `created_at` as a watermark, a 7-day TTL on discovery *attempts*
(so an identity that publishes no 10002 is re-discovered weekly, not on every
start), and a 1-day backoff on the directory fallback (a missing profile never
advances `fetched_at`, so `needs_refresh` stays true). A far-future `created_at`
is refused, so a relay cannot pin a watermark out of reach.

The picture is cached and rendered like a client icon: same hardened
`IconStore`, same 0600 files, decoded on the main loop. Identity avatars are
*not* behind `load-app-icons` — that switch is about a not-yet-trusted client's
URL — so the icon gc's live set grows to clients plus vault identities,
`forget_textures` clears the one-shot hydration claims it used to leave behind,
and removing a key forgets its avatar immediately. The switcher, the identities
list, the Connect dialog and the approval dialog's "Signing as" field draw it;
the Apps page's row stays text-only (that avatar was dropped deliberately in
d4bb9d5).

The gossip path in nostr-sdk was considered and rejected: its store is
in-process, it builds one filter per relay with the whole author set, and it
needs the same directory set anyway. Gitea issue #1.
This commit is contained in:
raucao committed 2026-11-29 14:47:00 +04:00
1 parent a9d51db400
commit 549829b0c0
10 files changed
+1500 -137

No files matched your search

+107 -14
View File
@@ -37,8 +37,8 @@ src/signer/policy.rs the auto-approval rate limit
src/store/apps.rs the registry of approved applications + their permissions
src/store/audit.rs the activity log (metadata only, mode 0600)
src/store/keys.rs the NIP-49 key vault (identity keys + the device key)
src/store/profiles.rs cached kind-0 display names (read-only)
src/store/icons.rs app icons: hardened fetch + disk cache (M11)
src/store/profiles.rs cached kind-0 names and picture URLs (read-only)
src/store/icons.rs app icons + identity avatars: hardened fetch, disk cache (M11)
src/ui/approval.rs approval dialogs
src/ui/apps_view.rs the apps page (permission table + revoke)
src/ui/activity_view.rs the activity page
@@ -402,7 +402,8 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
### The multi-identity UI (M7b)
- **Header identity switcher** (`ui/switcher.rs`, Fractal's account-switcher
pattern): a `GtkMenuButton` showing the current identity's initials avatar,
pattern): a `GtkMenuButton` showing the current identity's avatar (the kind-0
picture when one is cached, else initials),
opening a popover with one row per key (avatar, `display_name` or key label,
short npub, a check on the current), then "Manage identities…" (opens the
identities window). Hidden when there are no keys; rebuilds on key and selection
@@ -413,12 +414,84 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
to the identity and "Clear this identity's activity" keeps the rest. Pre-M7
audit rows (no identity) show under every scope.
- The "Connect an app" dialog names the identity a new pairing will use.
- **Profiles** (`store/profiles.rs`): kind-0 is fetched best-effort from the
configured relays and cached in `profiles.json` (0600). Only `display_name` is
shown — never nip05 as verified, since kind-0 is attacker-publishable. Avatars
are initials only (no image downloads). The fetch uses a fresh **ephemeral**
client, never the device/identity key, so a relay cannot link an identity to
this signer. Our relays are NIP-46 relays, so "no profile" is normal.
- **Profiles** (`store/profiles.rs`): kind-0 is fetched best-effort and cached in
`profiles.json` (0600). Discovery goes through a **directory set** —
`PROFILE_RELAYS` (`wss://directory.yabu.me`, `wss://purplepag.es`,
`wss://profiles.nostr1.com`), overridable with `REGENT_PROFILE_RELAYS`, else
`REGENT_RELAYS` (so an overridden run — acceptance, the ignored tests, a headless
check — makes no public requests), else the constant. **The NIP-46 relays are
never asked for profiles**: they are members-only and carry none, and an
`authors` query tells them which identities this machine holds. The set is
measured, not guessed (2026-11-29, 20-key sample; full data in the plan's
`relay-survey`): those three answered the most kind-10002 and kind-0, all fresh,
0.74–0.98 s to EOSE. The per-author union of every candidate tried was the same
15/20, so further relays buy availability, not coverage.
- **One REQ per author, never a batched author list.** purplepag.es silently
under-returns a multi-author filter (measured: 8 of 20 keys batched, 15 of 20
per author; it also replays historical versions, so an event count is not an
author count). `author_targets` therefore emits one filter per relay, one author
ever; in `nostr-sdk` that means one `subscribe`/`fetch_events` call per identity
(`RelayPool` generates **one** `SubscriptionId` shared by every targeted relay,
and reports success as `HashMap<RelayUrl, ()>` — completion is keyed on
`(relay_url, id)`, not on per-relay ids). The SDK's **gossip** path was
considered and rejected (its store is in-process, it batches authors per relay,
and it needs the same directory set anyway); see §10.7 of the profile plan for
the tradeoffs and the growth path. Filters carry **no `limit`**:
`limit(0)` caps the *stored* events a relay sends to zero, so a fetch with one
receives nothing at all (live subscriptions still work, which is why the signer
uses it).
- **Three EOSE-capped waves, one newest-wins map per kind.** 1. *discovery*:
kind-10002 + kind-0 from the directory set for an identity with no trustworthy
outbox; 2. *outbox*: kind-0 from the identity's own write/unmarked relays
(capped at `MAX_OUTBOX_RELAYS`); 3. *directory fallback*: kind-0 from the
directory for an identity whose own relays served nothing. Waves end on EOSE
(`fetch_events`, `WAVE_CAP` 5 s as the backstop). A relay is added and connected
only when a wave is about to use it — a warm outbox opens no socket to the
directory set at all — and never while it is still connecting, because a REQ sent
then is registered but not transmitted (trap 2). Budget: warm ~1 s (one wave on
the identity's own relays); cold ~2–3 s; when every relay stalls, a single
identity that has to discover and then reach its outbox costs at most two
`CONNECT_WAIT`s plus two `WAVE_CAP`s (~20 s), and each further identity adds up
to one cap per wave it joins — all on the async runtime. A whole-wave setup
failure (a relay that left the pool) is retried one relay at a time, so it
cannot discard the other relays' answers.
Every event goes through one `consider` merge
that drops authors nobody asked for and any `created_at` more than 5 minutes in
the future (`FUTURE_SLACK`) — that is what keeps a relay from pinning a
watermark out of reach.
- **`profiles.json` holds the outbox and its clocks**, written by three
single-owner writers: `put_metadata` (kind-0, refuses a not-newer answer,
sets `kind0_at`/`fetched_at`), `put_relay_list` (sets `write_relays` only from a
newer kind-10002 — `created_at = 0` means "nothing found" and only moves the
clock, so a transient miss cannot wipe a working outbox — and always sets
`relays_checked_at`), and `note_recovery`. `RELAYS_TTL` is **7 days** on
*attempts*, so an identity that publishes no 10002 is re-discovered weekly, not
on every start; `RECOVERY_BACKOFF` is 1 day on the directory kind-0 fallback,
which matters because a missing profile never advances `fetched_at`, so
`needs_refresh` stays true. (**Amber does none of this**: it re-queries the
kind-10002 on every profile fetch, applies it only if newer, and always asks
*indexers ∪ saved relays* — no TTL, no outbox-only path.) Disclosure, honestly:
the discovery wave leaves the machine weekly per identity (daily through the
recovery clock when the identity's own relays cannot serve it), and an identity
with no usable outbox keeps asking the directory for **kind-0** at the refresh
cadence. The ignored `nak_the_outbox_relay_profile_wins` test covers the
cross-relay newest-wins rule, two identities and the warm path (dead directory,
cached outbox) against two local `nak serve`s on ports 10590/10591.
- Only `display_name` and `picture` are kept; nip05 is never shown as verified,
since kind-0 is attacker-publishable. `picture` is bounded like
`ClientInfo.image` (trimmed, ≤256 chars, blank ⇒ absent) and re-bounded on
read, because `profiles.json` is on disk.
- **Identity avatars are fetched, cached and rendered** through the *same*
hardened `IconStore` as app icons (https/inline `data:` only, pinned public
addresses, ≤3 re-validated redirects, 1 MiB, magic-byte raster gate — see
M11). `AppState::ensure_avatars` is the single "make avatars show" call, from
`refresh_identities` and from the profile fetch's completion; it hydrates the
cached picture and fetches the rest. **Not gated by `load-app-icons`**: that
switch is about requesting a not-yet-trusted *client's* URL, while this is the
user's own identity. The leak that follows is real and accepted: the picture
host learns the request (and the machine's address), as the relays already do.
- The fetch uses a fresh **ephemeral** client, never the device/identity key, so
a relay cannot link an identity to this signer.
- `AppState::identity_label` is the single display rule: profile `display_name`
first, else the user's key label.
- Adding a key never switches the selection. A key refresh never clobbers a pick
@@ -638,11 +711,24 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
**decoration, never the sole identifier**, and the name stays plain text — a
client must not be able to forge something that looks like Regent's own UI.
- `gc` runs only on an actual Apps-page rebuild (revoke/forget/last-key-removed),
never per ping, and its live set is `AppRegistry::client_keys()` — every pubkey
across identities. The page list is identity-scoped, so a live set taken from it
would evict other identities' icons.
- **Preference** `load-app-icons` (GSettings, default on) gates all fetching;
turning it off clears the in-memory textures and rebuilds to initials.
never per ping, and its live set is `AppState::icon_live_keys()` — every client
pubkey across identities **plus every identity key in the vault**. The page list
is identity-scoped, so a live set taken from it would evict other identities'
icons; and identity avatars live in this same namespace, so a clients-only live
set would evict them on any Apps rebuild. Removing an identity key forgets its
avatar immediately (`keys_view`), not at the next gc.
- **Identity avatars share this store.** An identity's kind-0 `picture` is
fetched, cached and rendered exactly like an app icon (`ensure_avatars`,
`hydrate_avatar`/`load_avatar`/`show_avatar` in `state.rs`), which is why the
two are keyed by the same 64-hex namespace. The only differences: it is **not**
gated by `load-app-icons`, it is fetched at startup and on every profile
refresh rather than at consent time, and `show_avatar` hands the texture to an
approval dialog that outlives no single rebuild.
- **Preference** `load-app-icons` (GSettings, default on) gates **client** icon
fetching; turning it off calls `IconStore::forget_textures` (textures *and* the
one-shot hydration claims, so the disk cache can be read again) and rebuilds to
initials. Identity avatars are re-hydrated right after, because they do not
belong to that switch.
- `client_info` bounds `image` to 256 chars like `parse_client_uri` does — it
reaches `apps.json` and is now a fetch input.
@@ -898,6 +984,13 @@ the UI is tested. `build-aux/deploy-dev.sh` runs on the build host,
end: a locked vault that the user opens signs, and one the user does not open
denies with `locked` in the log (never `allowed-silently`) — plus a responder
test that a silent UI never unlocks.
- `store::profiles::tests::nak_the_outbox_relay_profile_wins` (ignored, needs
`nak` and ports 10590/10591) is the profile fetch's end-to-end check: an older
kind-0 on the directory relay, a newer one on the identity's own relay named by
its kind-10002, two identities (so the per-author shape is exercised), and two
warm-path fetches — one where the directory is *alive* and holds a newer profile
(which must NOT be used: the cached outbox wins), and one with the directory
killed (the outbox still serves).
- `a_request_on_an_added_relay_is_answered_there` (ignored, needs `nak`) starts
the signer on one relay, adds a second, and drives a request/response through
the added one — the check that a dynamically added client relay carries both
+4
View File
@@ -208,6 +208,7 @@ GDK_BACKEND=broadway BROADWAY_DISPLAY=:11 \
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_GRESOURCE="$ROOT/$BUILD/data/resources/org.kosmos.raucao.Regent.gresource" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
REGENT_PROFILE_RELAYS="ws://127.0.0.1:$PORT" \
REGENT_NOTIFY_ALWAYS=1 \
"$ROOT/$BUILD/regent" >"$TMP_HOME/app.log" 2>&1 &
APP=$!
@@ -329,6 +330,7 @@ sleep 2
URI="nostrconnect://$CLIENT?relay=ws%3A%2F%2F127.0.0.1%3A$PORT&secret=acceptance&name=Acceptance%20Client&perms=sign_event%3A1"
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
REGENT_PROFILE_RELAYS="ws://127.0.0.1:$PORT" \
"$ROOT/$BUILD/regent" --pair "$URI" --passphrase-file "$PASSPHRASE_FILE" \
>"$TMP_HOME/headless.log" 2>&1 &
HEADLESS=$!
@@ -378,6 +380,7 @@ GDK_BACKEND=broadway BROADWAY_DISPLAY=:11 \
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_GRESOURCE="$ROOT/$BUILD/data/resources/org.kosmos.raucao.Regent.gresource" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
REGENT_PROFILE_RELAYS="ws://127.0.0.1:$PORT" \
timeout 8 "$ROOT/$BUILD/regent" >"$TMP_HOME/first-run.log" 2>&1
grep -q 'no identity key yet, opening the identities window' "$TMP_HOME/first-run.log"
@@ -393,6 +396,7 @@ GDK_BACKEND=broadway BROADWAY_DISPLAY=:11 \
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_GRESOURCE="$ROOT/$BUILD/data/resources/org.kosmos.raucao.Regent.gresource" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
REGENT_PROFILE_RELAYS="ws://127.0.0.1:$PORT" \
"$ROOT/$BUILD/regent" --background >"$TMP_HOME/background.log" 2>&1 &
BACKGROUND=$!
sleep 6
+133 -13
View File
@@ -157,9 +157,9 @@ impl AppState {
Rc::clone(&self.icons)
}
/// Decode an already-cached icon, on this (main) thread, so a first paint
/// shows it without a round trip. Bounded by the icon byte cap.
pub fn hydrate_icon(&self, key: &str, url: &str) {
/// Decode an already-cached image, on this (main) thread, so a first paint
/// shows it without a round trip. Bounded by the byte cap.
fn hydrate_texture(&self, key: &str, url: &str, noun: &str) {
let icons = self.icons();
if !icons.begin_hydrate(key, url) {
return;
@@ -173,16 +173,23 @@ impl AppState {
match crate::store::icons::decode(&bytes) {
Ok(texture) => icons.set_texture(key, texture),
Err(error) => {
eprintln!("regent: ignoring a cached app icon: {error}");
eprintln!("regent: ignoring a cached {noun}: {error}");
icons.mark_failed(key, url);
}
}
}
/// Fetch an application's icon, decode it on the main loop, cache it and ask
/// the views to repaint. A no-op when it is cached, in flight, or the key or
/// URL is unusable.
pub fn load_icon(self: &Rc<Self>, key: &str, url: &str) {
/// Fetch an image, decode it on the main loop, cache it and ask the views to
/// repaint. A no-op when it is cached, in flight, or the key or URL is
/// unusable. `apply` hands the fresh texture to a widget that will not be
/// rebuilt by the change ping (a dialog's avatar).
fn load_texture(
self: &Rc<Self>,
key: &str,
url: &str,
noun: &'static str,
apply: Option<Box<dyn FnOnce(gdk::Texture) + 'static>>,
) {
let icons = self.icons();
if !icons.begin(key, url) {
return;
@@ -199,15 +206,18 @@ impl AppState {
Ok(bytes) => match crate::store::icons::decode(&bytes) {
Ok(texture) => {
icons.store(&key, &url, &bytes);
icons.set_texture(&key, texture);
icons.set_texture(&key, texture.clone());
if let Some(apply) = apply {
apply(texture);
}
}
Err(error) => {
eprintln!("regent: could not decode an app icon: {error}");
eprintln!("regent: could not decode an {noun}: {error}");
icons.mark_failed(&key, &url);
}
},
Err(error) => {
eprintln!("regent: could not fetch an app icon: {error}");
eprintln!("regent: could not fetch an {noun}: {error}");
icons.mark_failed(&key, &url);
}
}
@@ -216,6 +226,69 @@ impl AppState {
);
}
/// Decode an already-cached application icon.
pub fn hydrate_icon(&self, key: &str, url: &str) {
self.hydrate_texture(key, url, "app icon");
}
/// Fetch an application's icon.
pub fn load_icon(self: &Rc<Self>, key: &str, url: &str) {
self.load_texture(key, url, "app icon", None);
}
/// Decode an already-cached identity avatar. Same cache as the app icons —
/// both are public-key-keyed pictures fetched through the hardened path.
pub fn hydrate_avatar(&self, key: &str, url: &str) {
self.hydrate_texture(key, url, "identity avatar");
}
/// Fetch an identity's avatar.
pub fn load_avatar(self: &Rc<Self>, key: &str, url: &str) {
self.load_texture(key, url, "identity avatar", None);
}
/// Show an identity avatar on a widget that outlives one refresh — the
/// approval dialog is built per question, so a cached texture is used at
/// once and a fetch is swapped in through `apply` when it lands.
pub fn show_avatar(
self: &Rc<Self>,
key: &str,
url: &str,
apply: impl FnOnce(gdk::Texture) + 'static,
) {
if let Some(texture) = self.icons().texture(key) {
apply(texture);
return;
}
self.load_texture(key, url, "identity avatar", Some(Box::new(apply)));
}
/// Hydrate or fetch the avatar of every identity key that has a picture.
///
/// Deliberately **not** behind `load-app-icons`: that switch exists because a
/// client's declared URL is a request to a not-yet-trusted server, while this
/// is the user's own identity. Idempotent — the sidecar URL arms the fetch, so
/// a second call in one run does nothing.
pub fn ensure_avatars(self: &Rc<Self>) {
for key in self.store.list_user_keys() {
let Some(picture) = self.profiles.picture(&key.public_key) else {
continue;
};
if !crate::store::icons::is_fetchable(&picture) {
continue;
}
let hex = key.public_key.to_hex();
self.hydrate_avatar(&hex, &picture);
self.load_avatar(&hex, &picture);
}
}
/// Every pubkey whose cached image must survive an icon gc: approved clients
/// across all identities, plus every identity key in the vault.
pub fn icon_live_keys(&self) -> Vec<String> {
live_icon_keys(&self.registry.lock().unwrap(), &self.store.list_user_keys())
}
/// Fetch a client's declared icon for an approval dialog, **before** it is
/// approved, and hand the texture to `apply` for display.
///
@@ -308,6 +381,7 @@ impl AppState {
}
self.notify();
self.notify_changes();
self.ensure_avatars();
self.fetch_profiles(
keys.iter()
.filter(|key| self.profiles.needs_refresh(&key.public_key))
@@ -322,15 +396,18 @@ impl AppState {
if keys.is_empty() {
return;
}
let relays = Config::new().relays();
let directory = crate::store::profiles::profile_relays();
let profiles = self.profiles.clone();
let state = Rc::clone(self);
runtime::spawn(
async move { crate::store::profiles::fetch(relays, keys, profiles).await },
async move { crate::store::profiles::fetch(directory, keys, profiles).await },
move |result| {
if let Err(error) = result {
eprintln!("regent: could not fetch profiles: {error}");
}
// A profile that just arrived may carry a picture: hydrate what
// is cached and fetch the rest. Safe to call on every fetch.
state.ensure_avatars();
state.notify();
state.notify_changes();
},
@@ -388,6 +465,19 @@ fn resolve_selection(
.or_else(|| keys.first().map(|key| key.public_key))
}
/// The live set for [`IconStore::gc`]: every approved client across all
/// identities, plus every identity key in the vault.
///
/// A pubkey can be both (a user may pair their own key), and they share one
/// cache namespace, so leaving either out would evict a real image on the next
/// Apps-page rebuild. Free function so it is testable without an `AppState`
/// (which opens the real vault and starts a profile fetch).
fn live_icon_keys(registry: &AppRegistry, keys: &[KeyRef]) -> Vec<String> {
let mut live = registry.client_keys();
live.extend(keys.iter().map(|key| key.public_key.to_hex()));
live
}
#[cfg(test)]
mod tests {
use super::*;
@@ -427,4 +517,34 @@ mod tests {
Some(a_pk)
);
}
/// An icon gc must keep both kinds of cached picture: a client's app icon
/// and an identity's avatar live in the same namespace.
#[test]
fn the_icon_live_set_covers_clients_and_identities() {
use crate::signer::approval::ClientInfo;
let (identity, identity_pk) = key("me");
let client = Keys::generate().public_key();
let mut registry = AppRegistry::default();
registry
.approve(
&ClientInfo {
public_key: client,
name: None,
url: None,
image: None,
},
identity_pk,
None,
)
.unwrap();
let live = live_icon_keys(&registry, &[identity]);
assert!(live.contains(&client.to_hex()), "the client's icon stays");
assert!(
live.contains(&identity_pk.to_hex()),
"the identity's avatar stays"
);
}
}
+35 -3
View File
@@ -391,10 +391,17 @@ impl IconStore {
}
}
/// Drop the decoded textures (not the files). Used when icon loading is turned
/// off, so the rows fall back to initials without losing the cache.
pub fn clear_textures(&self) {
/// Drop the decoded textures (not the files), so the rows fall back to initials
/// without losing the cache.
///
/// The one-shot hydration claims go too: otherwise a texture dropped here could
/// never be read back from the untouched `.img` (they are what keeps a missing
/// cached icon from being probed on every change ping). Fetches already in
/// flight are left alone — they will set their texture when they land, and
/// forgetting them would only allow a duplicate request.
pub fn forget_textures(&self) {
self.textures.borrow_mut().clear();
self.hydrated.borrow_mut().clear();
}
/// Claim `(key, url)` for a fetch. `false` when it is already in flight, was
@@ -709,6 +716,31 @@ mod tests {
assert!(store.needs_fetch(&dead, url), "the evicted key must refetch");
}
#[test]
fn forgetting_textures_lets_the_cache_be_hydrated_again() {
let dir = temp_dir();
let store = IconStore::at(dir.clone());
let key = key();
let url = "https://example.com/i.png";
let bytes = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
store.store(&key, url, &bytes);
assert!(store.begin_hydrate(&key, url), "the first paint claims it");
assert!(
!store.begin_hydrate(&key, url),
"a second paint must not probe the disk again"
);
assert!(store.cached_bytes(&key, url).is_some());
store.forget_textures();
assert!(store.texture(&key).is_none());
assert!(
store.begin_hydrate(&key, url),
"the texture is gone, so the cache may be read again"
);
assert_eq!(store.cached_bytes(&key, url).as_deref(), Some(&bytes[..]));
}
#[test]
fn an_invalid_key_is_refused() {
let dir = temp_dir();
+1137 -83
View File
File diff suppressed because it is too large. Load diff
+15 -7
View File
@@ -643,13 +643,21 @@ fn identity_field(state: &Rc<AppState>, identity: &crate::signer::approval::Sign
.spacing(10)
.build();
// The same avatar/placeholder as the application field beside it: initials of
// the name, or libadwaita's glyph when it has none, with a cached image when
// there is one (identities have none yet).
let avatar = plain::avatar(
32,
name,
state.icons().texture(&identity.public_key.to_hex()).as_ref(),
);
// the name, or libadwaita's glyph when it has none, with the identity's own
// cached picture when there is one. A prompt can arrive before that fetch
// ever ran, so a missing texture is swapped in when it lands.
let hex = identity.public_key.to_hex();
let texture = state.icons().texture(&hex);
let avatar = plain::avatar(32, name, texture.as_ref());
if texture.is_none()
&& let Some(picture) = state.profiles().picture(&identity.public_key)
&& crate::store::icons::is_fetchable(&picture)
{
let avatar = avatar.clone();
state.show_avatar(&hex, &picture, move |texture| {
avatar.set_custom_image(Some(&texture));
});
}
// A signing key always has a name; the shortened npub is only a fallback
// for a key that somehow does not.
let value = match name {
+4 -2
View File
@@ -251,8 +251,10 @@ impl Ui {
self.body.append(&self.forget_all_group());
// Reap icons for apps that are gone (revoke, logout, last key removed).
// Only here, on an actual rebuild — never on every change ping.
let live = self.state.registry().lock().unwrap().client_keys();
// Only here, on an actual rebuild — never on every change ping. The live
// set is clients **and** identities: both have cached pictures in this
// namespace, and an identity avatar must survive an Apps rebuild.
let live = self.state.icon_live_keys();
self.state.icons().gc(&live);
}
+50 -9
View File
@@ -36,6 +36,10 @@ struct Handles {
/// The rows currently in the list, so a reload can remove exactly them.
type Rows = Rc<RefCell<Vec<adw::ActionRow>>>;
/// Each row's avatar and the key it belongs to, so a picture that lands later
/// can be swapped in without rebuilding the list (a rebuild would close a row's
/// open menu).
type Avatars = Rc<RefCell<Vec<(String, adw::Avatar)>>>;
/// The toplevel, resolved lazily: a view is not in a window when it is built.
fn toplevel(handles: &Handles) -> Option<gtk::Window> {
@@ -114,6 +118,7 @@ impl KeysView {
overlay: overlay.clone(),
};
let rows: Rows = Rc::new(RefCell::new(Vec::new()));
let avatars: Avatars = Rc::new(RefCell::new(Vec::new()));
let widget: gtk::Widget = overlay.upcast();
for button in [&create_button, &create] {
@@ -127,11 +132,20 @@ impl KeysView {
// Reload on key changes (`refresh_identities` announces them with
// `notify`). The selection no longer shows here, so a registry change is
// nothing this window needs to hear about.
// nothing this window needs to hear about — but an avatar that lands
// later does: `listen_changes` is what an icon/avatar fetch announces.
{
let (listener_state, handles, rows) =
(Rc::clone(&state), handles.clone(), Rc::clone(&rows));
state.listen(move || reload(&listener_state, &handles, &rows));
let (listener_state, handles, rows, avatars) = (
Rc::clone(&state),
handles.clone(),
Rc::clone(&rows),
Rc::clone(&avatars),
);
state.listen(move || reload(&listener_state, &handles, &rows, &avatars));
}
{
let (listener_state, avatars) = (Rc::clone(&state), Rc::clone(&avatars));
state.listen_changes(move || refresh_avatars(&listener_state, &avatars));
}
Self { widget }
@@ -139,10 +153,11 @@ impl KeysView {
}
/// Rebuild the identity list from the shared state.
fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows) {
fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows, avatars: &Avatars) {
for row in rows.borrow_mut().drain(..) {
handles.list.remove(&row);
}
avatars.borrow_mut().clear();
let names = state.names();
let names = names.lock().unwrap().clone();
@@ -159,15 +174,28 @@ fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows) {
let profile = PublicKey::from_hex(&hex)
.ok()
.and_then(|key| state.profiles().display_name(&key));
let row = key_row(state, handles, &hex, &name, profile.as_deref());
let row = key_row(state, handles, avatars, &hex, &name, profile.as_deref());
handles.list.add(&row);
rows.borrow_mut().push(row);
}
}
/// Put the pictures that landed after the list was built onto the existing rows.
///
/// Deliberately not a `reload`: a change ping also fires for activity and app
/// registry changes, and rebuilding would close an open per-key menu for a
/// reason the user cannot see.
fn refresh_avatars(state: &Rc<AppState>, avatars: &Avatars) {
for (hex, avatar) in avatars.borrow().iter() {
let texture = state.icons().texture(hex);
avatar.set_custom_image(texture.as_ref());
}
}
fn key_row(
state: &Rc<AppState>,
handles: &Handles,
avatars: &Avatars,
hex: &str,
name: &str,
profile: Option<&str>,
@@ -185,8 +213,15 @@ fn key_row(
// One line, cut to `head…tail`; the full npub stays reachable as a tooltip.
row.set_subtitle_lines(1);
row.set_tooltip_text(Some(&npub));
// Initials avatar, from the kind-0 name when there is one.
row.add_prefix(&adw::Avatar::new(32, Some(profile.unwrap_or(name)), true));
// The identity's own picture when one is cached, else initials. Decoration:
// the name beside it stays the identifier.
let avatar = plain::avatar(
32,
Some(profile.unwrap_or(name)),
state.icons().texture(hex).as_ref(),
);
row.add_prefix(&avatar);
avatars.borrow_mut().push((hex.to_string(), avatar));
let menu = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
@@ -623,6 +658,7 @@ fn present_remove(
let registry = state.registry();
let after = Rc::clone(&state);
let handles = handles.clone();
let hex = public_key.to_hex();
runtime::spawn(
async move {
registry.lock().unwrap().clear_for(public_key)?;
@@ -630,7 +666,12 @@ fn present_remove(
Ok::<(), crate::store::keys::Error>(())
},
move |result| match result {
Ok(()) => after.refresh_identities(),
Ok(()) => {
// The identity is gone, so its cached avatar has no
// owner left; do not wait for an Apps-page gc.
after.icons().forget(&hex);
after.refresh_identities();
}
Err(error) => report_error(&handles, &error),
},
);
+6 -3
View File
@@ -330,9 +330,12 @@ impl Preferences {
config.set_load_app_icons(load);
}
if !load {
// Drop the decoded textures and rebuild, so the rows fall
// back to initials without touching the cache on disk.
preferences.state.icons().clear_textures();
// Drop the decoded textures and rebuild, so client rows fall
// back to initials without touching the cache on disk. Then
// bring back the identity avatars: they are not gated by this
// switch, so they must not disappear with the client icons.
preferences.state.icons().forget_textures();
preferences.state.ensure_avatars();
}
preferences.state.notify_changes();
});
+9 -3
View File
@@ -14,7 +14,6 @@ use nostr::nips::nip19::ToBech32;
use nostr::prelude::PublicKey;
use gtk::prelude::*;
use libadwaita as adw;
use crate::state::AppState;
use crate::ui::plain;
@@ -82,7 +81,10 @@ impl IdentitySwitcher {
let current_label = current
.map(|key| self.state.identity_label(&key))
.unwrap_or_else(|| "?".to_string());
let avatar = adw::Avatar::new(24, Some(&current_label), true);
let current_texture = current
.map(|key| self.state.icons().texture(&key.to_hex()))
.unwrap_or_default();
let avatar = plain::avatar(24, Some(&current_label), current_texture.as_ref());
self.button.set_child(Some(&avatar));
self.button
.set_tooltip_text(Some(&format!("Identity: {current_label}")));
@@ -133,7 +135,11 @@ impl IdentitySwitcher {
.orientation(gtk::Orientation::Horizontal)
.spacing(10)
.build();
line.append(&adw::Avatar::new(32, Some(&label), true));
line.append(&plain::avatar(
32,
Some(&label),
self.state.icons().texture(hex).as_ref(),
));
let texts = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)