Skip to content

Commit 83aab8c

Browse files
wpfleger96Duncan
andauthored
feat(desktop): remove communities locally and stop their agent pairs (#7997)
🤖 Leave contacts the relay before it removes anything locally: it checks the relay's `/info` for NIP-43 membership support, then waits for the relay to accept a signed leave request. When a relay has been torn down, that check fails, Leave throws, and the community stays in the rail. Removing a community also left its relay's managed agent pairs running, and they kept reconnecting to it until the app was quit. **Remove from this device** - A new community action, **Remove from this device**, sits under **Leave community** in the profile menu's community actions. It never contacts the relay. A confirm dialog explains that relay membership isn't revoked. - `useCommunityNavigationTransitions` splits the old `removeCommunity` into `removeCommunityFromDevice` (local-only cleanup and navigation to a fallback community or the discovery screen) and `leaveAndRemoveCommunity` (calls `leaveCommunity`, then runs the same cleanup). Leave's flow hasn't changed. - When Leave fails, the error now adds: "If the community no longer exists, use Remove from this device." The error shown when community discovery state can't be saved no longer says "Membership was removed", so its wording fits both actions. **Agent pairs on a removed relay** - Once the local removal completes, the shared cleanup stops every live agent pair on that relay, including manually started ones. It matches relays with `canonicalRelayUrl`. Stopping is best-effort: failures are logged and the removal still completes. Pairs on other relays aren't touched, and nothing is stopped if another community still uses the same relay. - Both reconcile call sites (`useManagedAgentRuntimeReconciliation` and `bootstrapManagedAgentRuntimePairs`) now go through `reconcileConfiguredManagedAgentRuntimes`. A reconcile that is already running in Rust can't be cancelled, so after it resolves, this helper stops any pair it started whose relay is no longer in the saved community list. - Launch restore runs in the background after `apply_workspace` and can finish after its community is removed. `apply_workspace` takes a restore ticket (the current `launch_restore_generation` in `AppState`) before handing its lock to the restore task. Removing the active community calls the new `invalidate_launch_restore` command, which bumps that generation while holding the runtime transition lock. `restore_managed_agents_on_launch` re-checks its ticket under the same lock and spawns nothing if it changed. If restore takes the lock first, its pairs are registered before invalidation returns, and the removal stop then finds them. Removal never changes `relay_url_override`: the outgoing relay stays applied until the next `apply_workspace`, exactly as on `main`, so in-flight work never falls back to the default relay. Invalidation never takes `workspace_apply_lock`, which restore holds while waiting on the transition lock, so lock order is unchanged. - With no relay applied, backend readers fall back to the default relay, the same state as launch before the first `apply_workspace`. A normal quit and relaunch doesn't bring a pair back on a removed relay: restore targets the applied workspace, and the legacy per-record relay pin is ignored. **Tests** - A `community-rail` e2e case makes the mocked relay's membership check fail, the way an unreachable relay does. It checks that Leave shows the error and keeps the community, and that Remove from this device then removes it, switches to the fallback, stops the agent pair on the removed relay, and leaves the pair on the other relay running. - Unit tests in `managedAgentRelayCleanup.test.mjs` cover relay matching, a stop or listing failure not throwing, and the reconcile fence stopping a pair that started on a relay removed mid-flight. --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent fad4ff6 commit 83aab8c

58 files changed

Lines changed: 2486 additions & 276 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ pub struct AppState {
4646
/// Serializes every managed-runtime transition that changes the protected
4747
/// PID set: spawn/register, adoption, stop, shutdown, and sweep snapshots.
4848
/// Never perform network I/O while holding this lock.
49-
pub managed_agent_runtime_transition: Mutex<()>,
49+
/// Owns the per-relay admission record every local pair spawn re-checks.
50+
pub managed_agent_runtime_transition: Mutex<crate::managed_agents::RelayAdmissions>,
5051
pub managed_agents_store_lock: Mutex<()>,
5152
pub channel_templates_store_lock: Mutex<()>,
5253
pub managed_agent_processes: Mutex<HashMap<ManagedAgentRuntimeKey, ManagedAgentPairRuntime>>,
@@ -222,7 +223,7 @@ pub fn build_app_state() -> AppState {
222223
managed_agent_restore_pending: AtomicBool::new(false),
223224
managed_agent_experiments: crate::managed_agents::ManagedAgentExperimentState::default(),
224225
shutdown_started: AtomicBool::new(false),
225-
managed_agent_runtime_transition: Mutex::new(()),
226+
managed_agent_runtime_transition: Mutex::default(),
226227
identity_mutation: Mutex::new(()),
227228
managed_agents_store_lock: Mutex::new(()),
228229
channel_templates_store_lock: Mutex::new(()),

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,8 @@ async fn restart_single_agent_after_install(
514514
let app_for_stop = app.clone();
515515
let pubkey_owned = pubkey.to_string();
516516
let runtime_id_owned = runtime_id.to_string();
517-
517+
let state = app.state::<AppState>();
518+
let gate = crate::managed_agents::AdmissionSnapshot::capture(&state);
518519
let stop_result = tokio::task::spawn_blocking(move || {
519520
let state = app_for_stop.state::<AppState>();
520521

@@ -610,9 +611,8 @@ async fn restart_single_agent_after_install(
610611
}
611612
};
612613

613-
let relay_urls: Vec<_> = runtime_keys.into_iter().map(|key| key.relay_url).collect();
614-
let state = app.state::<AppState>();
615-
match super::agents::start_local_agent_pairs_with_preflight(app, &state, pubkey, &relay_urls)
614+
let urls: Vec<_> = runtime_keys.into_iter().map(|key| key.relay_url).collect();
615+
match super::agents::start_local_agent_pairs_with_preflight(app, &state, pubkey, &urls, &gate)
616616
.await
617617
{
618618
Ok(_) => {

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,9 @@ pub async fn update_managed_agent(
145145
app: AppHandle,
146146
state: State<'_, AppState>,
147147
) -> Result<UpdateManagedAgentResponse, String> {
148+
// Captured before Phase 1 stops the runtime for an access-policy change: a
149+
// community removed while this update runs refuses the restart.
150+
let admission = crate::managed_agents::AdmissionSnapshot::capture(&state);
148151
// Phase 1: local save (synchronous, under lock)
149152
let (mut summary, sync_params, rollback, access_policy_changed, access_restart_relays) = {
150153
let _store_guard = state
@@ -430,6 +433,7 @@ pub async fn update_managed_agent(
430433
&state,
431434
&summary.pubkey,
432435
&access_restart_relays,
436+
&admission,
433437
)
434438
.await
435439
{
@@ -456,6 +460,7 @@ pub async fn update_managed_agent(
456460
&state,
457461
&summary.pubkey,
458462
&access_restart_relays,
463+
&admission,
459464
)
460465
.await
461466
.map_err(|error| {

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

Lines changed: 62 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -59,28 +59,32 @@ mod create_fields;
5959
use create_fields::{normalize_relay_mesh, resolve_created_avatar_url, trim_to_optional_string};
6060

6161
#[cfg(feature = "mesh-llm")]
62-
async fn ensure_relay_mesh_for_record(
63-
app: &AppHandle,
62+
async fn ensure_relay_mesh_for_record<R: tauri::Runtime>(
63+
app: &AppHandle<R>,
6464
model_id: Option<&str>,
6565
allow_fresh_create_start: bool,
6666
) -> Result<(), String> {
6767
crate::commands::ensure_relay_mesh_for_record(app, model_id, allow_fresh_create_start).await
6868
}
6969

7070
#[cfg(not(feature = "mesh-llm"))]
71-
async fn ensure_relay_mesh_for_record(
72-
_app: &AppHandle,
71+
async fn ensure_relay_mesh_for_record<R: tauri::Runtime>(
72+
_app: &AppHandle<R>,
7373
_model_id: Option<&str>,
7474
_allow_fresh_create_start: bool,
7575
) -> Result<(), String> {
7676
Ok(())
7777
}
7878

79+
/// Start `pubkey`'s pairs on `relay_urls`. Restart flows capture `admission`
80+
/// before they stop the pairs, so a community removed while the restart runs
81+
/// refuses its start; those relays are skipped quietly.
7982
pub(super) async fn start_local_agent_pairs_with_preflight(
8083
app: &AppHandle,
8184
state: &AppState,
8285
pubkey: &str,
8386
relay_urls: &[String],
87+
admission: &crate::managed_agents::AdmissionSnapshot,
8488
) -> Result<ManagedAgentSummary, String> {
8589
let record_snapshot = {
8690
let _store_guard = state
@@ -131,9 +135,13 @@ pub(super) async fn start_local_agent_pairs_with_preflight(
131135
if let Err(error) = crate::managed_agents::start_managed_agent_runtime_pair_lazy(
132136
pubkey.to_string(),
133137
relay_url.clone(),
138+
admission,
134139
app.clone(),
135140
) {
136-
errors.push(format!("{relay_url}: {error}"));
141+
// A relay removed since `admission` was captured has nothing to restart.
142+
if error != crate::managed_agents::RELAY_REMOVED_ERROR {
143+
errors.push(format!("{relay_url}: {error}"));
144+
}
137145
}
138146
}
139147
if !errors.is_empty() {
@@ -159,15 +167,49 @@ pub(super) async fn start_local_agent_pairs_with_preflight(
159167
summarize_from_disk(app, record, &runtimes)
160168
}
161169

162-
pub(super) async fn start_local_agent_with_preflight(
163-
app: &AppHandle,
170+
pub(super) async fn start_local_agent_with_preflight<R: tauri::Runtime>(
171+
app: &AppHandle<R>,
164172
state: &AppState,
165173
pubkey: &str,
166174
allow_fresh_create_start: bool,
167175
expected_relay_url: Option<&str>,
168176
expected_signer_pubkey: Option<&str>,
169177
replay_floor_unix: Option<u64>,
170178
) -> Result<ManagedAgentSummary, String> {
179+
start_local_agent_after_preflight(
180+
app,
181+
state,
182+
pubkey,
183+
expected_relay_url,
184+
expected_signer_pubkey,
185+
replay_floor_unix,
186+
|mesh_model_id| async move {
187+
ensure_relay_mesh_for_record(app, mesh_model_id.as_deref(), allow_fresh_create_start)
188+
.await
189+
},
190+
)
191+
.await
192+
}
193+
194+
/// The ordinary start with its one awaited step, mesh preflight, supplied by
195+
/// the caller so tests can hold it open across a removal.
196+
pub(super) async fn start_local_agent_after_preflight<R, P, F>(
197+
app: &AppHandle<R>,
198+
state: &AppState,
199+
pubkey: &str,
200+
expected_relay_url: Option<&str>,
201+
expected_signer_pubkey: Option<&str>,
202+
replay_floor_unix: Option<u64>,
203+
preflight: P,
204+
) -> Result<ManagedAgentSummary, String>
205+
where
206+
R: tauri::Runtime,
207+
P: FnOnce(Option<String>) -> F,
208+
F: std::future::Future<Output = Result<(), String>>,
209+
{
210+
// Captured before mesh preflight: a community removed while it awaits
211+
// refuses this start below.
212+
let admission = crate::managed_agents::AdmissionSnapshot::capture(state);
171213
let record_snapshot = {
172214
let _store_guard = state
173215
.managed_agents_store_lock
@@ -200,7 +242,7 @@ pub(super) async fn start_local_agent_with_preflight(
200242
&personas,
201243
&global,
202244
);
203-
ensure_relay_mesh_for_record(app, mesh_model_id.as_deref(), allow_fresh_create_start).await?;
245+
preflight(mesh_model_id).await?;
204246

205247
// The mesh preflight above is the suspension window Projects callbacks
206248
// capture their scope against: a community switch during that await
@@ -220,6 +262,14 @@ pub(super) async fn start_local_agent_with_preflight(
220262
let workspace_owner =
221263
crate::relay::bind_expected_signer(expected_signer_pubkey, workspace_owner_hex(state)?)?;
222264

265+
// Lock order matches `start_pair`: transition, then store, then runtime
266+
// map. The transition lock is held until the pair is registered, so a
267+
// removal either refuses this start or waits and its stop sweep finds it.
268+
let transition = state
269+
.managed_agent_runtime_transition
270+
.lock()
271+
.map_err(|e| e.to_string())?;
272+
let admitted = transition.admit(&admission, workspace_relay_url.as_str())?;
223273
let _store_guard = state
224274
.managed_agents_store_lock
225275
.lock()
@@ -260,6 +310,7 @@ pub(super) async fn start_local_agent_with_preflight(
260310
&mut runtimes,
261311
Some(workspace_owner.as_str()),
262312
&workspace_relay_url,
313+
&admitted,
263314
replay_floor_unix,
264315
)?;
265316
save_managed_agents(app, &records)?;
@@ -1175,6 +1226,9 @@ pub(crate) use profile::*;
11751226
#[cfg(test)]
11761227
use profile::{profile_needs_sync, resolve_legacy_avatar};
11771228

1229+
#[cfg(all(test, not(target_os = "windows")))]
1230+
#[path = "agents_admission_tests.rs"]
1231+
mod admission_tests;
11781232
#[cfg(test)]
11791233
#[path = "agents_tests.rs"]
11801234
mod tests;
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
//! The ordinary local start against a removed relay, through the production
2+
//! `start_local_agent_with_preflight` on a mock app, and across its preflight
3+
//! await.
4+
5+
use super::{start_local_agent_after_preflight, start_local_agent_with_preflight};
6+
use crate::app_state::AppState;
7+
use crate::managed_agents::admission_test_support::{
8+
app_with_keyless_agent, reached_spawn, refused, RELAY,
9+
};
10+
use crate::managed_agents::{readd_relay, remove_relay};
11+
use tauri::Manager;
12+
13+
#[tokio::test]
14+
async fn ordinary_start_refuses_a_removed_relay_until_readded() {
15+
let test = app_with_keyless_agent();
16+
let (app, state) = (test.app.handle(), test.app.state::<AppState>());
17+
let start =
18+
|| start_local_agent_with_preflight(app, &state, &test.pubkey, false, None, None, None);
19+
20+
remove_relay(&state, RELAY).unwrap();
21+
let error = start().await.unwrap_err();
22+
assert!(refused(&error), "{error}");
23+
24+
readd_relay(&state, RELAY).unwrap();
25+
let error = start().await.unwrap_err();
26+
assert!(reached_spawn(&error), "{error}");
27+
}
28+
29+
/// Runs the ordinary start with its preflight held open while `during` runs.
30+
async fn start_across_preflight(during: impl FnOnce(&AppState)) -> String {
31+
let test = app_with_keyless_agent();
32+
let (app, state) = (test.app.handle(), test.app.state::<AppState>());
33+
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
34+
let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
35+
let start = start_local_agent_after_preflight(
36+
app,
37+
&state,
38+
&test.pubkey,
39+
None,
40+
None,
41+
None,
42+
|_| async move {
43+
entered_tx.send(()).unwrap();
44+
release_rx.await.unwrap();
45+
Ok(())
46+
},
47+
);
48+
let control = async {
49+
entered_rx.await.unwrap();
50+
during(&state);
51+
release_tx.send(()).unwrap();
52+
};
53+
let (result, ()) = tokio::join!(start, control);
54+
result.unwrap_err()
55+
}
56+
57+
#[tokio::test]
58+
async fn ordinary_start_removed_and_readded_during_preflight_is_refused() {
59+
let error = start_across_preflight(|state| {
60+
remove_relay(state, RELAY).unwrap();
61+
readd_relay(state, RELAY).unwrap();
62+
})
63+
.await;
64+
assert!(refused(&error), "{error}");
65+
}
66+
67+
#[tokio::test]
68+
async fn ordinary_start_with_no_removal_during_preflight_reaches_spawn() {
69+
let error = start_across_preflight(|_| {}).await;
70+
assert!(reached_spawn(&error), "{error}");
71+
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ use crate::{app_state::AppState, managed_agents::ManagedAgentRecord};
2222
/// only runtime fields produces an identical row and never re-enqueues a
2323
/// publish. Best-effort: a failure here is logged and swallowed so a retention
2424
/// hiccup never blocks the disk-authoritative write.
25-
pub(crate) fn retain_managed_agent_pending(
26-
app: &AppHandle,
25+
pub(crate) fn retain_managed_agent_pending<R: tauri::Runtime>(
26+
app: &AppHandle<R>,
2727
state: &AppState,
2828
record: &ManagedAgentRecord,
2929
) {

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,9 @@ pub(crate) fn mark_profile_reconciled(
190190
/// keeps deferred reconciliation from following a community switch it was
191191
/// never authorized for while honoring a deliberate per-agent pin wherever
192192
/// it points.
193-
pub(crate) async fn reconcile_agent_profile(
193+
pub(crate) async fn reconcile_agent_profile<R: tauri::Runtime>(
194194
state: &AppState,
195-
app: &AppHandle,
195+
app: &AppHandle<R>,
196196
agent_pubkey: &str,
197197
data: &ProfileReconcileData,
198198
) -> Result<ProfileReconcileOutcome, String> {

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,9 @@ async fn restart_local_agent_on_config_change(
257257
let old_global_clone = old_global.clone();
258258
let new_global_clone = new_global.clone();
259259
let personas_owned = personas_snapshot.to_vec();
260+
use tauri::Manager;
261+
// Captured before the stop: a community removed meanwhile refuses the start.
262+
let admission = crate::managed_agents::AdmissionSnapshot::capture(&app.state::<AppState>());
260263

261264
let stop_result = tokio::task::spawn_blocking(move || {
262265
use tauri::Manager;
@@ -346,10 +349,15 @@ async fn restart_local_agent_on_config_change(
346349
};
347350

348351
let relay_urls: Vec<_> = runtime_keys.into_iter().map(|key| key.relay_url).collect();
349-
use tauri::Manager;
350352
let state = app.state::<AppState>();
351-
match super::agents::start_local_agent_pairs_with_preflight(app, &state, pubkey, &relay_urls)
352-
.await
353+
match super::agents::start_local_agent_pairs_with_preflight(
354+
app,
355+
&state,
356+
pubkey,
357+
&relay_urls,
358+
&admission,
359+
)
360+
.await
353361
{
354362
Ok(_) => {
355363
eprintln!(

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

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,18 @@ fn one_shot_restart_checkpoint(config: &MeshSharingConfig) -> MeshSharingConfig
3737
checkpoint
3838
}
3939

40-
fn mesh_sharing_config_path(app: &AppHandle) -> Result<PathBuf, String> {
40+
fn mesh_sharing_config_path<R: tauri::Runtime>(app: &AppHandle<R>) -> Result<PathBuf, String> {
4141
Ok(app
4242
.path()
4343
.app_data_dir()
4444
.map_err(|error| format!("failed to resolve app data dir: {error}"))?
4545
.join("mesh-sharing.json"))
4646
}
4747

48-
fn save_mesh_sharing_config(app: &AppHandle, config: &MeshSharingConfig) -> Result<(), String> {
48+
fn save_mesh_sharing_config<R: tauri::Runtime>(
49+
app: &AppHandle<R>,
50+
config: &MeshSharingConfig,
51+
) -> Result<(), String> {
4952
let path = mesh_sharing_config_path(app)?;
5053
if let Some(parent) = path.parent() {
5154
std::fs::create_dir_all(parent)
@@ -56,7 +59,9 @@ fn save_mesh_sharing_config(app: &AppHandle, config: &MeshSharingConfig) -> Resu
5659
crate::managed_agents::atomic_write_json(&path, &payload)
5760
}
5861

59-
fn load_mesh_sharing_config(app: &AppHandle) -> Result<Option<MeshSharingConfig>, String> {
62+
fn load_mesh_sharing_config<R: tauri::Runtime>(
63+
app: &AppHandle<R>,
64+
) -> Result<Option<MeshSharingConfig>, String> {
6065
let path = mesh_sharing_config_path(app)?;
6166
match std::fs::read(&path) {
6267
Ok(payload) => serde_json::from_slice(&payload)
@@ -337,7 +342,10 @@ async fn resolve_buzz_mesh_startup_at(
337342
}
338343
}
339344

340-
pub(crate) async fn restore_mesh_sharing(app: &AppHandle, state: &AppState) -> CmdResult<()> {
345+
pub(crate) async fn restore_mesh_sharing<R: tauri::Runtime>(
346+
app: &AppHandle<R>,
347+
state: &AppState,
348+
) -> CmdResult<()> {
341349
let Some(mut config) = load_mesh_sharing_config(app)? else {
342350
return Ok(());
343351
};
@@ -678,8 +686,8 @@ fn pick_serve_target_for_model(
678686
/// a relay query failure ("could not refresh targets") is not the same as a
679687
/// relay that answered with no live target for this model ("peer offline").
680688
/// Non relay-mesh records are a no-op.
681-
pub(crate) async fn ensure_relay_mesh_for_record(
682-
app: &AppHandle,
689+
pub(crate) async fn ensure_relay_mesh_for_record<R: tauri::Runtime>(
690+
app: &AppHandle<R>,
683691
model_id: Option<&str>,
684692
_allow_fresh_create_start: bool,
685693
) -> Result<(), String> {

0 commit comments

Comments
 (0)