mirror of
https://github.com/block/buzz.git
synced 2026-11-25 18:52:52 +00:00
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 <pfleger.will@gmail.com> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
//! Mock-app fixture for the admission tests at the production spawn sites.
|
||||
//! Its agent has no private key, so a start that passes admission reaches
|
||||
//! `spawn_agent_child` and stops at the key refusal there — no process runs.
|
||||
//! The keyring is swapped for keyring's in-memory mock, which holds no keys,
|
||||
//! so the test never touches (or prompts for) the system keychain.
|
||||
|
||||
use super::{save_managed_agents, ManagedAgentRecord, RELAY_REMOVED_ERROR};
|
||||
use tauri::test::MockRuntime;
|
||||
|
||||
pub const RELAY: &str = "wss://removed.example";
|
||||
|
||||
pub struct TestApp {
|
||||
pub app: tauri::App<MockRuntime>,
|
||||
pub pubkey: String,
|
||||
_data: tempfile::TempDir,
|
||||
}
|
||||
|
||||
/// A mock app whose store holds one keyless local agent that starts on launch.
|
||||
pub fn app_with_keyless_agent() -> TestApp {
|
||||
#[cfg(feature = "system-keyring")]
|
||||
keyring::set_default_credential_builder(keyring::mock::default_credential_builder());
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
let mut context = tauri::test::mock_context(tauri::test::noop_assets());
|
||||
// An absolute identifier replaces the app data base dir.
|
||||
context.config_mut().identifier = data.path().to_str().unwrap().to_owned();
|
||||
let state = crate::app_state::build_app_state();
|
||||
*state.relay_url_override.lock().unwrap() = Some(RELAY.into());
|
||||
let app = tauri::test::mock_builder()
|
||||
.manage(state)
|
||||
.build(context)
|
||||
.unwrap();
|
||||
let pubkey = nostr::Keys::generate().public_key().to_hex();
|
||||
let record: ManagedAgentRecord = serde_json::from_value(serde_json::json!({
|
||||
"pubkey": pubkey, "name": "Admission Test Agent", "relay_url": RELAY,
|
||||
"acp_command": "", "agent_command": "", "agent_args": [], "mcp_command": "",
|
||||
"turn_timeout_seconds": 0, "system_prompt": null,
|
||||
"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z",
|
||||
"last_started_at": null, "last_stopped_at": null, "last_exit_code": null,
|
||||
"last_error": null, "start_on_app_launch": true
|
||||
}))
|
||||
.unwrap();
|
||||
save_managed_agents(app.handle(), &[record]).unwrap();
|
||||
TestApp {
|
||||
app,
|
||||
pubkey,
|
||||
_data: data,
|
||||
}
|
||||
}
|
||||
|
||||
/// A start error from the admission check rather than from spawning.
|
||||
pub fn refused(error: &str) -> bool {
|
||||
error == RELAY_REMOVED_ERROR
|
||||
}
|
||||
|
||||
/// A start error from `spawn_agent_child`'s key refusal: admission passed.
|
||||
pub fn reached_spawn(error: &str) -> bool {
|
||||
error.contains("has no private key available")
|
||||
}
|
||||
@@ -10,6 +10,8 @@ pub(crate) use agent_env::{
|
||||
};
|
||||
mod agent_description;
|
||||
pub(crate) use agent_description::{effective_agent_description, record_effective_description};
|
||||
#[cfg(all(test, not(target_os = "windows")))]
|
||||
pub(crate) mod admission_test_support;
|
||||
mod backend;
|
||||
pub(crate) mod bestie_assignment;
|
||||
pub(crate) mod claude_config;
|
||||
@@ -23,6 +25,7 @@ pub(crate) mod git_bash;
|
||||
pub(crate) mod global_config;
|
||||
mod managed_node_paths;
|
||||
mod nest;
|
||||
mod pair_admission;
|
||||
pub(crate) mod parallelism;
|
||||
mod persona_avatars;
|
||||
pub(crate) mod persona_events;
|
||||
@@ -88,6 +91,7 @@ pub(crate) use global_config::{
|
||||
};
|
||||
pub(crate) use managed_node_paths::*;
|
||||
pub use nest::*;
|
||||
pub use pair_admission::*;
|
||||
pub use parallelism::{acp_agents_value, effective_parallelism, harness_max_parallelism};
|
||||
pub use personas::*;
|
||||
#[cfg(windows)]
|
||||
|
||||
201
desktop/src-tauri/src/managed_agents/pair_admission.rs
Normal file
201
desktop/src-tauri/src/managed_agents/pair_admission.rs
Normal file
@@ -0,0 +1,201 @@
|
||||
//! Per-relay admission for local agent pairs.
|
||||
//!
|
||||
//! Removing a community from this device stops every local pair on its relay,
|
||||
//! but a start already in flight can await (mesh preflight, a restart's stop
|
||||
//! phase), let that stop sweep finish, then resume and connect to the removed
|
||||
//! relay. So every spawn site captures an [`AdmissionSnapshot`] before its
|
||||
//! async work and re-checks it with [`RelayAdmissions::admit`] while holding
|
||||
//! `managed_agent_runtime_transition` — the lock that owns this table — until
|
||||
//! the pair is registered, where a removal's stop sweep will find it.
|
||||
//! `spawn_agent_child` requires the [`Admitted`] proof `admit` returns, so no
|
||||
//! spawn site can skip the check.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::app_state::AppState;
|
||||
|
||||
/// Refusal for a start whose relay was removed from this device. Callers that
|
||||
/// start pairs in the background treat it as a quiet no-op, not a failure.
|
||||
pub const RELAY_REMOVED_ERROR: &str = "relay was removed from this device";
|
||||
|
||||
/// Admission state per canonical relay URL (`buzz_core::relay::normalize_relay_url`).
|
||||
#[derive(Default)]
|
||||
pub struct RelayAdmissions(HashMap<String, RelayAdmission>);
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct RelayAdmission {
|
||||
removed: bool,
|
||||
/// Bumped on every removal, so work captured before a removal is never
|
||||
/// admitted again, even after a re-add.
|
||||
epoch: u64,
|
||||
}
|
||||
|
||||
/// Proof that a relay passed [`RelayAdmissions::admit`]. It borrows the table,
|
||||
/// so it cannot outlive the transition lock it was checked under.
|
||||
pub struct Admitted<'a> {
|
||||
relay: String,
|
||||
_table: std::marker::PhantomData<&'a RelayAdmissions>,
|
||||
}
|
||||
|
||||
impl Admitted<'_> {
|
||||
/// Refuses a spawn on any relay other than the one admitted.
|
||||
pub fn covers(&self, relay_url: &str) -> Result<(), String> {
|
||||
if canonical(relay_url)? != self.relay {
|
||||
return Err(format!("{relay_url} was not admitted for this spawn"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Relay epochs captured by a start before its async work.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct AdmissionSnapshot(HashMap<String, u64>);
|
||||
|
||||
fn canonical(relay_url: &str) -> Result<String, String> {
|
||||
buzz_core_pkg::relay::normalize_relay_url(relay_url).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
impl RelayAdmissions {
|
||||
pub fn snapshot(&self) -> AdmissionSnapshot {
|
||||
AdmissionSnapshot(
|
||||
self.0
|
||||
.iter()
|
||||
.map(|(relay, admission)| (relay.clone(), admission.epoch))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Refuse this relay's pairs until it is re-added, and invalidate every
|
||||
/// snapshot taken so far.
|
||||
pub fn remove(&mut self, relay_url: &str) -> Result<(), String> {
|
||||
let admission = self.0.entry(canonical(relay_url)?).or_default();
|
||||
admission.removed = true;
|
||||
admission.epoch += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Admit a removed relay again. Work captured before the removal stays
|
||||
/// refused: its epoch is older.
|
||||
pub fn readd(&mut self, relay_url: &str) -> Result<(), String> {
|
||||
if let Some(admission) = self.0.get_mut(&canonical(relay_url)?) {
|
||||
admission.removed = false;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `Err(RELAY_REMOVED_ERROR)` if the relay is removed, or was removed
|
||||
/// after `snapshot` was captured.
|
||||
pub fn admit(
|
||||
&self,
|
||||
snapshot: &AdmissionSnapshot,
|
||||
relay_url: &str,
|
||||
) -> Result<Admitted<'_>, String> {
|
||||
let relay = canonical(relay_url)?;
|
||||
let current = self.0.get(&relay).copied().unwrap_or_default();
|
||||
let captured = snapshot.0.get(&relay).copied().unwrap_or_default();
|
||||
if current.removed || current.epoch != captured {
|
||||
return Err(RELAY_REMOVED_ERROR.into());
|
||||
}
|
||||
Ok(Admitted {
|
||||
relay,
|
||||
_table: std::marker::PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AdmissionSnapshot {
|
||||
/// Capture before any async work. Takes the transition lock briefly, so
|
||||
/// never call it while holding that lock. A poisoned lock still yields
|
||||
/// the table: capture must not be the reason a start skips its refusal.
|
||||
pub fn capture(state: &AppState) -> Self {
|
||||
state
|
||||
.managed_agent_runtime_transition
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.snapshot()
|
||||
}
|
||||
}
|
||||
|
||||
/// Record that a community's relay was removed from this device. The caller
|
||||
/// applies the shared-relay guard: only when no other saved community uses it.
|
||||
/// Runs under the transition lock, so a start that already passed admission
|
||||
/// has registered its pair before this returns and the caller's stop sweep
|
||||
/// finds it.
|
||||
pub fn remove_relay(state: &AppState, relay_url: &str) -> Result<(), String> {
|
||||
state
|
||||
.managed_agent_runtime_transition
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?
|
||||
.remove(relay_url)
|
||||
}
|
||||
|
||||
/// Record that a saved community on this relay was explicitly added again.
|
||||
pub fn readd_relay(state: &AppState, relay_url: &str) -> Result<(), String> {
|
||||
state
|
||||
.managed_agent_runtime_transition
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?
|
||||
.readd(relay_url)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{AdmissionSnapshot, RelayAdmissions, RELAY_REMOVED_ERROR};
|
||||
|
||||
const RELAY: &str = "wss://relay.example";
|
||||
|
||||
fn refusal(
|
||||
admissions: &RelayAdmissions,
|
||||
snapshot: &AdmissionSnapshot,
|
||||
relay: &str,
|
||||
) -> Result<(), String> {
|
||||
admissions.admit(snapshot, relay).map(|_| ())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_covers_only_its_own_relay() {
|
||||
let admissions = RelayAdmissions::default();
|
||||
let admitted = admissions.admit(&admissions.snapshot(), RELAY).unwrap();
|
||||
assert_eq!(admitted.covers("WSS://relay.example/"), Ok(()));
|
||||
assert!(admitted.covers("wss://other.example").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removal_refuses_captured_and_fresh_work_until_readded() {
|
||||
let mut admissions = RelayAdmissions::default();
|
||||
let before = admissions.snapshot();
|
||||
admissions.remove("WSS://Relay.Example/").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
refusal(&admissions, &before, RELAY),
|
||||
Err(RELAY_REMOVED_ERROR.into())
|
||||
);
|
||||
assert_eq!(
|
||||
refusal(&admissions, &admissions.snapshot(), RELAY),
|
||||
Err(RELAY_REMOVED_ERROR.into())
|
||||
);
|
||||
admissions.readd(RELAY).unwrap();
|
||||
assert_eq!(refusal(&admissions, &admissions.snapshot(), RELAY), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_captured_before_a_removal_stays_refused_after_readd() {
|
||||
let mut admissions = RelayAdmissions::default();
|
||||
let before_removal = admissions.snapshot();
|
||||
admissions.remove(RELAY).unwrap();
|
||||
admissions.readd(RELAY).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
refusal(&admissions, &before_removal, RELAY),
|
||||
Err(RELAY_REMOVED_ERROR.into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removal_leaves_other_relays_admitted() {
|
||||
let mut admissions = RelayAdmissions::default();
|
||||
let before = admissions.snapshot();
|
||||
admissions.remove(RELAY).unwrap();
|
||||
assert_eq!(refusal(&admissions, &before, "wss://other.example"), Ok(()));
|
||||
}
|
||||
}
|
||||
@@ -86,21 +86,72 @@ pub fn backfill_persona_snapshots(app: &tauri::AppHandle) -> Result<(), String>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Schedule launch restore: captures admission now, at scheduling, and
|
||||
/// returns the deferred restore that runs under that snapshot. A community
|
||||
/// removed after this call refuses the restore even if it is re-added before
|
||||
/// the task runs. `sweeps` is Phase A's live process sweeps.
|
||||
pub fn launch_restore_task<R, S>(
|
||||
app: tauri::AppHandle<R>,
|
||||
sweeps: S,
|
||||
) -> impl std::future::Future<Output = Result<(), String>>
|
||||
where
|
||||
R: tauri::Runtime,
|
||||
S: FnOnce(&tauri::AppHandle<R>, &[u32]),
|
||||
{
|
||||
let admission = super::AdmissionSnapshot::capture(&app.state::<AppState>());
|
||||
async move {
|
||||
let state = app.state::<AppState>();
|
||||
restore_managed_agents_on_launch(&app, &state.shutdown_started, admission, sweeps).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Phase A's sweeps of live, untracked agent processes, skipping `tracked_pids`.
|
||||
pub fn live_process_sweeps(app: &tauri::AppHandle, tracked_pids: &[u32]) {
|
||||
super::sweep_orphaned_agent_processes(app, tracked_pids);
|
||||
|
||||
// System-wide sweep: enumerate all user processes and kill any known
|
||||
// agent binaries not tracked by this session. Catches orphans whose
|
||||
// PID files were already cleaned up (e.g. agent workers in their own
|
||||
// process group whose parent harness exited).
|
||||
super::sweep_system_agent_processes(&super::current_instance_id(app), tracked_pids);
|
||||
|
||||
// Dead-instance reaping: find agents belonging to Buzz instances
|
||||
// whose desktop process is no longer running and reap them.
|
||||
super::reap_dead_instance_agents(&super::current_instance_id(app), tracked_pids);
|
||||
|
||||
// Exact-path sweep: kill any buzz-acp process whose executable path
|
||||
// matches this bundle's harness binary but is not in the tracked set.
|
||||
// Complements the env-var sweep above — catches orphans that predate
|
||||
// BUZZ_MANAGED_AGENT injection or lost their PID-file receipt.
|
||||
//
|
||||
// TODO: the three sweeps above each walk the PID table independently.
|
||||
// A future consolidation should collect a single shared process snapshot
|
||||
// at the top of this block and thread it through all sweep functions,
|
||||
// replacing the three separate kernel enumerations.
|
||||
super::sweep_untracked_bundle_harnesses(tracked_pids);
|
||||
}
|
||||
|
||||
/// Restore managed agents that were running before the app was closed.
|
||||
///
|
||||
/// Split into three phases to minimise lock contention with the frontend:
|
||||
/// A (under lock): sync process state, cleanup, collect agents to start
|
||||
/// B (no locks): resolve commands and spawn processes in parallel
|
||||
/// C (re-lock): write back PIDs and status to records on disk
|
||||
pub async fn restore_managed_agents_on_launch(
|
||||
app: &tauri::AppHandle,
|
||||
async fn restore_managed_agents_on_launch<R: tauri::Runtime>(
|
||||
app: &tauri::AppHandle<R>,
|
||||
shutdown_started: &AtomicBool,
|
||||
admission: super::AdmissionSnapshot,
|
||||
sweeps: impl FnOnce(&tauri::AppHandle<R>, &[u32]),
|
||||
) -> Result<(), String> {
|
||||
if shutdown_started.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let state = app.state::<AppState>();
|
||||
// `apply_workspace` still holds the apply lock for this task, so the relay
|
||||
// cannot change underneath it; pin it for the spawn loop.
|
||||
let restore_relay = crate::relay::relay_ws_url_with_override(&state);
|
||||
let restore_relay = restore_relay.as_str();
|
||||
|
||||
// ── Phase A (under lock): housekeeping + collect agents to restore ──
|
||||
let mut agents_to_start: Vec<super::ManagedAgentRecord>;
|
||||
@@ -148,28 +199,7 @@ pub async fn restore_managed_agents_on_launch(
|
||||
}),
|
||||
)
|
||||
.collect();
|
||||
super::sweep_orphaned_agent_processes(app, &tracked_pids);
|
||||
|
||||
// System-wide sweep: enumerate all user processes and kill any known
|
||||
// agent binaries not tracked by this session. Catches orphans whose
|
||||
// PID files were already cleaned up (e.g. agent workers in their own
|
||||
// process group whose parent harness exited).
|
||||
super::sweep_system_agent_processes(&super::current_instance_id(app), &tracked_pids);
|
||||
|
||||
// Dead-instance reaping: find agents belonging to Buzz instances
|
||||
// whose desktop process is no longer running and reap them.
|
||||
super::reap_dead_instance_agents(&super::current_instance_id(app), &tracked_pids);
|
||||
|
||||
// Exact-path sweep: kill any buzz-acp process whose executable path
|
||||
// matches this bundle's harness binary but is not in the tracked set.
|
||||
// Complements the env-var sweep above — catches orphans that predate
|
||||
// BUZZ_MANAGED_AGENT injection or lost their PID-file receipt.
|
||||
//
|
||||
// TODO: the three sweeps above each walk the PID table independently.
|
||||
// A future consolidation should collect a single shared process snapshot
|
||||
// at the top of this block and thread it through all sweep functions,
|
||||
// replacing the three separate kernel enumerations.
|
||||
super::sweep_untracked_bundle_harnesses(&tracked_pids);
|
||||
sweeps(app, &tracked_pids);
|
||||
|
||||
let candidates: Vec<String> = records
|
||||
.iter()
|
||||
@@ -282,91 +312,139 @@ pub async fn restore_managed_agents_on_launch(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let reconcile_items = spawn_and_register_restored_agents(
|
||||
app,
|
||||
shutdown_started,
|
||||
&admission,
|
||||
restore_relay,
|
||||
&agents_to_start,
|
||||
owner_hex.as_deref(),
|
||||
)?;
|
||||
|
||||
// ── Profile reconciliation (fire-and-forget) ────────────────────────────
|
||||
// Spawn background tasks to ensure each restored agent's kind:0 profile is
|
||||
// published on the relay. Same pattern as the UI start path.
|
||||
for (pubkey, data) in reconcile_items {
|
||||
let reconcile_app = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let state = reconcile_app.state::<AppState>();
|
||||
if let Err(e) =
|
||||
crate::commands::reconcile_agent_profile(&state, &reconcile_app, &pubkey, &data)
|
||||
.await
|
||||
{
|
||||
eprintln!("buzz-desktop: profile reconciliation failed for agent {pubkey}: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Phases B and C of launch restore: spawn `agents_to_start` on `restore_relay`
|
||||
/// if it is still admitted under the snapshot `apply_workspace` scheduled the
|
||||
/// restore with, then register them. Split from the sweeps above so tests can
|
||||
/// drive the real admission and registration without sweeping live processes.
|
||||
/// Returns the profile reconciliations to run for the agents it registered.
|
||||
fn spawn_and_register_restored_agents<R: tauri::Runtime>(
|
||||
app: &tauri::AppHandle<R>,
|
||||
shutdown_started: &AtomicBool,
|
||||
admission: &super::AdmissionSnapshot,
|
||||
restore_relay: &str,
|
||||
agents_to_start: &[super::ManagedAgentRecord],
|
||||
owner_hex: Option<&str>,
|
||||
) -> Result<Vec<(String, crate::commands::ProfileReconcileData)>, String> {
|
||||
let state = app.state::<AppState>();
|
||||
// Serialize spawning and runtime registration with shutdown cleanup. The
|
||||
// shutdown flag is rechecked after taking the lock so shutdown either
|
||||
// prevents this transition or waits until every child is tracked and can
|
||||
// be terminated.
|
||||
let restore_transition = state
|
||||
.managed_agent_runtime_transition
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?;
|
||||
if shutdown_started.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// ── Phase B (transition lock held): resolve commands and spawn in parallel ──
|
||||
let spawn_results: Vec<AgentSpawnResult> = std::thread::scope(|scope| {
|
||||
let owner_hex_ref = owner_hex.as_deref();
|
||||
let handles: Vec<_> = agents_to_start
|
||||
.iter()
|
||||
.filter(|_| !shutdown_started.load(Ordering::SeqCst))
|
||||
.map(|record| {
|
||||
let handle = scope.spawn(move || {
|
||||
let workspace_relay =
|
||||
crate::relay::relay_ws_url_with_override(&app.state::<AppState>());
|
||||
let relay_url = crate::relay::effective_agent_relay_url(
|
||||
&record.relay_url,
|
||||
&workspace_relay,
|
||||
);
|
||||
let outcome =
|
||||
match super::ManagedAgentRuntimeKey::new(record.pubkey.clone(), &relay_url)
|
||||
{
|
||||
Ok(key) => {
|
||||
// F2: if a concurrent startup reconcile already
|
||||
// tracked a live child for this exact pair during
|
||||
// the Phase A window, leave it alone. Mirrors the
|
||||
// live-child guard in `start_pair`.
|
||||
let already_live = app
|
||||
.state::<AppState>()
|
||||
.managed_agent_processes
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut runtimes| {
|
||||
runtimes.get_mut(&key).map(|runtime| {
|
||||
runtime.child.try_wait().ok().flatten().is_none()
|
||||
let spawned = spawn_if_admitted(
|
||||
&state,
|
||||
shutdown_started,
|
||||
admission,
|
||||
restore_relay,
|
||||
|admitted| {
|
||||
std::thread::scope(|scope| {
|
||||
let owner_hex_ref = owner_hex;
|
||||
let handles: Vec<_> = agents_to_start
|
||||
.iter()
|
||||
.filter(|_| !shutdown_started.load(Ordering::SeqCst))
|
||||
.map(|record| {
|
||||
let handle = scope.spawn(move || {
|
||||
let relay_url = crate::relay::effective_agent_relay_url(
|
||||
&record.relay_url,
|
||||
restore_relay,
|
||||
);
|
||||
let outcome = match super::ManagedAgentRuntimeKey::new(
|
||||
record.pubkey.clone(),
|
||||
&relay_url,
|
||||
) {
|
||||
Ok(key) => {
|
||||
// F2: if a concurrent startup reconcile already
|
||||
// tracked a live child for this exact pair during
|
||||
// the Phase A window, leave it alone. Mirrors the
|
||||
// live-child guard in `start_pair`.
|
||||
let already_live = app
|
||||
.state::<AppState>()
|
||||
.managed_agent_processes
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut runtimes| {
|
||||
runtimes.get_mut(&key).map(|runtime| {
|
||||
runtime.child.try_wait().ok().flatten().is_none()
|
||||
})
|
||||
})
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if already_live {
|
||||
SpawnOutcome::Skipped
|
||||
} else {
|
||||
match super::terminate_untracked_pair_runtime(app, &key)
|
||||
.and_then(|()| {
|
||||
// F1: restore spawns lazy, matching
|
||||
// reconcile and manual start. Eager on
|
||||
// restore buys nothing — a crashed
|
||||
// mid-turn session is not resumed by an
|
||||
// eager child — and silently reintroduces
|
||||
// N idle brains on every launch.
|
||||
spawn_agent_child(
|
||||
app,
|
||||
record,
|
||||
&key.relay_url,
|
||||
true,
|
||||
owner_hex_ref,
|
||||
None,
|
||||
)
|
||||
}) {
|
||||
Ok(process) => {
|
||||
SpawnOutcome::Spawned(key, Box::new(process))
|
||||
.unwrap_or(false);
|
||||
if already_live {
|
||||
SpawnOutcome::Skipped
|
||||
} else {
|
||||
match super::terminate_untracked_pair_runtime(app, &key)
|
||||
.and_then(|()| {
|
||||
// F1: restore spawns lazy, matching
|
||||
// reconcile and manual start. Eager on
|
||||
// restore buys nothing — a crashed
|
||||
// mid-turn session is not resumed by an
|
||||
// eager child — and silently reintroduces
|
||||
// N idle brains on every launch.
|
||||
spawn_agent_child(
|
||||
app,
|
||||
record,
|
||||
&key.relay_url,
|
||||
admitted,
|
||||
true,
|
||||
owner_hex_ref,
|
||||
None,
|
||||
)
|
||||
}) {
|
||||
Ok(process) => {
|
||||
SpawnOutcome::Spawned(key, Box::new(process))
|
||||
}
|
||||
Err(error) => SpawnOutcome::Failed(error),
|
||||
}
|
||||
Err(error) => SpawnOutcome::Failed(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => SpawnOutcome::Failed(error),
|
||||
};
|
||||
(record.pubkey.clone(), outcome)
|
||||
});
|
||||
handle
|
||||
})
|
||||
.collect();
|
||||
Err(error) => SpawnOutcome::Failed(error),
|
||||
};
|
||||
(record.pubkey.clone(), outcome)
|
||||
});
|
||||
handle
|
||||
})
|
||||
.collect();
|
||||
|
||||
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|h| h.join().unwrap())
|
||||
.collect::<Vec<AgentSpawnResult>>()
|
||||
})
|
||||
},
|
||||
)?;
|
||||
let Some((restore_transition, spawn_results)) = spawned else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
|
||||
if spawn_results.is_empty() {
|
||||
return Ok(());
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// ── Phase C (re-acquire lock): write back PIDs and status to records ──
|
||||
@@ -475,23 +553,7 @@ pub async fn restore_managed_agents_on_launch(
|
||||
drop(_store_guard);
|
||||
drop(restore_transition);
|
||||
|
||||
// ── Profile reconciliation (fire-and-forget) ────────────────────────────
|
||||
// Spawn background tasks to ensure each restored agent's kind:0 profile is
|
||||
// published on the relay. Same pattern as the UI start path.
|
||||
for (pubkey, data) in reconcile_items {
|
||||
let reconcile_app = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let state = reconcile_app.state::<AppState>();
|
||||
if let Err(e) =
|
||||
crate::commands::reconcile_agent_profile(&state, &reconcile_app, &pubkey, &data)
|
||||
.await
|
||||
{
|
||||
eprintln!("buzz-desktop: profile reconciliation failed for agent {pubkey}: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Ok(reconcile_items)
|
||||
}
|
||||
|
||||
fn profile_reconcile_completed(outcome: crate::commands::ProfileReconcileOutcome) -> bool {
|
||||
@@ -546,8 +608,8 @@ pub(crate) fn spawn_pending_profile_reconciliations(app: &tauri::AppHandle, work
|
||||
}
|
||||
|
||||
#[cfg(feature = "mesh-llm")]
|
||||
fn persist_restore_error(
|
||||
app: &tauri::AppHandle,
|
||||
fn persist_restore_error<R: tauri::Runtime>(
|
||||
app: &tauri::AppHandle<R>,
|
||||
state: &AppState,
|
||||
pubkey: &str,
|
||||
error: String,
|
||||
@@ -563,6 +625,36 @@ fn persist_restore_error(
|
||||
save_managed_agents(app, &records)
|
||||
}
|
||||
|
||||
/// Restore's check-then-spawn step. Takes the runtime transition lock and runs
|
||||
/// `spawn` only if shutdown has not started and `restore_relay` is still
|
||||
/// admitted under the snapshot `apply_workspace` captured when it scheduled
|
||||
/// this restore; otherwise spawns nothing and returns `None`. On success the
|
||||
/// lock is returned still held, so the caller registers the spawned children
|
||||
/// before shutdown or a removal's stop sweep can run.
|
||||
fn spawn_if_admitted<'a, T>(
|
||||
state: &'a AppState,
|
||||
shutdown_started: &AtomicBool,
|
||||
admission: &super::AdmissionSnapshot,
|
||||
restore_relay: &str,
|
||||
spawn: impl FnOnce(&super::Admitted<'_>) -> T,
|
||||
) -> Result<Option<(std::sync::MutexGuard<'a, super::RelayAdmissions>, T)>, String> {
|
||||
let transition = state
|
||||
.managed_agent_runtime_transition
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?;
|
||||
if shutdown_started.load(Ordering::SeqCst) {
|
||||
return Ok(None);
|
||||
}
|
||||
let spawned = match transition.admit(admission, restore_relay) {
|
||||
Ok(admitted) => spawn(&admitted),
|
||||
Err(error) => {
|
||||
eprintln!("buzz-desktop: skipping managed agent restore: {error}");
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
Ok(Some((transition, spawned)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod profile_reconcile_tests {
|
||||
use super::profile_reconcile_completed;
|
||||
@@ -578,3 +670,64 @@ mod profile_reconcile_tests {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// `build_app_state()` pulls in native Windows DLLs unavailable on the CI runner.
|
||||
#[cfg(all(test, not(target_os = "windows")))]
|
||||
mod launch_restore_admission_tests {
|
||||
use super::spawn_if_admitted;
|
||||
use crate::app_state::{build_app_state, AppState};
|
||||
use crate::managed_agents::AdmissionSnapshot;
|
||||
use crate::relay::{relay_api_base_url_with_override, relay_ws_url_with_override};
|
||||
use std::cell::Cell;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
const RELAY: &str = "wss://removed.example";
|
||||
|
||||
/// Runs restore's spawn step with `admission` and returns how many times it spawned.
|
||||
fn spawns(state: &AppState, shutdown: &AtomicBool, admission: &AdmissionSnapshot) -> u32 {
|
||||
let count = Cell::new(0);
|
||||
let gate = spawn_if_admitted(state, shutdown, admission, RELAY, |_| {
|
||||
count.set(count.get() + 1)
|
||||
});
|
||||
assert_eq!(gate.unwrap().is_some(), count.get() == 1);
|
||||
count.get()
|
||||
}
|
||||
|
||||
fn remove(state: &AppState) {
|
||||
crate::managed_agents::remove_relay(state, RELAY).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_scheduled_before_a_removal_spawns_nothing_even_after_readd() {
|
||||
let state = build_app_state();
|
||||
let shutdown = AtomicBool::new(false);
|
||||
*state.relay_url_override.lock().unwrap() = Some(RELAY.into());
|
||||
// What `apply_workspace` captures when it schedules the restore.
|
||||
let scheduled = AdmissionSnapshot::capture(&state);
|
||||
|
||||
remove(&state);
|
||||
crate::managed_agents::readd_relay(&state, RELAY).unwrap();
|
||||
|
||||
assert_eq!(spawns(&state, &shutdown, &scheduled), 0);
|
||||
assert_eq!(relay_ws_url_with_override(&state), RELAY);
|
||||
assert_eq!(
|
||||
relay_api_base_url_with_override(&state),
|
||||
"https://removed.example"
|
||||
);
|
||||
// A restore scheduled after the re-add spawns normally.
|
||||
let fresh = AdmissionSnapshot::capture(&state);
|
||||
assert_eq!(spawns(&state, &shutdown, &fresh), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_spawns_nothing_even_when_admitted() {
|
||||
let state = build_app_state();
|
||||
let shutdown = AtomicBool::new(true);
|
||||
let admission = AdmissionSnapshot::capture(&state);
|
||||
assert_eq!(spawns(&state, &shutdown, &admission), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_os = "windows")))]
|
||||
#[path = "restore_admission_tests.rs"]
|
||||
mod admission_entry_tests;
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Launch restore against a removed relay: scheduled through the production
|
||||
//! `launch_restore_task`, run through the real restore wrapper, with only
|
||||
//! Phase A's live process sweeps replaced by an inert stand-in.
|
||||
|
||||
use super::{launch_restore_task, spawn_and_register_restored_agents};
|
||||
use crate::app_state::AppState;
|
||||
use crate::managed_agents::admission_test_support::{
|
||||
app_with_keyless_agent, reached_spawn, TestApp, RELAY,
|
||||
};
|
||||
use crate::managed_agents::{load_managed_agents, readd_relay, remove_relay, AdmissionSnapshot};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use tauri::Manager;
|
||||
|
||||
fn last_error(test: &TestApp) -> Option<String> {
|
||||
load_managed_agents(test.app.handle()).unwrap()[0]
|
||||
.last_error
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Schedules restore, runs `before_run` before the deferred task executes,
|
||||
/// then runs it and returns the agent's recorded start error.
|
||||
async fn schedule_and_restore(before_run: impl FnOnce(&AppState)) -> Option<String> {
|
||||
let test = app_with_keyless_agent();
|
||||
let restore = launch_restore_task(test.app.handle().clone(), |_, _| {});
|
||||
before_run(&test.app.state::<AppState>());
|
||||
restore.await.unwrap();
|
||||
last_error(&test)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restore_scheduled_before_a_remove_and_readd_starts_nothing() {
|
||||
let error = schedule_and_restore(|state| {
|
||||
remove_relay(state, RELAY).unwrap();
|
||||
readd_relay(state, RELAY).unwrap();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restore_scheduled_with_no_removal_reaches_spawn() {
|
||||
let error = schedule_and_restore(|_| {}).await.unwrap();
|
||||
assert!(reached_spawn(&error), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_spawn_phase_refuses_a_stale_snapshot() {
|
||||
let test = app_with_keyless_agent();
|
||||
let state = test.app.state::<AppState>();
|
||||
let app = test.app.handle();
|
||||
let scheduled = AdmissionSnapshot::capture(&state);
|
||||
remove_relay(&state, RELAY).unwrap();
|
||||
readd_relay(&state, RELAY).unwrap();
|
||||
let agents = load_managed_agents(app).unwrap();
|
||||
spawn_and_register_restored_agents(
|
||||
app,
|
||||
&AtomicBool::new(false),
|
||||
&scheduled,
|
||||
RELAY,
|
||||
&agents,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(last_error(&test), None);
|
||||
}
|
||||
@@ -145,8 +145,8 @@ fn persona_drift_state(
|
||||
/// pin is ignored — see `effective_agent_relay_url`). Returns `None` for
|
||||
/// records that cannot form a valid pair key yet (e.g. key-less agents that
|
||||
/// mint keys on first start).
|
||||
pub(crate) fn workspace_pair_key(
|
||||
app: &AppHandle,
|
||||
pub(crate) fn workspace_pair_key<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
record: &ManagedAgentRecord,
|
||||
) -> Option<ManagedAgentRuntimeKey> {
|
||||
let state = app.state::<crate::app_state::AppState>();
|
||||
@@ -170,8 +170,8 @@ pub(crate) fn resolve_workspace_pair_key(
|
||||
ManagedAgentRuntimeKey::new(pubkey.to_string(), &effective_relay).ok()
|
||||
}
|
||||
|
||||
pub fn build_managed_agent_summary(
|
||||
app: &AppHandle,
|
||||
pub fn build_managed_agent_summary<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
record: &ManagedAgentRecord,
|
||||
runtimes: &HashMap<ManagedAgentRuntimeKey, ManagedAgentPairRuntime>,
|
||||
personas: &[crate::managed_agents::types::AgentDefinition],
|
||||
@@ -481,14 +481,16 @@ pub(crate) fn spawn_with_effort_proof(
|
||||
/// publishes the triggering message before this spawn and passes its send
|
||||
/// timestamp here so the harness's first REQ replays past that message no
|
||||
/// matter how long the spawn takes. buzz-acp clamps stale floors to ~15 min.
|
||||
pub fn spawn_agent_child(
|
||||
app: &AppHandle,
|
||||
pub fn spawn_agent_child<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
record: &ManagedAgentRecord,
|
||||
relay_url: &str,
|
||||
admitted: &super::Admitted<'_>,
|
||||
lazy: bool,
|
||||
owner_hex: Option<&str>,
|
||||
replay_floor_unix: Option<u64>,
|
||||
) -> Result<crate::managed_agents::ManagedAgentProcess, String> {
|
||||
admitted.covers(relay_url)?;
|
||||
if let Some(error) = spawn_key_refusal(record) {
|
||||
return Err(error);
|
||||
}
|
||||
@@ -899,12 +901,13 @@ pub fn spawn_agent_child(
|
||||
/// exact workspace-relay read the caller's scope assertion passed on; it never
|
||||
/// re-reads the mutable override (see `relay::scope`). The key comes from
|
||||
/// [`bound_runtime_key`] — the seam the spawn-key regressions exercise.
|
||||
pub fn start_managed_agent_process(
|
||||
app: &AppHandle,
|
||||
pub fn start_managed_agent_process<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
record: &mut ManagedAgentRecord,
|
||||
runtimes: &mut HashMap<ManagedAgentRuntimeKey, ManagedAgentPairRuntime>,
|
||||
owner_hex: Option<&str>,
|
||||
workspace_relay: &crate::relay::ScopedWorkspaceRelay,
|
||||
admitted: &super::Admitted<'_>,
|
||||
replay_floor_unix: Option<u64>,
|
||||
) -> Result<(), String> {
|
||||
let key = bound_runtime_key(record, workspace_relay)?;
|
||||
@@ -929,6 +932,7 @@ pub fn start_managed_agent_process(
|
||||
app,
|
||||
record,
|
||||
&key.relay_url,
|
||||
admitted,
|
||||
false,
|
||||
owner_hex,
|
||||
replay_floor_unix,
|
||||
|
||||
@@ -445,8 +445,8 @@ pub(super) fn terminate_runtime_receipt_with(
|
||||
/// the same pair. The caller must hold the runtime transition lock so receipt
|
||||
/// inspection, termination, spawn, and registration cannot race shutdown or
|
||||
/// another start.
|
||||
pub(crate) fn terminate_untracked_pair_runtime(
|
||||
app: &AppHandle,
|
||||
pub(crate) fn terminate_untracked_pair_runtime<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
key: &ManagedAgentRuntimeKey,
|
||||
) -> Result<(), String> {
|
||||
let instance_id = current_instance_id(app);
|
||||
|
||||
@@ -15,8 +15,8 @@ use crate::app_state::AppState;
|
||||
|
||||
const STATUS_EVENT: &str = "managed-agent-runtime-status";
|
||||
|
||||
fn status_for(
|
||||
app: &AppHandle,
|
||||
fn status_for<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
record: &super::ManagedAgentRecord,
|
||||
key: &ManagedAgentRuntimeKey,
|
||||
runtime: Option<&ManagedAgentPairRuntime>,
|
||||
@@ -44,8 +44,8 @@ struct StatusInputs<'a> {
|
||||
global: &'a super::GlobalAgentConfig,
|
||||
}
|
||||
|
||||
fn status_for_with(
|
||||
app: &AppHandle,
|
||||
fn status_for_with<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
record: &super::ManagedAgentRecord,
|
||||
key: &ManagedAgentRuntimeKey,
|
||||
runtime: Option<&ManagedAgentPairRuntime>,
|
||||
@@ -73,7 +73,7 @@ fn status_for_with(
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_status(app: &AppHandle, status: &ManagedAgentRuntimeStatus) {
|
||||
fn emit_status<R: tauri::Runtime>(app: &AppHandle<R>, status: &ManagedAgentRuntimeStatus) {
|
||||
let _ = app.emit(STATUS_EVENT, status);
|
||||
}
|
||||
|
||||
@@ -227,9 +227,10 @@ pub async fn list_managed_agent_runtimes(
|
||||
pub(crate) fn start_managed_agent_runtime_pair_lazy(
|
||||
pubkey: String,
|
||||
relay_url: String,
|
||||
admission: &super::AdmissionSnapshot,
|
||||
app: AppHandle,
|
||||
) -> Result<ManagedAgentRuntimeStatus, String> {
|
||||
start_pair(pubkey, relay_url, true, None, app)
|
||||
start_pair(pubkey, relay_url, true, None, admission, app)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -238,24 +239,27 @@ pub fn start_managed_agent_runtime(
|
||||
relay_url: String,
|
||||
app: AppHandle,
|
||||
) -> Result<ManagedAgentRuntimeStatus, String> {
|
||||
start_managed_agent_runtime_pair_lazy(pubkey, relay_url, app)
|
||||
let admission = super::AdmissionSnapshot::capture(&app.state::<AppState>());
|
||||
start_managed_agent_runtime_pair_lazy(pubkey, relay_url, &admission, app)
|
||||
}
|
||||
|
||||
fn start_pair(
|
||||
fn start_pair<R: tauri::Runtime>(
|
||||
pubkey: String,
|
||||
relay_url: String,
|
||||
lazy: bool,
|
||||
expected_updated_at: Option<&str>,
|
||||
app: AppHandle,
|
||||
admission: &super::AdmissionSnapshot,
|
||||
app: AppHandle<R>,
|
||||
) -> Result<ManagedAgentRuntimeStatus, String> {
|
||||
let state = app.state::<AppState>();
|
||||
let _transition = state
|
||||
let transition = state
|
||||
.managed_agent_runtime_transition
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if state.shutdown_started.load(Ordering::Acquire) {
|
||||
return Err("desktop shutdown has started".into());
|
||||
}
|
||||
let admitted = transition.admit(admission, &relay_url)?;
|
||||
let _store = state
|
||||
.managed_agents_store_lock
|
||||
.lock()
|
||||
@@ -288,8 +292,15 @@ fn start_pair(
|
||||
.lock()
|
||||
.ok()
|
||||
.map(|keys| keys.public_key().to_hex());
|
||||
let mut process =
|
||||
spawn_agent_child(&app, record, &key.relay_url, lazy, owner.as_deref(), None)?;
|
||||
let mut process = spawn_agent_child(
|
||||
&app,
|
||||
record,
|
||||
&key.relay_url,
|
||||
&admitted,
|
||||
lazy,
|
||||
owner.as_deref(),
|
||||
None,
|
||||
)?;
|
||||
let now = crate::util::now_iso();
|
||||
let receipt = ManagedAgentRuntimeReceipt {
|
||||
key: key.clone(),
|
||||
@@ -320,6 +331,14 @@ pub fn stop_managed_agent_runtime(
|
||||
pubkey: String,
|
||||
relay_url: String,
|
||||
app: AppHandle,
|
||||
) -> Result<ManagedAgentRuntimeStatus, String> {
|
||||
stop_pair(pubkey, relay_url, app)
|
||||
}
|
||||
|
||||
fn stop_pair<R: tauri::Runtime>(
|
||||
pubkey: String,
|
||||
relay_url: String,
|
||||
app: AppHandle<R>,
|
||||
) -> Result<ManagedAgentRuntimeStatus, String> {
|
||||
let state = app.state::<AppState>();
|
||||
let _transition = state
|
||||
@@ -388,8 +407,23 @@ pub fn restart_managed_agent_runtime(
|
||||
relay_url: String,
|
||||
app: AppHandle,
|
||||
) -> Result<ManagedAgentRuntimeStatus, String> {
|
||||
stop_managed_agent_runtime(pubkey.clone(), relay_url.clone(), app.clone())?;
|
||||
start_pair(pubkey, relay_url, true, None, app)
|
||||
let stop_app = app.clone();
|
||||
let (stop_pubkey, stop_relay) = (pubkey.clone(), relay_url.clone());
|
||||
restart_pair(pubkey, relay_url, app, move || {
|
||||
stop_pair(stop_pubkey, stop_relay, stop_app).map(drop)
|
||||
})
|
||||
}
|
||||
|
||||
fn restart_pair<R: tauri::Runtime>(
|
||||
pubkey: String,
|
||||
relay_url: String,
|
||||
app: AppHandle<R>,
|
||||
stop: impl FnOnce() -> Result<(), String>,
|
||||
) -> Result<ManagedAgentRuntimeStatus, String> {
|
||||
// Captured before the stop, so a removal landing between the two refuses the start.
|
||||
let admission = super::AdmissionSnapshot::capture(&app.state::<AppState>());
|
||||
stop()?;
|
||||
start_pair(pubkey, relay_url, true, None, &admission, app)
|
||||
}
|
||||
|
||||
/// Probe whether this agent can operate on `requested_relay_url`.
|
||||
@@ -469,6 +503,8 @@ pub async fn reconcile_managed_agent_runtimes(
|
||||
) -> Result<Vec<ManagedAgentRuntimeStatus>, String> {
|
||||
use futures_util::{stream, StreamExt};
|
||||
|
||||
// Captured before the probes: a community removed while they run is refused.
|
||||
let admission = super::AdmissionSnapshot::capture(&app.state::<AppState>());
|
||||
let records = load_managed_agents(&app)?;
|
||||
let mut jobs = Vec::new();
|
||||
for community in communities {
|
||||
@@ -513,12 +549,15 @@ pub async fn reconcile_managed_agent_runtimes(
|
||||
key.relay_url.clone(),
|
||||
true,
|
||||
Some(&record.updated_at),
|
||||
&admission,
|
||||
app.clone(),
|
||||
) {
|
||||
Ok(mut status) => {
|
||||
status.requested_relay_url = Some(requested);
|
||||
rows.push(status);
|
||||
}
|
||||
// Removed mid-reconcile: nothing to start and nothing to report.
|
||||
Err(error) if error == super::RELAY_REMOVED_ERROR => {}
|
||||
Err(error) => {
|
||||
let mut status = status_for_with(
|
||||
&app,
|
||||
@@ -732,3 +771,7 @@ mod tests {
|
||||
assert!(observer_lifecycle_key(&ready_with_error.pubkey, &ready_with_error).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_os = "windows")))]
|
||||
#[path = "runtime_commands_admission_tests.rs"]
|
||||
mod admission_tests;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! `start_pair` and the native pair restart against a removed relay, driven
|
||||
//! through the production admission check on a mock app.
|
||||
|
||||
use super::{restart_pair, start_pair};
|
||||
use crate::app_state::AppState;
|
||||
use crate::managed_agents::admission_test_support::{
|
||||
app_with_keyless_agent, reached_spawn, refused, RELAY,
|
||||
};
|
||||
use crate::managed_agents::{readd_relay, remove_relay, AdmissionSnapshot};
|
||||
use tauri::Manager;
|
||||
|
||||
fn start(
|
||||
test: &crate::managed_agents::admission_test_support::TestApp,
|
||||
admission: &AdmissionSnapshot,
|
||||
) -> String {
|
||||
start_pair(
|
||||
test.pubkey.clone(),
|
||||
RELAY.into(),
|
||||
true,
|
||||
None,
|
||||
admission,
|
||||
test.app.handle().clone(),
|
||||
)
|
||||
.unwrap_err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_pair_refuses_a_removed_relay_until_readded() {
|
||||
let test = app_with_keyless_agent();
|
||||
let state = test.app.state::<AppState>();
|
||||
let before = AdmissionSnapshot::capture(&state);
|
||||
remove_relay(&state, RELAY).unwrap();
|
||||
assert!(refused(&start(&test, &AdmissionSnapshot::capture(&state))));
|
||||
|
||||
readd_relay(&state, RELAY).unwrap();
|
||||
// Work captured before the removal stays refused after the re-add.
|
||||
assert!(refused(&start(&test, &before)));
|
||||
// Fresh work after the re-add reaches the spawn.
|
||||
assert!(reached_spawn(&start(
|
||||
&test,
|
||||
&AdmissionSnapshot::capture(&state)
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_straddling_a_remove_and_readd_starts_nothing() {
|
||||
let test = app_with_keyless_agent();
|
||||
let app = test.app.handle().clone();
|
||||
let stop_app = app.clone();
|
||||
let error = restart_pair(test.pubkey.clone(), RELAY.into(), app.clone(), move || {
|
||||
let state = stop_app.state::<AppState>();
|
||||
remove_relay(&state, RELAY)?;
|
||||
readd_relay(&state, RELAY)
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(refused(&error), "{error}");
|
||||
|
||||
// A restart that crosses no removal reaches the spawn.
|
||||
let error = restart_pair(test.pubkey.clone(), RELAY.into(), app, || Ok(())).unwrap_err();
|
||||
assert!(reached_spawn(&error), "{error}");
|
||||
}
|
||||
@@ -48,7 +48,7 @@ pub(crate) fn managed_agents_store_path<R: tauri::Runtime>(
|
||||
Ok(managed_agents_base_dir(app)?.join("managed-agents.json"))
|
||||
}
|
||||
|
||||
fn managed_agents_logs_dir(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
fn managed_agents_logs_dir<R: tauri::Runtime>(app: &AppHandle<R>) -> Result<PathBuf, String> {
|
||||
let dir = managed_agents_base_dir(app)?.join("logs");
|
||||
fs::create_dir_all(&dir).map_err(|error| format!("failed to create logs dir: {error}"))?;
|
||||
Ok(dir)
|
||||
@@ -82,14 +82,17 @@ fn is_safe_id_char(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || c == '-' || c == '_'
|
||||
}
|
||||
|
||||
pub fn managed_agent_log_path(app: &AppHandle, pubkey: &str) -> Result<PathBuf, String> {
|
||||
pub fn managed_agent_log_path<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
pubkey: &str,
|
||||
) -> Result<PathBuf, String> {
|
||||
Ok(managed_agents_logs_dir(app)?.join(format!("{pubkey}.log")))
|
||||
}
|
||||
|
||||
/// Pair-scoped log path for a managed runtime. The relay URL never appears in
|
||||
/// the filename; the suffix is a hash of the canonical URL.
|
||||
pub fn managed_agent_runtime_log_path(
|
||||
app: &AppHandle,
|
||||
pub fn managed_agent_runtime_log_path<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
key: &ManagedAgentRuntimeKey,
|
||||
) -> Result<PathBuf, String> {
|
||||
Ok(managed_agents_logs_dir(app)?.join(format!("{}.log", key.runtime_id())))
|
||||
@@ -813,8 +816,8 @@ fn agent_pids_dir<R: tauri::Runtime>(app: &AppHandle<R>) -> Result<PathBuf, Stri
|
||||
/// Persist a pair-scoped runtime receipt atomically. Callers must register the
|
||||
/// process in memory in the same runtime transition; on write failure they must
|
||||
/// terminate the child before releasing that transition.
|
||||
pub fn write_agent_runtime_receipt(
|
||||
app: &AppHandle,
|
||||
pub fn write_agent_runtime_receipt<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
receipt: &ManagedAgentRuntimeReceipt,
|
||||
) -> Result<(), String> {
|
||||
let path = agent_pids_dir(app)?.join(format!("{}.json", receipt.key.runtime_id()));
|
||||
@@ -836,8 +839,8 @@ pub fn remove_agent_runtime_receipt_path(path: &Path) {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
|
||||
pub fn read_all_agent_runtime_receipts(
|
||||
app: &AppHandle,
|
||||
pub fn read_all_agent_runtime_receipts<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
) -> Vec<(PathBuf, ManagedAgentRuntimeReceipt)> {
|
||||
let Ok(dir) = agent_pids_dir(app) else {
|
||||
return Vec::new();
|
||||
|
||||
Reference in New Issue
Block a user