Skip to content

Commit 8953cbf

Browse files
wesbillmanCarl
andauthored
fix(desktop): keep managed agent avatars usable across communities (block#7732)
## Summary Fix Desktop-managed agents losing avatars after joining another community. The saved persona/instance stores one desired source URL, but authenticated media belongs to a community. Republishing community A’s URL in B does not make that image accessible in B. - Before comparing or publishing kind-0, reuse or copy configured-community avatar media into the pinned destination. Keep exact image bytes, including animation, and leave the saved source unchanged. - Keep the previous profile on transfer/publication failure so existing reconciliation can retry. Reuse destination bytes during source outages; after source removal, reuse only an already-published signed destination picture with the same original content hash. - Refresh source permissions through narrow, serialized IPC without reconnecting or resetting the active community. Startup waits until the latest permission update completes before restoring agents. ### Related issue Refs block#2366 (avatar portion only, not runtime availability). Related block#2659 deliberately excludes avatar/media mirroring; this change addresses that media boundary without introducing runtime fan-out. Searched existing issues/PRs for `avatar community` before opening. ## Contract and safety Desktop-managed profiles still follow the saved persona source; this does not introduce community-specific persona editing. Agent-managed profiles still opt out of automatic reconciliation. Authenticated transfer requests use the fixed agent key/NIP-OA tag, origin-scoped Blossom auth, and the pinned destination, never mutable active-workspace owner credentials. They refuse redirects, enforce 30-second request timeouts and bounded bodies, verify SHA-256 and detected image MIME, and validate the returned descriptor’s origin/hash/MIME/size. Source permission is rechecked after an awaited destination HEAD miss. The removed-source fallback verifies the destination profile’s signature, kind, signer, origin, and original-media hash without contacting the removed source. Ordinary external images retain passthrough behavior and receive no community credentials. No public-media policy change, image-reader URL rewriting, new persistence, background service, or global profile merge. ## Testing Normal commit and push hooks passed on exact head `925781eece66d5f6a4b084b3b3abd6309cda357e`; working tree clean before and after: - Desktop formatting/lint, typecheck, and **6,508 tests**. - Full native workspace suite, including **3,204 desktop-library tests** (19 ignored), integration tests, terminal crates, and doc tests. - Native Clippy on default and `mesh-llm` workspace/all-target configurations with warnings denied; repository file-size and branch-skew gates. Regression coverage exercises production reconciliation/shared publication against two local HTTP fixtures: add/edit/restart, upload and rejected-publication retry, removed-source local-image preservation, fixed signer/destination, redirect/hash/descriptor/size failures, revocation during pending HEAD, and opt-out no-I/O. Mounted initialization tests cover inactive-list changes without workspace reset, two deferred permission updates, and rejection of either update. Earlier working-tree validation at base `4ab4f786085a23fe6126529861840eff6048ceee` also passed the E2E frontend build and four Chromium mock-bridge community flows (boot, switch, active removal/fallback, leave-final/setup). Subsequent production changes only serialize permission writes and wait for a stable latest update; the complete suites above cover the final commit. Mutations independently removing serialization or stable waiting failed the new regression. ## Remaining validation and limitations - No live production avatar was changed. Native GUI rendering against two hosted communities remains to be verified with a build containing this fix; local HTTP fixtures and the browser mock bridge do not establish that outcome. - A removed/unreachable source with no existing destination copy cannot be recovered automatically. Choose a reachable image/source in that case. - This is a publication/reconciliation fix, not a visual redesign. No before/after native GUI screenshots are claimed. Broad repository CI remains required; it was not duplicated locally. ## Review Independent security/scope and caller/ordering reviews are clear after the bounded fixes. Final hook-ordering reread covered the staged tree that became this commit. Commit authorship/sign-off use the implementing Carl identity and configured Carl signing key. Signed-off-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz> Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
1 parent 779af88 commit 8953cbf

17 files changed

Lines changed: 1234 additions & 13 deletions

File tree

‎desktop/src-tauri/src/app_state.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ pub struct AppState {
3232
/// validated relay origin.
3333
pub media_fetch_client: reqwest::Client,
3434
pub relay_url_override: Mutex<Option<String>>,
35+
/// User-configured communities, supplied by narrow workspace IPC, never learned
36+
/// from profile URLs. Only these origins may supply portable agent media.
37+
pub agent_avatar_communities: Mutex<Vec<String>>,
3538
pub workspace_apply_lock: Arc<AsyncMutex<()>>,
3639
pub workspace_apply_generation: AtomicU64,
3740
/// Defers managed-agent restore until `apply_workspace` installs relay and identity.
@@ -213,6 +216,7 @@ pub fn build_app_state() -> AppState {
213216
header across origins (redirect-hop SSRF)",
214217
),
215218
relay_url_override: Mutex::new(None),
219+
agent_avatar_communities: Mutex::new(Vec::new()),
216220
workspace_apply_lock: Arc::new(AsyncMutex::new(())),
217221
workspace_apply_generation: AtomicU64::new(0),
218222
managed_agent_restore_pending: AtomicBool::new(false),

‎desktop/src-tauri/src/commands/agents_profile.rs‎

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ pub(crate) struct ProfileReconcileData {
2525
/// left unpinned (no tenant boundary) resolves the current workspace at
2626
/// execution time. See `resolve_reconcile_relay`.
2727
pub(crate) target_relay_url: Option<String>,
28-
/// Expected avatar URL for the published profile. `None` for legacy records
28+
/// Saved avatar source, localized to the target community before publishing.
29+
/// `None` for legacy records
2930
/// that predate the `avatar_url` field — these will be backfilled from the
3031
/// relay's existing kind:0 profile on first reconciliation.
3132
pub(crate) avatar_url: Option<String>,
@@ -195,7 +196,7 @@ pub(crate) async fn reconcile_agent_profile(
195196
agent_pubkey: &str,
196197
data: &ProfileReconcileData,
197198
) -> Result<ProfileReconcileOutcome, String> {
198-
use crate::relay::{query_agent_profile, sync_managed_agent_profile};
199+
use crate::relay::query_agent_profile;
199200

200201
// Resolved ONCE and used for both the read and the write-back. A pinned
201202
// `target_relay_url` wins unconditionally — see `resolve_reconcile_relay`.
@@ -260,28 +261,62 @@ pub(crate) async fn reconcile_agent_profile(
260261
Some(expected_avatar)
261262
};
262263

263-
if !profile_needs_sync(
264+
reconcile_profile_at(
265+
state,
266+
&relay_url,
267+
data,
268+
expected_avatar.as_deref(),
264269
existing.as_ref(),
270+
)
271+
.await
272+
}
273+
274+
/// Network half of startup/restore reconciliation, after legacy source backfill.
275+
/// Kept separate from the disk migration so the production compare-and-publish
276+
/// seam can be exercised against two communities without a GUI runtime.
277+
pub(crate) async fn reconcile_profile_at(
278+
state: &AppState,
279+
relay_url: &str,
280+
data: &ProfileReconcileData,
281+
expected_avatar: Option<&str>,
282+
existing: Option<&crate::relay::AgentProfileInfo>,
283+
) -> Result<ProfileReconcileOutcome, String> {
284+
if !state
285+
.managed_agent_profile_reconcile_enabled()
286+
.load(std::sync::atomic::Ordering::Acquire)
287+
{
288+
return Ok(ProfileReconcileOutcome::SkippedDisabled);
289+
}
290+
let agent_keys = Keys::parse(&data.private_key_nsec)
291+
.map_err(|e| format!("failed to parse agent keys: {e}"))?;
292+
let expected_avatar = crate::relay::profile_avatar::localize_avatar(
293+
state,
294+
relay_url,
295+
&agent_keys,
296+
expected_avatar,
297+
data.auth_tag.as_deref(),
298+
)
299+
.await?;
300+
301+
if !profile_needs_sync(
302+
existing,
265303
&data.name,
266304
expected_avatar.as_deref(),
267305
data.about.as_deref(),
268306
) {
269307
return Ok(ProfileReconcileOutcome::Reconciled);
270308
}
271309

272-
let agent_keys = Keys::parse(&data.private_key_nsec)
273-
.map_err(|e| format!("failed to parse agent keys: {e}"))?;
274-
275310
if !state
276311
.managed_agent_profile_reconcile_enabled()
277312
.load(std::sync::atomic::Ordering::Acquire)
278313
{
279314
return Ok(ProfileReconcileOutcome::SkippedDisabled);
280315
}
281316

282-
sync_managed_agent_profile(
317+
crate::relay::sync_managed_agent_profile(
283318
state,
284-
&relay_url,
319+
relay_url,
285320
&agent_keys,
286321
&data.name,
287322
expected_avatar.as_deref(),

‎desktop/src-tauri/src/commands/media.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ pub(crate) fn mint_media_get_auth(state: &AppState, base_url: &str) -> Option<St
359359
}
360360
}
361361

362-
fn sign_blossom_upload_auth(
362+
pub(crate) fn sign_blossom_upload_auth(
363363
keys: &Keys,
364364
sha256: &str,
365365
expiry_secs: u64,

‎desktop/src-tauri/src/commands/workspace.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,20 @@ pub async fn validate_repos_dir(dir: String) -> Result<(), String> {
136136
.map_err(|e| format!("spawn_blocking failed: {e}"))?
137137
}
138138

139+
/// Refresh avatar source trust without reconnecting or restoring the workspace.
140+
/// Only the user's saved community list may supply these origins.
141+
#[tauri::command]
142+
pub fn set_agent_avatar_communities(
143+
relay_urls: Vec<String>,
144+
state: State<'_, AppState>,
145+
) -> Result<(), String> {
146+
*state
147+
.agent_avatar_communities
148+
.lock()
149+
.map_err(|e| e.to_string())? = relay_urls;
150+
Ok(())
151+
}
152+
139153
/// Apply a workspace's configuration to the backend session.
140154
///
141155
/// Called by the frontend on app init (after reload) to configure the

‎desktop/src-tauri/src/egress_guard_tests.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@ const EVENTS_INVENTORY: &[(&str, usize, usize)] = &[
273273
("src/relay_admission.rs", 1, 0),
274274
("src/native_relay_client_transport_tests.rs", 1, 0),
275275
("src/archive/mod_tests.rs", 1, 0),
276+
("src/relay/profile_avatar/tests.rs", 1, 0),
276277
("src/managed_agents/persona_events/tests.rs", 1, 0),
277278
("src/commands/team_snapshot/tests.rs", 1, 0),
278279
// Mock-relay route in its in-file tests; production publish goes through

‎desktop/src-tauri/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -834,6 +834,7 @@ pub fn run() {
834834
confirm_pairing_sas,
835835
cancel_pairing,
836836
apply_workspace,
837+
set_agent_avatar_communities,
837838
validate_repos_dir,
838839
get_active_workspace,
839840
fetch_workspace_icon,

‎desktop/src-tauri/src/relay.rs‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,8 @@ fn build_profile_event(
535535
.map_err(|e| format!("failed to sign profile event: {e}"))
536536
}
537537

538+
pub(crate) mod profile_avatar;
539+
538540
// ── Managed-agent profile sync ──────────────────────────────────────────────
539541

540542
/// Sync a managed agent's kind:0 profile event to the relay using NIP-98 auth.
@@ -544,6 +546,8 @@ fn build_profile_event(
544546
/// description (see `managed_agents::record_effective_description`); the
545547
/// relay treats kind:0
546548
/// fields as absolute, so passing `None` clears any previously published about.
549+
/// Configured-community avatar media is copied into this target before signing;
550+
/// transfer failure never replaces the existing profile with a foreign URL.
547551
pub async fn sync_managed_agent_profile(
548552
state: &AppState,
549553
relay_url: &str,
@@ -554,8 +558,17 @@ pub async fn sync_managed_agent_profile(
554558
auth_tag: Option<&str>, // NIP-OA auth tag JSON
555559
) -> Result<(), String> {
556560
crate::relay_admission::wait_for_rate_limit().await;
557-
// Build a signed kind:0 profile event (with optional NIP-OA auth tag).
558-
let event = build_profile_event(agent_keys, display_name, avatar_url, about, auth_tag)?;
561+
// Resolve media before replacing the complete profile. A failed transfer
562+
// leaves the previous kind:0 untouched and the saved source available to retry.
563+
let avatar_url =
564+
profile_avatar::localize_avatar(state, relay_url, agent_keys, avatar_url, auth_tag).await?;
565+
let event = build_profile_event(
566+
agent_keys,
567+
display_name,
568+
avatar_url.as_deref(),
569+
about,
570+
auth_tag,
571+
)?;
559572
let event_json = event.as_json();
560573
let body_bytes = event_json.into_bytes();
561574
crate::egress_guard::assert_no_key_backup_bytes(&body_bytes, "agent profile sync")?;
@@ -564,8 +577,9 @@ pub async fn sync_managed_agent_profile(
564577
let auth = build_nip98_auth_header_for_keys(agent_keys, &Method::POST, &url, &body_bytes)?;
565578

566579
let mut request = state
567-
.http_client
580+
.media_fetch_client
568581
.post(&url)
582+
.timeout(std::time::Duration::from_secs(30))
569583
.header("Authorization", auth)
570584
.header("Content-Type", "application/json");
571585
if let Some(tag) = auth_tag {
@@ -584,6 +598,10 @@ pub async fn sync_managed_agent_profile(
584598
));
585599
}
586600

601+
let result: SubmitEventResponse = parse_json_response(response).await?;
602+
if !result.accepted {
603+
return Err(format!("relay rejected agent profile: {}", result.message));
604+
}
587605
Ok(())
588606
}
589607

0 commit comments

Comments
 (0)