|
| 1 | +use std::sync::atomic::Ordering; |
| 2 | + |
| 3 | +use tauri::{AppHandle, State}; |
| 4 | + |
| 5 | +use crate::{ |
| 6 | + app_state::AppState, |
| 7 | + managed_agents::{ |
| 8 | + bestie_assignment::{ |
| 9 | + assignment_matches, clear_assignment, get_assignment, |
| 10 | + recover_pending_assignment_cleanup, replace_assignment, BestieAssignment, |
| 11 | + }, |
| 12 | + load_managed_agents, managed_agents_base_dir, |
| 13 | + retention::{active_retention_scope, open_retention_db, RetentionScope}, |
| 14 | + BackendKind, ManagedAgentRecord, |
| 15 | + }, |
| 16 | + models::ChannelInfo, |
| 17 | +}; |
| 18 | + |
| 19 | +fn canonical_relay(relay_url: &str) -> Result<String, String> { |
| 20 | + buzz_core_pkg::relay::normalize_relay_url(relay_url).map_err(|error| error.to_string()) |
| 21 | +} |
| 22 | + |
| 23 | +fn assert_expected_scope( |
| 24 | + scope: &RetentionScope, |
| 25 | + expected_relay_url: Option<&str>, |
| 26 | + expected_signer_pubkey: Option<&str>, |
| 27 | +) -> Result<(), String> { |
| 28 | + if let Some(expected) = expected_relay_url { |
| 29 | + if canonical_relay(expected)? != canonical_relay(&scope.relay_url)? { |
| 30 | + return Err("active community changed while resolving Bestie".to_string()); |
| 31 | + } |
| 32 | + } |
| 33 | + if let Some(expected) = expected_signer_pubkey { |
| 34 | + if expected.trim().to_ascii_lowercase() != scope.owner_keys.public_key().to_hex() { |
| 35 | + return Err("active identity changed while resolving Bestie".to_string()); |
| 36 | + } |
| 37 | + } |
| 38 | + Ok(()) |
| 39 | +} |
| 40 | + |
| 41 | +fn validate_agent_pubkey(pubkey: &str) -> Result<String, String> { |
| 42 | + let normalized = pubkey.trim().to_ascii_lowercase(); |
| 43 | + if normalized.len() != 64 |
| 44 | + || !normalized |
| 45 | + .chars() |
| 46 | + .all(|character| character.is_ascii_hexdigit()) |
| 47 | + { |
| 48 | + return Err("Bestie agent pubkey must be 64 hexadecimal characters".to_string()); |
| 49 | + } |
| 50 | + Ok(normalized) |
| 51 | +} |
| 52 | + |
| 53 | +fn require_eligible_local_agent( |
| 54 | + records: &[ManagedAgentRecord], |
| 55 | + pubkey: &str, |
| 56 | +) -> Result<(), String> { |
| 57 | + let record = records |
| 58 | + .iter() |
| 59 | + .find(|record| record.pubkey.eq_ignore_ascii_case(pubkey)) |
| 60 | + .ok_or_else(|| "assigned Bestie agent no longer exists on this device".to_string())?; |
| 61 | + if record.backend != BackendKind::Local { |
| 62 | + return Err("only a local managed agent can be your Bestie".to_string()); |
| 63 | + } |
| 64 | + Ok(()) |
| 65 | +} |
| 66 | + |
| 67 | +fn recover_pending_cleanup(app: &AppHandle, records: &[ManagedAgentRecord]) -> Result<(), String> { |
| 68 | + recover_pending_assignment_cleanup(&managed_agents_base_dir(app)?, |pending_pubkey| { |
| 69 | + records |
| 70 | + .iter() |
| 71 | + .any(|record| record.pubkey.eq_ignore_ascii_case(pending_pubkey)) |
| 72 | + }) |
| 73 | +} |
| 74 | + |
| 75 | +#[tauri::command] |
| 76 | +pub fn get_bestie_assignment( |
| 77 | + expected_relay_url: Option<String>, |
| 78 | + expected_signer_pubkey: Option<String>, |
| 79 | + app: AppHandle, |
| 80 | + state: State<'_, AppState>, |
| 81 | +) -> Result<Option<BestieAssignment>, String> { |
| 82 | + let scope = active_retention_scope(&app, &state)?; |
| 83 | + assert_expected_scope( |
| 84 | + &scope, |
| 85 | + expected_relay_url.as_deref(), |
| 86 | + expected_signer_pubkey.as_deref(), |
| 87 | + )?; |
| 88 | + let _store_guard = state |
| 89 | + .managed_agents_store_lock |
| 90 | + .lock() |
| 91 | + .map_err(|error| error.to_string())?; |
| 92 | + let records = load_managed_agents(&app)?; |
| 93 | + recover_pending_cleanup(&app, &records)?; |
| 94 | + let conn = open_retention_db(&scope.db_path)?; |
| 95 | + get_assignment(&conn) |
| 96 | +} |
| 97 | + |
| 98 | +#[tauri::command] |
| 99 | +pub fn assign_bestie( |
| 100 | + agent_pubkey: String, |
| 101 | + expected_relay_url: Option<String>, |
| 102 | + expected_signer_pubkey: Option<String>, |
| 103 | + app: AppHandle, |
| 104 | + state: State<'_, AppState>, |
| 105 | +) -> Result<BestieAssignment, String> { |
| 106 | + let pubkey = validate_agent_pubkey(&agent_pubkey)?; |
| 107 | + let scope = active_retention_scope(&app, &state)?; |
| 108 | + assert_expected_scope( |
| 109 | + &scope, |
| 110 | + expected_relay_url.as_deref(), |
| 111 | + expected_signer_pubkey.as_deref(), |
| 112 | + )?; |
| 113 | + let _store_guard = state |
| 114 | + .managed_agents_store_lock |
| 115 | + .lock() |
| 116 | + .map_err(|error| error.to_string())?; |
| 117 | + let records = load_managed_agents(&app)?; |
| 118 | + recover_pending_cleanup(&app, &records)?; |
| 119 | + require_eligible_local_agent(&records, &pubkey)?; |
| 120 | + let mut conn = open_retention_db(&scope.db_path)?; |
| 121 | + replace_assignment(&mut conn, &pubkey) |
| 122 | +} |
| 123 | + |
| 124 | +#[tauri::command] |
| 125 | +pub fn clear_bestie_assignment( |
| 126 | + expected_relay_url: Option<String>, |
| 127 | + expected_signer_pubkey: Option<String>, |
| 128 | + app: AppHandle, |
| 129 | + state: State<'_, AppState>, |
| 130 | +) -> Result<(), String> { |
| 131 | + let scope = active_retention_scope(&app, &state)?; |
| 132 | + assert_expected_scope( |
| 133 | + &scope, |
| 134 | + expected_relay_url.as_deref(), |
| 135 | + expected_signer_pubkey.as_deref(), |
| 136 | + )?; |
| 137 | + let _store_guard = state |
| 138 | + .managed_agents_store_lock |
| 139 | + .lock() |
| 140 | + .map_err(|error| error.to_string())?; |
| 141 | + let records = load_managed_agents(&app)?; |
| 142 | + recover_pending_cleanup(&app, &records)?; |
| 143 | + let mut conn = open_retention_db(&scope.db_path)?; |
| 144 | + clear_assignment(&mut conn) |
| 145 | +} |
| 146 | + |
| 147 | +#[tauri::command] |
| 148 | +pub async fn resolve_bestie_conversation( |
| 149 | + expected_relay_url: Option<String>, |
| 150 | + expected_signer_pubkey: Option<String>, |
| 151 | + app: AppHandle, |
| 152 | + state: State<'_, AppState>, |
| 153 | +) -> Result<ChannelInfo, String> { |
| 154 | + let generation = state.workspace_apply_generation.load(Ordering::Acquire); |
| 155 | + let scope = active_retention_scope(&app, &state)?; |
| 156 | + assert_expected_scope( |
| 157 | + &scope, |
| 158 | + expected_relay_url.as_deref(), |
| 159 | + expected_signer_pubkey.as_deref(), |
| 160 | + )?; |
| 161 | + let assignment = { |
| 162 | + let _store_guard = state |
| 163 | + .managed_agents_store_lock |
| 164 | + .lock() |
| 165 | + .map_err(|error| error.to_string())?; |
| 166 | + let records = load_managed_agents(&app)?; |
| 167 | + recover_pending_cleanup(&app, &records)?; |
| 168 | + let conn = open_retention_db(&scope.db_path)?; |
| 169 | + let assignment = get_assignment(&conn)? |
| 170 | + .ok_or_else(|| "choose an agent before opening Bestie".to_string())?; |
| 171 | + require_eligible_local_agent(&records, &assignment.agent_pubkey)?; |
| 172 | + assignment |
| 173 | + }; |
| 174 | + |
| 175 | + let owner_pubkey = scope.owner_keys.public_key().to_hex(); |
| 176 | + let channel = super::dms::open_dm_with_scope( |
| 177 | + vec![assignment.agent_pubkey.clone()], |
| 178 | + Some(&scope.relay_url), |
| 179 | + Some(&owner_pubkey), |
| 180 | + &state, |
| 181 | + ) |
| 182 | + .await?; |
| 183 | + |
| 184 | + if state.workspace_apply_generation.load(Ordering::Acquire) != generation { |
| 185 | + return Err("active workspace changed while resolving Bestie".to_string()); |
| 186 | + } |
| 187 | + let current_scope = active_retention_scope(&app, &state)?; |
| 188 | + assert_expected_scope(¤t_scope, Some(&scope.relay_url), Some(&owner_pubkey))?; |
| 189 | + let conn = open_retention_db(&scope.db_path)?; |
| 190 | + if !assignment_matches(&conn, &assignment.agent_pubkey)? { |
| 191 | + return Err("Bestie assignment changed while opening the conversation".to_string()); |
| 192 | + } |
| 193 | + Ok(channel) |
| 194 | +} |
| 195 | + |
| 196 | +#[cfg(test)] |
| 197 | +mod tests { |
| 198 | + use super::*; |
| 199 | + |
| 200 | + #[test] |
| 201 | + fn relay_scope_accepts_runtime_equivalences() { |
| 202 | + assert_eq!( |
| 203 | + canonical_relay(" WSS://LOCALHOST:443/ ") |
| 204 | + .unwrap_or_else(|error| panic!("canonical relay: {error}")), |
| 205 | + "wss://127.0.0.1" |
| 206 | + ); |
| 207 | + } |
| 208 | + |
| 209 | + #[test] |
| 210 | + fn pubkeys_are_normalized_and_validated() { |
| 211 | + assert_eq!( |
| 212 | + validate_agent_pubkey(&"A".repeat(64)) |
| 213 | + .unwrap_or_else(|error| panic!("valid pubkey: {error}")), |
| 214 | + "a".repeat(64) |
| 215 | + ); |
| 216 | + assert!(validate_agent_pubkey("short").is_err()); |
| 217 | + } |
| 218 | +} |
0 commit comments