From 440899c11bc3499ed11e7a500e78084f53b6ebea Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Fri, 28 Aug 2026 16:08:16 +1000 Subject: [PATCH] feat: reap prewoken agents the draft never used The composer's mention prewake starts a stopped local agent one second into a qualifying draft. Nothing reclaimed it: if the draft was abandoned, the eager harness and its worker subprocesses stayed up -- and showed as online to the whole community -- until app quit, a manual Stop, or a config-change restart. Every existing harness self-reap timer is disabled or inapplicable on the eager spawn path. The prewake should be a pure latency optimization with no lifetime side effects: (prewake + send) must end where (send alone) does, a durable running agent, and (prewake + abandoned draft) must end where (abandoned draft alone) does, a stopped one. Bound the second case in the harness, because only the harness can see turns, heartbeats, and queued work race-free -- any desktop-side "is it idle?" decision has an unavoidable time-of-check/time-of-use race against an in-flight turn it cannot observe, including turns serving a third party who messaged the prewoken agent. buzz-acp gains `--exit-if-unused` / `BUZZ_ACP_EXIT_IF_UNUSED`: exit gracefully if no event has ever been dispatched within N seconds of boot; the first dispatch disarms it permanently. Deliberately not the existing rolling `--exit-after-inactivity` TTL, which would make a prewoken-then-used agent exit 15 minutes after its last turn while a send-started one lives forever -- the same user action producing different lifetimes depending on typing speed. A one-shot boot bound restores exact pre-prewake behavior instead: first real use promotes the agent to a normal durable start, with no promotion RPC. The disarm seam is `dispatch_pending`, which already stamps `last_activity`; both facts now live in one `DispatchActivity` so a future dispatch path cannot stamp the clock and forget the latch. The tick arm reuses the busy gates `idle_pool_sleep_due` codifies -- no turn or heartbeat in flight, no undispatched queued work, no wake/respawn running -- since accepted-but-throttled work means the harness is about to be used and exiting would strand it *before* the dispatch that would have disarmed the bound. Graceful exit is code 0, which `sync_managed_agent_processes` already records as a clean stop, so no desktop-side exit handling is needed. Desktop states the policy at spawn. `lazy: bool` becomes a three-variant `SpawnPolicy` (Durable / Lazy / Speculative) that owns all three lifetime env values: the combinations were never independent -- a lazy speculative pair would defeat the prewake it exists for -- and a second adjacent bool at `spawn_agent_child(.., false, false, ..)` would have been unreadable. `BUZZ_ACP_EXIT_IF_UNUSED` is written on every spawn, inert for deliberate starts, and joins RESERVED_ENV_KEYS so user env cannot strip the bound. `start_managed_agent` takes `speculative`; only the local arm consumes it, since a draft mention must never deploy remote compute. 900s matches IDLE_POOL_SLEEP_SECS -- expiry costs only a cold start, because the preflight re-arms on a resumed draft and the send path has always started a non-running mentioned agent. `managedAgentStartFlightKey` still excludes the flag, now documented: a send arriving while a prewake is in flight should share it, since the send's own dispatch is what promotes the harness. Two files were at the size ceiling and are split along their existing patterns rather than grown: `start_managed_agent_process` moves to `runtime/start.rs` beside its sibling submodules, and the two start-with-preflight entry points to `commands/agents_start.rs` beside `agents_pending.rs` / `agents_deploy.rs` / `agents_profile.rs`. Tests: the bound fires when never dispatched, is disabled at 0, holds before the bound, is disarmed permanently by one dispatch (checked far past the bound), and is deferred by each busy gate; each SpawnPolicy maps to its three env values; the new reserved key is stripped from user env; the prewake's start input carries `speculative: true`; a durable start shares its flight key. buzz-acp 830 unit tests, Tauri 2776, 5688 desktop JS, and 74 mentions E2E specs pass. Signed-off-by: Matt Toohey --- crates/buzz-acp/src/config.rs | 27 ++ crates/buzz-acp/src/lib.rs | 253 ++++++++++++++++- desktop/src-tauri/src/commands/agents.rs | 264 +++--------------- .../src-tauri/src/commands/agents_start.rs | 242 ++++++++++++++++ .../src-tauri/src/managed_agents/agent_env.rs | 106 ++++++- .../src/managed_agents/env_vars/tests.rs | 1 + desktop/src-tauri/src/managed_agents/mod.rs | 1 + .../src/managed_agents/reserved_env_keys.rs | 4 + .../src-tauri/src/managed_agents/restore.rs | 4 +- .../src-tauri/src/managed_agents/runtime.rs | 72 +---- .../src/managed_agents/runtime/start.rs | 81 ++++++ .../src/managed_agents/runtime_commands.rs | 9 +- desktop/src/features/agents/hooks.ts | 2 + .../ui/useMentionWakePreflight.test.mjs | 32 +++ .../messages/ui/useMentionWakePreflight.ts | 10 + .../useSingleFlightManagedAgentStart.test.mjs | 19 ++ .../ui/useSingleFlightManagedAgentStart.ts | 10 + desktop/src/shared/api/tauriManagedAgents.ts | 6 + 18 files changed, 828 insertions(+), 315 deletions(-) create mode 100644 desktop/src-tauri/src/commands/agents_start.rs create mode 100644 desktop/src-tauri/src/managed_agents/runtime/start.rs diff --git a/crates/buzz-acp/src/config.rs b/crates/buzz-acp/src/config.rs index 2d7b212832..ade1f7c8ce 100644 --- a/crates/buzz-acp/src/config.rs +++ b/crates/buzz-acp/src/config.rs @@ -503,6 +503,17 @@ pub struct CliArgs { /// Requires `--lazy-pool`; ignored otherwise. 0 disables idle re-sleep. #[arg(long, env = "BUZZ_ACP_IDLE_POOL_SLEEP", default_value_t = 0)] pub idle_pool_sleep: u64, + + /// Exit gracefully if no event has ever been dispatched within this many + /// seconds of boot. The first dispatch disarms the bound permanently. + /// + /// This is a one-shot boot bound, deliberately not the rolling idle TTL of + /// `--exit-after-inactivity`: it exists for a harness some launcher started + /// speculatively, so that being *used even once* restores exactly the + /// lifetime the harness would have had if it were started deliberately. + /// 0 disables. + #[arg(long, env = "BUZZ_ACP_EXIT_IF_UNUSED", default_value_t = 0)] + pub exit_if_unused: u64, } /// Merged NIP-01 subscription filter for a single channel. @@ -590,6 +601,9 @@ pub struct Config { /// woken lazy pool is torn back down to the empty-slot state. 0 = disabled. /// Only meaningful when `lazy_pool` is true. pub idle_pool_sleep_secs: u64, + /// Seconds from boot before a harness that has *never* dispatched an event + /// exits gracefully. The first dispatch disarms it permanently. 0 = disabled. + pub exit_if_unused_secs: u64, /// Agent owner pubkey (hex). Used for `--respond-to=owner-only` gate. /// Replaces the old REST-based owner lookup. pub agent_owner: Option, @@ -1140,6 +1154,7 @@ impl Config { exit_after_inactivity_secs: args.exit_after_inactivity, lazy_pool: args.lazy_pool, idle_pool_sleep_secs: args.idle_pool_sleep, + exit_if_unused_secs: args.exit_if_unused, agent_owner: args.agent_owner.map(|s| s.trim().to_ascii_lowercase()), no_base_prompt: args.no_base_prompt, base_prompt_content, @@ -1513,6 +1528,7 @@ mod tests { exit_after_inactivity_secs: 0, lazy_pool: false, idle_pool_sleep_secs: 0, + exit_if_unused_secs: 0, agent_owner: None, no_base_prompt: false, base_prompt_content: None, @@ -2249,6 +2265,17 @@ channels = "ALL" assert_eq!(configured.idle_pool_sleep, 300); } + #[test] + fn exit_if_unused_defaults_disabled_and_accepts_cli_value() { + let key = "0".repeat(64); + let default = CliArgs::parse_from(["buzz-acp", "--private-key", &key]); + assert_eq!(default.exit_if_unused, 0); + + let configured = + CliArgs::parse_from(["buzz-acp", "--private-key", &key, "--exit-if-unused", "900"]); + assert_eq!(configured.exit_if_unused, 900); + } + #[test] fn lazy_pool_cli_flag_enables_deferred_startup() { let key = "0".repeat(64); diff --git a/crates/buzz-acp/src/lib.rs b/crates/buzz-acp/src/lib.rs index 25c6e54905..0de820cfe4 100644 --- a/crates/buzz-acp/src/lib.rs +++ b/crates/buzz-acp/src/lib.rs @@ -1650,6 +1650,64 @@ fn inactivity_expired( !bound.is_zero() && !turn_in_flight && now.duration_since(last_activity) >= bound } +/// Activity bookkeeping the dispatch path owns and the lifetime reapers read. +/// +/// The two fields are kept together because they are written at the same seam: +/// `dispatch_pending` stamps the clock and latches the flag whenever it hands a +/// batch to an agent. Putting `ever_dispatched` at the call sites instead would +/// let a future dispatch path forget it and silently leave a used harness +/// eligible for the never-used exit. +struct DispatchActivity { + /// When work was last dispatched. Drives the rolling inactivity TTL and the + /// idle pool re-sleep window. + last: tokio::time::Instant, + /// Whether any event has ever been dispatched since boot. A latch, never + /// cleared: it is the permanent disarm for [`exit_if_unused_due`]. + ever_dispatched: bool, +} + +impl DispatchActivity { + fn new() -> Self { + Self { + last: tokio::time::Instant::now(), + ever_dispatched: false, + } + } +} + +/// Whether a harness that has never been used may exit its one-shot boot bound. +/// +/// This is the reaper for speculatively started harnesses: a desktop that woke +/// an agent ahead of a draft that was then abandoned would otherwise leak the +/// process (and its online presence) until app quit. The bound is measured from +/// boot rather than from the last turn, and `ever_dispatched` disarms it +/// permanently, so a harness that IS used — by its own owner or by anyone else +/// who messages it in the window — keeps the same unbounded lifetime it would +/// have had from a deliberate start. +/// +/// The busy gates mirror [`idle_pool_sleep_due`], for the same race reason: +/// accepted-but-undispatched work (queued, retry-throttled, or awaiting a pool +/// wake) means the harness is about to be used, so exiting would strand it. +#[allow(clippy::too_many_arguments)] +fn exit_if_unused_due( + ever_dispatched: bool, + started_at: tokio::time::Instant, + now: tokio::time::Instant, + bound: Duration, + turn_in_flight: bool, + prompt_tasks_in_flight: bool, + work_queued: bool, + wake_or_respawn_in_flight: bool, +) -> bool { + !bound.is_zero() + && !ever_dispatched + && !turn_in_flight + && !prompt_tasks_in_flight + && !work_queued + && !wake_or_respawn_in_flight + && now.duration_since(started_at) >= bound +} + /// Whether a woken lazy pool may be torn back down to the empty-slot state. /// /// True only when the pool is ready, the idle bound has elapsed with no @@ -1721,6 +1779,114 @@ mod inactivity_tests { } } +#[cfg(test)] +mod exit_if_unused_tests { + use super::*; + + // Never dispatched, bound elapsed, nothing busy or queued. Every case below + // flips exactly one input off this baseline. + fn unused_after_bound() -> (tokio::time::Instant, tokio::time::Instant, Duration) { + let booted = tokio::time::Instant::now(); + ( + booted, + booted + Duration::from_secs(901), + Duration::from_secs(900), + ) + } + + #[test] + fn exits_when_never_dispatched_and_bound_elapsed() { + let (booted, now, bound) = unused_after_bound(); + assert!(exit_if_unused_due( + false, booted, now, bound, false, false, false, false + )); + } + + #[test] + fn zero_bound_disables_the_exit() { + let (booted, now, _) = unused_after_bound(); + assert!(!exit_if_unused_due( + false, + booted, + now, + Duration::ZERO, + false, + false, + false, + false + )); + } + + #[test] + fn before_the_bound_the_harness_stays_up() { + let booted = tokio::time::Instant::now(); + assert!(!exit_if_unused_due( + false, + booted, + booted + Duration::from_secs(899), + Duration::from_secs(900), + false, + false, + false, + false + )); + } + + // The promotion contract: one dispatch makes this a normal durable harness + // forever. Unlike the rolling inactivity TTL, no amount of later quiet + // re-arms it — a prewoken-then-used agent must outlive its bound exactly as + // a send-started one does. + #[test] + fn first_dispatch_disarms_the_bound_permanently() { + let booted = tokio::time::Instant::now(); + for elapsed in [901, 3_600, 86_400] { + assert!( + !exit_if_unused_due( + true, + booted, + booted + Duration::from_secs(elapsed), + Duration::from_secs(900), + false, + false, + false, + false + ), + "a used harness must never exit on the unused bound ({elapsed}s in)" + ); + } + } + + // A harness can be busy without ever having *dispatched*: the pool wake and + // the queue both run ahead of the dispatch seam. Exiting through any of + // these would kill in-flight or accepted work. + #[test] + fn busy_or_queued_work_defers_the_exit() { + let (booted, now, bound) = unused_after_bound(); + for (label, turn, prompt_tasks, queued, wake) in [ + ("turn in flight", true, false, false, false), + ("prompt task in flight", false, true, false, false), + ("undispatched queued work", false, false, true, false), + ("wake or respawn in flight", false, false, false, true), + ] { + assert!( + !exit_if_unused_due(false, booted, now, bound, turn, prompt_tasks, queued, wake), + "{label} must defer the never-used exit" + ); + } + } + + // The dispatch seam is shared with the inactivity clock so a new dispatch + // path cannot stamp one and forget the other. + #[test] + fn dispatch_activity_starts_unused_and_latches() { + let mut activity = DispatchActivity::new(); + assert!(!activity.ever_dispatched); + activity.last = tokio::time::Instant::now(); + activity.ever_dispatched = true; + assert!(activity.ever_dispatched); + } +} + #[cfg(test)] mod idle_pool_sleep_tests { use super::*; @@ -2269,7 +2435,7 @@ async fn tokio_main() -> Result<()> { // self-terminate. The watch interval is capped so small configured bounds // remain reasonably precise without waking long-lived agents frequently. let inactivity_bound = Duration::from_secs(config.exit_after_inactivity_secs); - let mut last_activity = tokio::time::Instant::now(); + let mut activity = DispatchActivity::new(); let mut inactivity_reaper = if inactivity_bound.is_zero() { None } else { @@ -2301,6 +2467,24 @@ async fn tokio_main() -> Result<()> { )) }; + // Never-used exit: bound a harness that some launcher started + // speculatively (the desktop composer wakes a mentioned agent while its + // draft is still being typed) so an abandoned draft cannot leak a live + // process and an online presence indefinitely. Measured from boot and + // disarmed permanently by the first dispatch, unlike the rolling + // `inactivity_bound` above — see `exit_if_unused_due`. + let exit_if_unused_bound = Duration::from_secs(config.exit_if_unused_secs); + let booted_at = tokio::time::Instant::now(); + let mut exit_if_unused_reaper = if exit_if_unused_bound.is_zero() { + None + } else { + let interval = exit_if_unused_bound.min(Duration::from_secs(30)); + Some(tokio::time::interval_at( + tokio::time::Instant::now() + interval, + interval, + )) + }; + // Runs at the TOP of every loop iteration via Instant check — cannot be // starved by the biased select. Slot refill spawns background tasks so // spawn_and_init never blocks the main loop. @@ -2475,7 +2659,7 @@ async fn tokio_main() -> Result<()> { // arrive when the channel is silent. if queue.has_flushable_work() { for (channel_id, thread_tags) in - dispatch_pending(&mut pool, &mut queue, &ctx, &mut last_activity) + dispatch_pending(&mut pool, &mut queue, &ctx, &mut activity) { typing_channels.insert(channel_id, thread_tags); } @@ -2527,7 +2711,7 @@ async fn tokio_main() -> Result<()> { // next relay event arrives — which can be minutes on quiet channels. if respawn_collected { for (channel_id, thread_tags) in - dispatch_pending(&mut pool, &mut queue, &ctx, &mut last_activity) + dispatch_pending(&mut pool, &mut queue, &ctx, &mut activity) { typing_channels.insert(channel_id, thread_tags); } @@ -2983,7 +3167,7 @@ async fn tokio_main() -> Result<()> { } if pool_ready { for (channel_id, thread_tags) in - dispatch_pending(&mut pool, &mut queue, &ctx, &mut last_activity) + dispatch_pending(&mut pool, &mut queue, &ctx, &mut activity) { typing_channels.insert(channel_id, thread_tags); } @@ -3008,7 +3192,7 @@ async fn tokio_main() -> Result<()> { } => { let _ = result_rx; if inactivity_expired( - last_activity, + activity.last, tokio::time::Instant::now(), inactivity_bound, queue.has_in_flight() || heartbeat_in_flight, @@ -3021,6 +3205,37 @@ async fn tokio_main() -> Result<()> { } None } + _ = async { + match exit_if_unused_reaper.as_mut() { + Some(timer) => timer.tick().await, + None => std::future::pending().await, + } + } => { + let _ = result_rx; // end split borrow before touching pool + // Same busy gates as the idle re-sleep arm below, for the + // same reason: a queued-but-undispatched batch means work + // was accepted and is about to run, so exiting here would + // strand it — and would do so *before* the dispatch that + // disarms this bound could ever happen. + if exit_if_unused_due( + activity.ever_dispatched, + booted_at, + tokio::time::Instant::now(), + exit_if_unused_bound, + queue.has_in_flight() || heartbeat_in_flight, + !pool.join_set.is_empty(), + queue.has_undispatched_work(), + !wake_tasks.is_empty() + || any_respawn_in_flight(&crash_history), + ) { + tracing::info!( + exit_if_unused_seconds = config.exit_if_unused_secs, + "never-used bound reached — exiting gracefully" + ); + let _ = shutdown_tx.send(()); + } + None + } _ = async { match idle_pool_sleep_reaper.as_mut() { Some(timer) => timer.tick().await, @@ -3037,7 +3252,7 @@ async fn tokio_main() -> Result<()> { // next iteration dispatches or re-wakes it. if idle_pool_sleep_due( pool_ready, - last_activity, + activity.last, tokio::time::Instant::now(), idle_pool_sleep_bound, queue.has_in_flight() || heartbeat_in_flight, @@ -3059,7 +3274,11 @@ async fn tokio_main() -> Result<()> { ); pool_ready = false; pool_lifecycle = PoolLifecycle::listening(); - last_activity = tokio::time::Instant::now(); + // Only the clock resets. A pool that ran long enough to + // go idle has dispatched, and `ever_dispatched` is a + // permanent latch — re-sleeping must not make a used + // harness eligible for the never-used exit again. + activity.last = tokio::time::Instant::now(); emit_runtime_lifecycle( observer.as_ref(), &runtime_start_nonce, @@ -3083,7 +3302,7 @@ async fn tokio_main() -> Result<()> { } else if queue.has_flushable_work() { tracing::debug!("heartbeat_skipped_events"); for (channel_id, thread_tags) in - dispatch_pending(&mut pool, &mut queue, &ctx, &mut last_activity) + dispatch_pending(&mut pool, &mut queue, &ctx, &mut activity) { typing_channels.insert(channel_id, thread_tags); } @@ -3182,7 +3401,7 @@ async fn tokio_main() -> Result<()> { break; } for (channel_id, thread_tags) in - dispatch_pending(&mut pool, &mut queue, &ctx, &mut last_activity) + dispatch_pending(&mut pool, &mut queue, &ctx, &mut activity) { typing_channels.insert(channel_id, thread_tags); } @@ -3207,7 +3426,7 @@ async fn tokio_main() -> Result<()> { break; } for (channel_id, thread_tags) in - dispatch_pending(&mut pool, &mut queue, &ctx, &mut last_activity) + dispatch_pending(&mut pool, &mut queue, &ctx, &mut activity) { typing_channels.insert(channel_id, thread_tags); } @@ -3362,7 +3581,7 @@ async fn tokio_main() -> Result<()> { // queue drains. We still try here in case the in-flight // task has already returned. for (channel_id, thread_tags) in - dispatch_pending(&mut pool, &mut queue, &ctx, &mut last_activity) + dispatch_pending(&mut pool, &mut queue, &ctx, &mut activity) { typing_channels.insert(channel_id, thread_tags); } @@ -3390,7 +3609,7 @@ async fn tokio_main() -> Result<()> { None, ); for (channel_id, thread_tags) in - dispatch_pending(&mut pool, &mut queue, &ctx, &mut last_activity) + dispatch_pending(&mut pool, &mut queue, &ctx, &mut activity) { typing_channels.insert(channel_id, thread_tags); } @@ -3730,7 +3949,7 @@ fn dispatch_pending( pool: &mut AgentPool, queue: &mut EventQueue, ctx: &Arc, - last_activity: &mut tokio::time::Instant, + activity: &mut DispatchActivity, ) -> Vec<(Uuid, ThreadTags)> { let mut dispatched_channels = Vec::new(); loop { @@ -3811,7 +4030,11 @@ fn dispatch_pending( }, ); dispatched_channels.push((channel_id, typing_scope)); - *last_activity = tokio::time::Instant::now(); + activity.last = tokio::time::Instant::now(); + // The harness has now done real work. This is the disarm seam for the + // one-shot never-used bound: whatever speculation started this process, + // it is an ordinary durable harness from here on. + activity.ever_dispatched = true; } tracing::debug!( dispatched = dispatched_channels.len(), @@ -6831,6 +7054,7 @@ mod build_mcp_servers_tests { exit_after_inactivity_secs: 0, lazy_pool: false, idle_pool_sleep_secs: 0, + exit_if_unused_secs: 0, agent_owner: None, no_base_prompt: false, base_prompt_content: None, @@ -7055,6 +7279,7 @@ mod error_outcome_emission_tests { exit_after_inactivity_secs: 0, lazy_pool: false, idle_pool_sleep_secs: 0, + exit_if_unused_secs: 0, agent_owner: None, no_base_prompt: false, base_prompt_content: None, diff --git a/desktop/src-tauri/src/commands/agents.rs b/desktop/src-tauri/src/commands/agents.rs index 33b6ae4462..118139fc34 100644 --- a/desktop/src-tauri/src/commands/agents.rs +++ b/desktop/src-tauri/src/commands/agents.rs @@ -9,11 +9,11 @@ use crate::{ build_managed_agent_summary, current_instance_id, ensure_persona_is_active, find_managed_agent_mut, load_managed_agents, load_personas, load_teams, managed_agent_avatar_url, normalize_agent_args, resolve_provider_binary, - save_managed_agents, start_managed_agent_process, stop_managed_agent_process, - stop_managed_agent_workspace_pair, sync_managed_agent_processes, try_regenerate_nest, - validate_provider_config, BackendKind, CreateManagedAgentRequest, - CreateManagedAgentResponse, ManagedAgentRecord, ManagedAgentSummary, RelayMeshConfig, - DEFAULT_ACP_COMMAND, DEFAULT_AGENT_PARALLELISM, DEFAULT_AGENT_TURN_TIMEOUT_SECONDS, + save_managed_agents, stop_managed_agent_process, stop_managed_agent_workspace_pair, + sync_managed_agent_processes, try_regenerate_nest, validate_provider_config, BackendKind, + CreateManagedAgentRequest, CreateManagedAgentResponse, ManagedAgentRecord, + ManagedAgentSummary, RelayMeshConfig, SpawnPolicy, DEFAULT_ACP_COMMAND, + DEFAULT_AGENT_PARALLELISM, DEFAULT_AGENT_TURN_TIMEOUT_SECONDS, }, relay::{relay_ws_url_with_override, sync_managed_agent_profile}, util::now_iso, @@ -34,6 +34,10 @@ pub(crate) use pending::{ archive_managed_agent_pending, retain_managed_agent_pending, tombstone_managed_agent_pending, }; +#[path = "agents_start.rs"] +mod start; +pub(crate) use start::{start_local_agent_pairs_with_preflight, start_local_agent_with_preflight}; + /// Build a summary from fresh disk state (personas, teams, global config). /// For one-shot command paths only — the 5s list poll calls /// `build_managed_agent_summary` directly with stores loaded once per call, @@ -101,226 +105,6 @@ fn resolve_created_avatar_url( .or_else(|| managed_agent_avatar_url(agent_command)) } -#[cfg(feature = "mesh-llm")] -async fn ensure_relay_mesh_for_record( - app: &AppHandle, - model_id: Option<&str>, - allow_fresh_create_start: bool, -) -> Result<(), String> { - crate::commands::ensure_relay_mesh_for_record(app, model_id, allow_fresh_create_start).await -} - -#[cfg(not(feature = "mesh-llm"))] -async fn ensure_relay_mesh_for_record( - _app: &AppHandle, - _model_id: Option<&str>, - _allow_fresh_create_start: bool, -) -> Result<(), String> { - Ok(()) -} - -pub(super) async fn start_local_agent_pairs_with_preflight( - app: &AppHandle, - state: &AppState, - pubkey: &str, - relay_urls: &[String], -) -> Result { - let record_snapshot = { - let _store_guard = state - .managed_agents_store_lock - .lock() - .map_err(|e| e.to_string())?; - load_managed_agents(app)? - .into_iter() - .find(|record| record.pubkey == pubkey) - .ok_or_else(|| format!("agent {pubkey} not found"))? - }; - if record_snapshot.backend != BackendKind::Local { - return Err(format!("agent {pubkey} is not a local agent")); - } - let personas_for_preflight = load_personas(app).unwrap_or_default(); - let global_for_preflight = - crate::managed_agents::load_global_agent_config(app).unwrap_or_default(); - let mesh_model_id = - crate::managed_agents::effective_config::resolve_effective_relay_mesh_model_id( - &record_snapshot, - &personas_for_preflight, - &global_for_preflight, - ); - ensure_relay_mesh_for_record(app, mesh_model_id.as_deref(), false).await?; - - { - let _store_guard = state - .managed_agents_store_lock - .lock() - .map_err(|e| e.to_string())?; - let mut records = load_managed_agents(app)?; - let record = find_managed_agent_mut(&mut records, pubkey)?; - let personas = load_personas(app).unwrap_or_default(); - if let Some(persona_id) = record.persona_id.clone() { - if let Some(persona) = personas.iter().find(|persona| persona.id == persona_id) { - crate::managed_agents::persona_events::apply_persona_snapshot(record, persona); - record.updated_at = crate::util::now_iso(); - } - } - save_managed_agents(app, &records)?; - if let Some(saved_record) = records.iter().find(|record| record.pubkey == pubkey) { - retain_managed_agent_pending(app, state, saved_record); - } - } - - let mut errors = Vec::new(); - for relay_url in relay_urls { - if let Err(error) = crate::managed_agents::start_managed_agent_runtime_pair_lazy( - pubkey.to_string(), - relay_url.clone(), - app.clone(), - ) { - errors.push(format!("{relay_url}: {error}")); - } - } - if !errors.is_empty() { - return Err(format!( - "failed to restart one or more managed-agent runtime pairs: {}", - errors.join("; ") - )); - } - - let _store_guard = state - .managed_agents_store_lock - .lock() - .map_err(|e| e.to_string())?; - let records = load_managed_agents(app)?; - let runtimes = state - .managed_agent_processes - .lock() - .map_err(|e| e.to_string())?; - let record = records - .iter() - .find(|record| record.pubkey == pubkey) - .ok_or_else(|| format!("agent {pubkey} not found"))?; - summarize_from_disk(app, record, &runtimes) -} - -pub(super) async fn start_local_agent_with_preflight( - app: &AppHandle, - state: &AppState, - pubkey: &str, - allow_fresh_create_start: bool, - expected_relay_url: Option<&str>, - expected_signer_pubkey: Option<&str>, -) -> Result { - let record_snapshot = { - let _store_guard = state - .managed_agents_store_lock - .lock() - .map_err(|e| e.to_string())?; - let records = load_managed_agents(app)?; - records - .iter() - .find(|record| record.pubkey == pubkey) - .cloned() - .ok_or_else(|| format!("agent {pubkey} not found"))? - }; - - if record_snapshot.backend != BackendKind::Local { - return Err(format!("agent {pubkey} is not a local agent")); - } - - // Preflight against the same resolution spawn uses — `resolve_effective_config` - // (definition → global fallback). A linked instance's own `provider`/`model`/ - // `relay_mesh` bytes never contribute: this reads the CURRENT definition - // directly, so a definition edit that flips `provider` to/from relay-mesh - // between saves is reflected here without needing a prospective re-snapshot; - // for a global-inherited blank definition, it also folds in the global - // default, which record-byte sniffing could never see. - let personas = load_personas(app).unwrap_or_default(); - let global = crate::managed_agents::load_global_agent_config(app).unwrap_or_default(); - let mesh_model_id = - crate::managed_agents::effective_config::resolve_effective_relay_mesh_model_id( - &record_snapshot, - &personas, - &global, - ); - ensure_relay_mesh_for_record(app, mesh_model_id.as_deref(), allow_fresh_create_start).await?; - - // The mesh preflight above is the suspension window Projects callbacks - // capture their scope against: a community switch during that await - // would otherwise spawn this pair keyed to the *new* workspace relay. - // Read the workspace relay ONCE, assert the caller's captured scope - // against that exact read, and hand the same bound value to the spawn - // below — the check is tied to its use, so a switch landing after this - // point can no longer retarget the spawn (it only changes state this - // call no longer consults). - let workspace_relay_url = crate::relay::bind_expected_relay_scope( - expected_relay_url, - crate::relay::relay_ws_url_with_override(state), - )?; - // Bind the active owner after the same final await as the relay. A - // same-relay identity replacement during mesh preflight must not release - // the stale preflight owner to spawn. - let workspace_owner = - crate::relay::bind_expected_signer(expected_signer_pubkey, workspace_owner_hex(state)?)?; - - let _store_guard = state - .managed_agents_store_lock - .lock() - .map_err(|e| e.to_string())?; - let mut records = load_managed_agents(app)?; - let mut runtimes = state - .managed_agent_processes - .lock() - .map_err(|e| e.to_string())?; - let record = find_managed_agent_mut(&mut records, pubkey)?; - if record.backend != BackendKind::Local { - return Err(format!("agent {pubkey} is no longer a local agent")); - } - // Re-snapshot the persona onto the record at every spawn so the agent always - // starts with the current persona config (system_prompt, model, provider, - // runtime). This clears the "out of date" drift badge without requiring a - // delete+recreate. See `apply_persona_snapshot` for the precedence and - // env-override self-heal rules. - // Load personas once: used for snapshot application below and summary build - // at the end — avoids a second disk read for the same file in the same call. - let personas = load_personas(app).unwrap_or_default(); - if let Some(persona_id) = record.persona_id.clone() { - match personas.iter().find(|p| p.id == persona_id) { - Some(persona) => { - crate::managed_agents::persona_events::apply_persona_snapshot(record, persona); - record.updated_at = crate::util::now_iso(); - } - None => { - return Err( - crate::managed_agents::effective_config::ORPHANED_INSTANCE_ERROR.to_string(), - ); - } - } - } - start_managed_agent_process( - app, - record, - &mut runtimes, - Some(workspace_owner.as_str()), - &workspace_relay_url, - )?; - save_managed_agents(app, &records)?; - if let Some(saved_record) = records.iter().find(|r| r.pubkey == pubkey) { - retain_managed_agent_pending(app, state, saved_record); - } - let record = records - .iter() - .find(|record| record.pubkey == pubkey) - .ok_or_else(|| format!("agent {pubkey} not found"))?; - build_managed_agent_summary( - app, - record, - &runtimes, - &personas, - &load_teams(app).unwrap_or_default(), - &crate::managed_agents::load_global_agent_config(app).unwrap_or_default(), - ) -} - pub(crate) use provider_deploy::deploy_to_provider; // Async so the blocking body (disk reads of agent/persona records, per-agent @@ -749,7 +533,17 @@ pub async fn create_managed_agent( // ── Phase 3b: local spawn (async preflight outside store lock) ─────────── let mut spawn_error = None; let agent = if input.spawn_after_create && input.backend == BackendKind::Local { - match start_local_agent_with_preflight(&app, &state, &pubkey, true, None, None).await { + match start_local_agent_with_preflight( + &app, + &state, + &pubkey, + true, + None, + None, + SpawnPolicy::Durable, + ) + .await + { Ok(agent) => agent, Err(error) => { let _store_guard = state @@ -856,12 +650,23 @@ pub async fn create_managed_agent( }) } -/// Data needed for background profile reconciliation after agent start. +/// Start a managed agent — locally, or by deploying to its provider backend — +/// and snapshot the data background profile reconciliation needs afterwards. +/// +/// `speculative` marks a start the user did not ask for: the composer prewakes +/// a mentioned agent while its draft is still being typed. Only the local arm +/// consumes it — the frontend never speculatively starts a provider-backed +/// agent, and deploying remote compute for a draft would be a far worse trade +/// than the local cold start it saves. A speculative local harness self-expires +/// if nothing is ever dispatched to it (see [`SpawnPolicy::Speculative`]), so an +/// abandoned draft leaves the same stopped agent it would have without the +/// prewake. #[tauri::command] pub async fn start_managed_agent( pubkey: String, expected_relay_url: Option, expected_signer_pubkey: Option, + speculative: Option, app: AppHandle, state: State<'_, AppState>, ) -> Result { @@ -961,6 +766,11 @@ pub async fn start_managed_agent( false, expected_relay_url.as_deref(), expected_signer_pubkey.as_deref(), + if speculative.unwrap_or(false) { + SpawnPolicy::Speculative + } else { + SpawnPolicy::Durable + }, ) .await } diff --git a/desktop/src-tauri/src/commands/agents_start.rs b/desktop/src-tauri/src/commands/agents_start.rs new file mode 100644 index 0000000000..48986ed274 --- /dev/null +++ b/desktop/src-tauri/src/commands/agents_start.rs @@ -0,0 +1,242 @@ +//! Local-agent start paths with their mesh/scope preflight. +//! +//! Split out of `commands/agents.rs` (at the repository file-size ceiling) +//! alongside the existing `agents_pending.rs` / `agents_deploy.rs` / +//! `agents_profile.rs` siblings. These are the two entry points that resolve a +//! record, run the relay-mesh and tenant-scope preflight, and spawn: one for a +//! single bound pair, one for every pair of a multi-community agent. + +use tauri::AppHandle; + +use crate::{ + app_state::AppState, + managed_agents::{ + build_managed_agent_summary, find_managed_agent_mut, load_managed_agents, load_personas, + load_teams, save_managed_agents, start_managed_agent_process, BackendKind, + ManagedAgentSummary, SpawnPolicy, + }, +}; + +use super::{retain_managed_agent_pending, summarize_from_disk, workspace_owner_hex}; + +#[cfg(feature = "mesh-llm")] +async fn ensure_relay_mesh_for_record( + app: &AppHandle, + model_id: Option<&str>, + allow_fresh_create_start: bool, +) -> Result<(), String> { + crate::commands::ensure_relay_mesh_for_record(app, model_id, allow_fresh_create_start).await +} + +#[cfg(not(feature = "mesh-llm"))] +async fn ensure_relay_mesh_for_record( + _app: &AppHandle, + _model_id: Option<&str>, + _allow_fresh_create_start: bool, +) -> Result<(), String> { + Ok(()) +} + +pub(crate) async fn start_local_agent_pairs_with_preflight( + app: &AppHandle, + state: &AppState, + pubkey: &str, + relay_urls: &[String], +) -> Result { + let record_snapshot = { + let _store_guard = state + .managed_agents_store_lock + .lock() + .map_err(|e| e.to_string())?; + load_managed_agents(app)? + .into_iter() + .find(|record| record.pubkey == pubkey) + .ok_or_else(|| format!("agent {pubkey} not found"))? + }; + if record_snapshot.backend != BackendKind::Local { + return Err(format!("agent {pubkey} is not a local agent")); + } + let personas_for_preflight = load_personas(app).unwrap_or_default(); + let global_for_preflight = + crate::managed_agents::load_global_agent_config(app).unwrap_or_default(); + let mesh_model_id = + crate::managed_agents::effective_config::resolve_effective_relay_mesh_model_id( + &record_snapshot, + &personas_for_preflight, + &global_for_preflight, + ); + ensure_relay_mesh_for_record(app, mesh_model_id.as_deref(), false).await?; + + { + let _store_guard = state + .managed_agents_store_lock + .lock() + .map_err(|e| e.to_string())?; + let mut records = load_managed_agents(app)?; + let record = find_managed_agent_mut(&mut records, pubkey)?; + let personas = load_personas(app).unwrap_or_default(); + if let Some(persona_id) = record.persona_id.clone() { + if let Some(persona) = personas.iter().find(|persona| persona.id == persona_id) { + crate::managed_agents::persona_events::apply_persona_snapshot(record, persona); + record.updated_at = crate::util::now_iso(); + } + } + save_managed_agents(app, &records)?; + if let Some(saved_record) = records.iter().find(|record| record.pubkey == pubkey) { + retain_managed_agent_pending(app, state, saved_record); + } + } + + let mut errors = Vec::new(); + for relay_url in relay_urls { + if let Err(error) = crate::managed_agents::start_managed_agent_runtime_pair_lazy( + pubkey.to_string(), + relay_url.clone(), + app.clone(), + ) { + errors.push(format!("{relay_url}: {error}")); + } + } + if !errors.is_empty() { + return Err(format!( + "failed to restart one or more managed-agent runtime pairs: {}", + errors.join("; ") + )); + } + + let _store_guard = state + .managed_agents_store_lock + .lock() + .map_err(|e| e.to_string())?; + let records = load_managed_agents(app)?; + let runtimes = state + .managed_agent_processes + .lock() + .map_err(|e| e.to_string())?; + let record = records + .iter() + .find(|record| record.pubkey == pubkey) + .ok_or_else(|| format!("agent {pubkey} not found"))?; + summarize_from_disk(app, record, &runtimes) +} + +pub(crate) async fn start_local_agent_with_preflight( + app: &AppHandle, + state: &AppState, + pubkey: &str, + allow_fresh_create_start: bool, + expected_relay_url: Option<&str>, + expected_signer_pubkey: Option<&str>, + policy: SpawnPolicy, +) -> Result { + let record_snapshot = { + let _store_guard = state + .managed_agents_store_lock + .lock() + .map_err(|e| e.to_string())?; + let records = load_managed_agents(app)?; + records + .iter() + .find(|record| record.pubkey == pubkey) + .cloned() + .ok_or_else(|| format!("agent {pubkey} not found"))? + }; + + if record_snapshot.backend != BackendKind::Local { + return Err(format!("agent {pubkey} is not a local agent")); + } + + // Preflight against the same resolution spawn uses — `resolve_effective_config` + // (definition → global fallback). A linked instance's own `provider`/`model`/ + // `relay_mesh` bytes never contribute: this reads the CURRENT definition + // directly, so a definition edit that flips `provider` to/from relay-mesh + // between saves is reflected here without needing a prospective re-snapshot; + // for a global-inherited blank definition, it also folds in the global + // default, which record-byte sniffing could never see. + let personas = load_personas(app).unwrap_or_default(); + let global = crate::managed_agents::load_global_agent_config(app).unwrap_or_default(); + let mesh_model_id = + crate::managed_agents::effective_config::resolve_effective_relay_mesh_model_id( + &record_snapshot, + &personas, + &global, + ); + ensure_relay_mesh_for_record(app, mesh_model_id.as_deref(), allow_fresh_create_start).await?; + + // The mesh preflight above is the suspension window Projects callbacks + // capture their scope against: a community switch during that await + // would otherwise spawn this pair keyed to the *new* workspace relay. + // Read the workspace relay ONCE, assert the caller's captured scope + // against that exact read, and hand the same bound value to the spawn + // below — the check is tied to its use, so a switch landing after this + // point can no longer retarget the spawn (it only changes state this + // call no longer consults). + let workspace_relay_url = crate::relay::bind_expected_relay_scope( + expected_relay_url, + crate::relay::relay_ws_url_with_override(state), + )?; + // Bind the active owner after the same final await as the relay. A + // same-relay identity replacement during mesh preflight must not release + // the stale preflight owner to spawn. + let workspace_owner = + crate::relay::bind_expected_signer(expected_signer_pubkey, workspace_owner_hex(state)?)?; + + let _store_guard = state + .managed_agents_store_lock + .lock() + .map_err(|e| e.to_string())?; + let mut records = load_managed_agents(app)?; + let mut runtimes = state + .managed_agent_processes + .lock() + .map_err(|e| e.to_string())?; + let record = find_managed_agent_mut(&mut records, pubkey)?; + if record.backend != BackendKind::Local { + return Err(format!("agent {pubkey} is no longer a local agent")); + } + // Re-snapshot the persona onto the record at every spawn so the agent always + // starts with the current persona config (system_prompt, model, provider, + // runtime). This clears the "out of date" drift badge without requiring a + // delete+recreate. See `apply_persona_snapshot` for the precedence and + // env-override self-heal rules. + // Load personas once: used for snapshot application below and summary build + // at the end — avoids a second disk read for the same file in the same call. + let personas = load_personas(app).unwrap_or_default(); + if let Some(persona_id) = record.persona_id.clone() { + match personas.iter().find(|p| p.id == persona_id) { + Some(persona) => { + crate::managed_agents::persona_events::apply_persona_snapshot(record, persona); + record.updated_at = crate::util::now_iso(); + } + None => { + return Err( + crate::managed_agents::effective_config::ORPHANED_INSTANCE_ERROR.to_string(), + ); + } + } + } + start_managed_agent_process( + app, + record, + &mut runtimes, + Some(workspace_owner.as_str()), + &workspace_relay_url, + policy, + )?; + save_managed_agents(app, &records)?; + if let Some(saved_record) = records.iter().find(|r| r.pubkey == pubkey) { + retain_managed_agent_pending(app, state, saved_record); + } + let record = records + .iter() + .find(|record| record.pubkey == pubkey) + .ok_or_else(|| format!("agent {pubkey} not found"))?; + build_managed_agent_summary( + app, + record, + &runtimes, + &personas, + &load_teams(app).unwrap_or_default(), + &crate::managed_agents::load_global_agent_config(app).unwrap_or_default(), + ) +} diff --git a/desktop/src-tauri/src/managed_agents/agent_env.rs b/desktop/src-tauri/src/managed_agents/agent_env.rs index 59b300d9d1..8cb8ee083a 100644 --- a/desktop/src-tauri/src/managed_agents/agent_env.rs +++ b/desktop/src-tauri/src/managed_agents/agent_env.rs @@ -15,15 +15,69 @@ use base64::Engine as _; /// normal back-and-forth but a truly quiet harness stops paying for workers. const IDLE_POOL_SLEEP_SECS: &str = "900"; -/// Value for `BUZZ_ACP_IDLE_POOL_SLEEP`. Idle re-sleep is only meaningful for -/// lazy harnesses (the harness ignores it otherwise); gate to `lazy` here so -/// the env reads inert (`"0"` = disabled) for eager harnesses. This is a -/// desktop-owned lifetime policy (reserved key), not user-tunable. -pub(super) fn idle_pool_sleep_env(lazy: bool) -> &'static str { - if lazy { - IDLE_POOL_SLEEP_SECS - } else { - "0" +/// Seconds a speculatively started harness may stay up without ever being used +/// before it exits gracefully (via `BUZZ_ACP_EXIT_IF_UNUSED`). Same 15 minutes +/// as [`IDLE_POOL_SLEEP_SECS`], for the symmetric reason: it is the window in +/// which the draft that woke the agent could still plausibly be sent. +/// +/// Expiring costs nothing but a cold start — the composer re-arms the prewake +/// when a parked draft is resumed, and the send path has always started a +/// mentioned agent that is not running. +const EXIT_IF_UNUSED_SECS: &str = "900"; + +/// How a spawned harness's worker pool and lifetime are bounded. +/// +/// One enum rather than a pair of booleans because the combinations are not +/// independent: a lazy pair defers its pool and lives until it is stopped, and +/// a speculative pair boots eagerly precisely so a send that may never come is +/// fast. "Lazy speculative" would defeat the prewake it exists for, so it is +/// not representable. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SpawnPolicy { + /// Eager pool, no lifetime bound. Every user-initiated start. + Durable, + /// Pool deferred until the first accepted event; no lifetime bound. Launch + /// restore and runtime reconciliation spawn these. + Lazy, + /// Eager pool with a one-shot never-used bound. Started ahead of a draft + /// that may never be sent (the composer's mention prewake), so the harness + /// self-expires unless something is dispatched to it. The first dispatched + /// event promotes it to a durable harness inside the harness itself — no + /// desktop-side promotion call, and no way for an outside kill to race a + /// turn it cannot see. + Speculative, +} + +impl SpawnPolicy { + /// Value for `BUZZ_ACP_LAZY_POOL`. + pub(super) fn lazy_pool_env(self) -> &'static str { + match self { + Self::Lazy => "true", + Self::Durable | Self::Speculative => "false", + } + } + + /// Value for `BUZZ_ACP_IDLE_POOL_SLEEP`. Idle re-sleep is only meaningful + /// for lazy harnesses (the harness ignores it otherwise); gate on the + /// policy here so the env reads inert (`"0"` = disabled) for eager + /// harnesses. This is a desktop-owned lifetime policy (reserved key), not + /// user-tunable. + pub(super) fn idle_pool_sleep_env(self) -> &'static str { + match self { + Self::Lazy => IDLE_POOL_SLEEP_SECS, + Self::Durable | Self::Speculative => "0", + } + } + + /// Value for `BUZZ_ACP_EXIT_IF_UNUSED`. Written on every spawn — inert + /// (`"0"`) for deliberate starts — so the bound is always stated explicitly + /// rather than inherited from an ambient environment. Also a reserved key: + /// user env must not disable the bound the desktop attached. + pub(super) fn exit_if_unused_env(self) -> &'static str { + match self { + Self::Speculative => EXIT_IF_UNUSED_SECS, + Self::Durable | Self::Lazy => "0", + } } } @@ -141,9 +195,41 @@ pub(crate) fn parse_agent_env_lines(raw: &str) -> Vec<(&str, &str)> { mod tests { use super::{ baked_build_env, build_buzz_agent_provider_defaults, build_env_map, - discovery_env_with_baked_floor, parse_agent_env_lines, + discovery_env_with_baked_floor, parse_agent_env_lines, SpawnPolicy, }; + // ── spawn policy → lifetime env ─────────────────────────────────────── + // + // These three keys are what the desktop uses to state a harness's pool and + // lifetime policy; every spawn writes all three, so a value is never + // inherited from the launching process's environment. + + #[test] + fn durable_policy_states_every_lifetime_bound_as_inert() { + // The deliberate start: eager pool, no re-sleep, no unused bound. + assert_eq!(SpawnPolicy::Durable.lazy_pool_env(), "false"); + assert_eq!(SpawnPolicy::Durable.idle_pool_sleep_env(), "0"); + assert_eq!(SpawnPolicy::Durable.exit_if_unused_env(), "0"); + } + + #[test] + fn lazy_policy_defers_the_pool_and_reclaims_idle_workers() { + assert_eq!(SpawnPolicy::Lazy.lazy_pool_env(), "true"); + assert_eq!(SpawnPolicy::Lazy.idle_pool_sleep_env(), "900"); + // A lazy pair is a reconcile/launch pair the user asked to keep + // running — it must not self-expire just because nobody messaged it. + assert_eq!(SpawnPolicy::Lazy.exit_if_unused_env(), "0"); + } + + #[test] + fn speculative_policy_boots_eagerly_and_bounds_the_unused_case() { + // Eager: the whole point of the prewake is to pay boot cost early. + assert_eq!(SpawnPolicy::Speculative.lazy_pool_env(), "false"); + assert_eq!(SpawnPolicy::Speculative.idle_pool_sleep_env(), "0"); + // Bounded: an abandoned draft must not leak a live harness. + assert_eq!(SpawnPolicy::Speculative.exit_if_unused_env(), "900"); + } + #[test] fn buzz_agent_provider_defaults_empty_in_oss_build() { // OSS (and normal test) builds set neither BUZZ_BUILD_BUZZ_AGENT_*, diff --git a/desktop/src-tauri/src/managed_agents/env_vars/tests.rs b/desktop/src-tauri/src/managed_agents/env_vars/tests.rs index f3de11ad24..361366ab6d 100644 --- a/desktop/src-tauri/src/managed_agents/env_vars/tests.rs +++ b/desktop/src-tauri/src/managed_agents/env_vars/tests.rs @@ -167,6 +167,7 @@ fn reserved_keys_include_remote_lifetime_policy() { for key in [ "BUZZ_ACP_EXIT_AFTER_INACTIVITY", "BUZZ_ACP_IDLE_POOL_SLEEP", + "BUZZ_ACP_EXIT_IF_UNUSED", "BUZZ_ACP_NO_PRESENCE", ] { assert!(is_reserved_env_key(key), "{key} should be reserved"); diff --git a/desktop/src-tauri/src/managed_agents/mod.rs b/desktop/src-tauri/src/managed_agents/mod.rs index 272c03348b..96087c6e7c 100644 --- a/desktop/src-tauri/src/managed_agents/mod.rs +++ b/desktop/src-tauri/src/managed_agents/mod.rs @@ -7,6 +7,7 @@ pub(crate) mod team_snapshot; pub(crate) use access_policy::{owner_only, owner_only_access_build, projected_access_with_policy}; pub(crate) use agent_env::{ baked_build_env, build_buzz_agent_provider_defaults, discovery_env_with_baked_floor, + SpawnPolicy, }; mod backend; pub(crate) mod claude_config; diff --git a/desktop/src-tauri/src/managed_agents/reserved_env_keys.rs b/desktop/src-tauri/src/managed_agents/reserved_env_keys.rs index afaaa2b4eb..9308a579bf 100644 --- a/desktop/src-tauri/src/managed_agents/reserved_env_keys.rs +++ b/desktop/src-tauri/src/managed_agents/reserved_env_keys.rs @@ -62,6 +62,10 @@ pub(crate) const RESERVED_ENV_KEYS: &[&str] = &[ // Desktop-owned pool lifetime policy: user env must not disable or reset // the idle worker-reclamation window while the desktop launcher sets it. "BUZZ_ACP_IDLE_POOL_SLEEP", + // Desktop-owned speculative lifetime policy: the composer's mention + // prewake attaches a never-used bound so an abandoned draft cannot leak a + // live harness. User env must not be able to remove it. + "BUZZ_ACP_EXIT_IF_UNUSED", "BUZZ_ACP_NO_PRESENCE", // Readiness handoff: desktop is the ONLY readiness source. A saved or // ambient env var must not be able to forge setup mode (NotReady) on a diff --git a/desktop/src-tauri/src/managed_agents/restore.rs b/desktop/src-tauri/src/managed_agents/restore.rs index a225f492d3..56b5248f1f 100644 --- a/desktop/src-tauri/src/managed_agents/restore.rs +++ b/desktop/src-tauri/src/managed_agents/restore.rs @@ -1,7 +1,7 @@ use super::{ find_managed_agent_mut, kill_stale_tracked_processes, load_managed_agents, load_personas, save_managed_agents, spawn_agent_child, sync_managed_agent_processes, BackendKind, - ManagedAgentProcess, + ManagedAgentProcess, SpawnPolicy, }; use crate::app_state::AppState; use crate::util; @@ -336,7 +336,7 @@ pub async fn restore_managed_agents_on_launch( app, record, &key.relay_url, - true, + SpawnPolicy::Lazy, owner_hex_ref, ) }) { diff --git a/desktop/src-tauri/src/managed_agents/runtime.rs b/desktop/src-tauri/src/managed_agents/runtime.rs index 0ce5ca7b21..ce233223ed 100644 --- a/desktop/src-tauri/src/managed_agents/runtime.rs +++ b/desktop/src-tauri/src/managed_agents/runtime.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use tauri::AppHandle; -use super::agent_env::{build_buzz_agent_provider_defaults, idle_pool_sleep_env}; +use super::agent_env::{build_buzz_agent_provider_defaults, SpawnPolicy}; use crate::{ managed_agents::{ @@ -71,6 +71,9 @@ pub use lifecycle::{kill_stale_tracked_processes, sync_managed_agent_processes}; mod spawn_key; // production spawn-key derivation + its regressions pub(crate) use spawn_key::bound_runtime_key; +mod start; +pub use start::start_managed_agent_process; + /// Classify an agent's persona against the live catalog for the Agents-menu /// drift indicator. Returns `(out_of_date, orphaned)`. /// @@ -403,11 +406,15 @@ pub(crate) fn configure_runtime_cli( /// /// `owner_hex`: the workspace owner's pubkey, used as a fallback for legacy /// records that have no NIP-OA `auth_tag`. See `build_respond_to_env`. +/// +/// `policy`: how the child's worker pool and lifetime are bounded. See +/// [`SpawnPolicy`] — the desktop states all three lifetime env vars on every +/// spawn, so nothing is inherited from the launching environment. pub fn spawn_agent_child( app: &AppHandle, record: &ManagedAgentRecord, relay_url: &str, - lazy: bool, + policy: SpawnPolicy, owner_hex: Option<&str>, ) -> Result { if let Some(error) = spawn_key_refusal(record) { @@ -532,8 +539,9 @@ pub fn spawn_agent_child( command.env("RUST_LOG", child_rust_log_filter()); command.env("BUZZ_PRIVATE_KEY", &record.private_key_nsec); command.env("BUZZ_RELAY_URL", &effective_relay_url); - command.env("BUZZ_ACP_LAZY_POOL", if lazy { "true" } else { "false" }); - command.env("BUZZ_ACP_IDLE_POOL_SLEEP", idle_pool_sleep_env(lazy)); + command.env("BUZZ_ACP_LAZY_POOL", policy.lazy_pool_env()); + command.env("BUZZ_ACP_IDLE_POOL_SLEEP", policy.idle_pool_sleep_env()); + command.env("BUZZ_ACP_EXIT_IF_UNUSED", policy.exit_if_unused_env()); command.env("BUZZ_ACP_AGENT_COMMAND", &resolved_agent_command); command.env("BUZZ_ACP_AGENT_ARGS", agent_args.join(",")); match &resolved_mcp_command { @@ -936,62 +944,6 @@ fn child_rust_log_filter() -> String { } } -/// Spawn (or adopt) the runtime pair for `record` on the caller's bound -/// workspace relay. `workspace_relay` can only be produced by -/// `bind_expected_relay_scope`, so this spawn consumes — by construction — the -/// 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, - record: &mut ManagedAgentRecord, - runtimes: &mut HashMap, - owner_hex: Option<&str>, - workspace_relay: &crate::relay::ScopedWorkspaceRelay, -) -> Result<(), String> { - let key = bound_runtime_key(record, workspace_relay)?; - if let Some(runtime) = runtimes.get_mut(&key) { - if runtime - .child - .try_wait() - .map_err(|error| format!("failed to inspect running process: {error}"))? - .is_none() - { - return Ok(()); - } - - runtimes.remove(&key); - super::remove_agent_runtime_receipt(app, &key); - } - - // Scalar PIDs are migration-only and never establish pair liveness. - record.runtime_pid = None; - - let mut process = spawn_agent_child(app, record, &key.relay_url, false, owner_hex)?; - let now = now_iso(); - let receipt = super::ManagedAgentRuntimeReceipt { - key: key.clone(), - pid: process.child.id(), - desktop_instance_id: current_instance_id(app), - started_at: now.clone(), - }; - if let Err(error) = super::write_agent_runtime_receipt(app, &receipt) { - let _ = terminate_process(process.child.id()); - let _ = process.child.wait(); - return Err(error); - } - - record.updated_at = now.clone(); - record.last_started_at = Some(now); - record.last_stopped_at = None; - record.last_exit_code = None; - record.last_error = None; - record.last_error_code = None; - - runtimes.insert(key, ManagedAgentPairRuntime::starting(process)); - Ok(()) -} - #[cfg(test)] mod test_fixtures; diff --git a/desktop/src-tauri/src/managed_agents/runtime/start.rs b/desktop/src-tauri/src/managed_agents/runtime/start.rs new file mode 100644 index 0000000000..a9680431ac --- /dev/null +++ b/desktop/src-tauri/src/managed_agents/runtime/start.rs @@ -0,0 +1,81 @@ +//! Runtime-pair start: spawn a child for a bound (agent, relay) pair and +//! record it as the live pair. +//! +//! Split out of `runtime.rs` (which is at the repository file-size ceiling) +//! alongside the other `runtime/` submodules. `spawn_agent_child` — the env +//! assembly this calls — stays there. + +use std::collections::HashMap; + +use tauri::AppHandle; + +use super::{ + bound_runtime_key, current_instance_id, spawn_agent_child, terminate_process, SpawnPolicy, +}; +use crate::{ + managed_agents::{ManagedAgentPairRuntime, ManagedAgentRecord, ManagedAgentRuntimeKey}, + util::now_iso, +}; + +/// Spawn (or adopt) the runtime pair for `record` on the caller's bound +/// workspace relay. `workspace_relay` can only be produced by +/// `bind_expected_relay_scope`, so this spawn consumes — by construction — the +/// 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. +/// +/// `policy` bounds the spawned child's pool and lifetime; see [`SpawnPolicy`]. +pub fn start_managed_agent_process( + app: &AppHandle, + record: &mut ManagedAgentRecord, + runtimes: &mut HashMap, + owner_hex: Option<&str>, + workspace_relay: &crate::relay::ScopedWorkspaceRelay, + policy: SpawnPolicy, +) -> Result<(), String> { + let key = bound_runtime_key(record, workspace_relay)?; + if let Some(runtime) = runtimes.get_mut(&key) { + if runtime + .child + .try_wait() + .map_err(|error| format!("failed to inspect running process: {error}"))? + .is_none() + { + // A live pair is left exactly as it is, whatever `policy` asked + // for: a durable start landing on a speculative pair spawns + // nothing, and the running harness's own bound is what promotes it + // — the send's message dispatch, not this call. + return Ok(()); + } + + runtimes.remove(&key); + crate::managed_agents::remove_agent_runtime_receipt(app, &key); + } + + // Scalar PIDs are migration-only and never establish pair liveness. + record.runtime_pid = None; + + let mut process = spawn_agent_child(app, record, &key.relay_url, policy, owner_hex)?; + let now = now_iso(); + let receipt = crate::managed_agents::ManagedAgentRuntimeReceipt { + key: key.clone(), + pid: process.child.id(), + desktop_instance_id: current_instance_id(app), + started_at: now.clone(), + }; + if let Err(error) = crate::managed_agents::write_agent_runtime_receipt(app, &receipt) { + let _ = terminate_process(process.child.id()); + let _ = process.child.wait(); + return Err(error); + } + + record.updated_at = now.clone(); + record.last_started_at = Some(now); + record.last_stopped_at = None; + record.last_exit_code = None; + record.last_error = None; + record.last_error_code = None; + + runtimes.insert(key, ManagedAgentPairRuntime::starting(process)); + Ok(()) +} diff --git a/desktop/src-tauri/src/managed_agents/runtime_commands.rs b/desktop/src-tauri/src/managed_agents/runtime_commands.rs index 135224d01d..b620cc7bec 100644 --- a/desktop/src-tauri/src/managed_agents/runtime_commands.rs +++ b/desktop/src-tauri/src/managed_agents/runtime_commands.rs @@ -9,7 +9,7 @@ use super::{ spawn_agent_child, terminate_process, terminate_untracked_pair_runtime, write_agent_runtime_receipt, AgentReadiness, BackendKind, ManagedAgentPairRuntime, ManagedAgentRuntimeKey, ManagedAgentRuntimeLifecycle, ManagedAgentRuntimeReceipt, - ManagedAgentRuntimeStatus, + ManagedAgentRuntimeStatus, SpawnPolicy, }; use crate::app_state::AppState; @@ -288,7 +288,12 @@ 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())?; + let policy = if lazy { + SpawnPolicy::Lazy + } else { + SpawnPolicy::Durable + }; + let mut process = spawn_agent_child(&app, record, &key.relay_url, policy, owner.as_deref())?; let now = crate::util::now_iso(); let receipt = ManagedAgentRuntimeReceipt { key: key.clone(), diff --git a/desktop/src/features/agents/hooks.ts b/desktop/src/features/agents/hooks.ts index b7dd766733..1a327af6fe 100644 --- a/desktop/src/features/agents/hooks.ts +++ b/desktop/src/features/agents/hooks.ts @@ -577,6 +577,7 @@ export function useStartManagedAgentMutation() { pubkey: string; expectedRelayUrl?: string; expectedSignerPubkey?: string; + speculative?: boolean; }, ) => typeof input === "string" @@ -584,6 +585,7 @@ export function useStartManagedAgentMutation() { : startManagedAgent(input.pubkey, { expectedRelayUrl: input.expectedRelayUrl, expectedSignerPubkey: input.expectedSignerPubkey, + speculative: input.speculative, }), onSuccess: (updated) => { queryClient.setQueryData( diff --git a/desktop/src/features/messages/ui/useMentionWakePreflight.test.mjs b/desktop/src/features/messages/ui/useMentionWakePreflight.test.mjs index 6bab7b6e99..46ab39b30f 100644 --- a/desktop/src/features/messages/ui/useMentionWakePreflight.test.mjs +++ b/desktop/src/features/messages/ui/useMentionWakePreflight.test.mjs @@ -351,6 +351,38 @@ test("mention-free drafts skip the mention-ref snapshot entirely", async () => { assert.equal(snapshots, 0); }); +test("a prewake start is marked speculative", async (t) => { + // The flag is what bounds the spawned harness's lifetime: without it an + // abandoned draft leaks a live agent until app quit. Nothing else in the app + // sets it, so this call site is the whole contract. + t.mock.timers.enable({ apis: ["setTimeout"] }); + const { act, renderHook } = await import("@testing-library/react"); + const inputs = []; + const contentRef = { current: "@Fizz please investigate" }; + const view = renderHook(() => + useMentionWakePreflight( + localAgentOptions(contentRef, () => {}, { + startManagedAgent: async (input) => { + inputs.push(input); + return { pubkey: AGENT, status: "running" }; + }, + }), + ), + ); + + act(() => view.result.current.prepareMentionWake(contentRef.current)); + await act(async () => t.mock.timers.tick(MENTION_WAKE_GATE_HOLD_MS)); + + assert.deepEqual(inputs, [ + { + pubkey: AGENT, + expectedRelayUrl: "wss://relay.example", + expectedSignerPubkey: "c".repeat(64), + speculative: true, + }, + ]); +}); + test("provider-backed agents are never woken speculatively", async (t) => { t.mock.timers.enable({ apis: ["setTimeout"] }); const { act, renderHook } = await import("@testing-library/react"); diff --git a/desktop/src/features/messages/ui/useMentionWakePreflight.ts b/desktop/src/features/messages/ui/useMentionWakePreflight.ts index de82a3f652..dd06d40534 100644 --- a/desktop/src/features/messages/ui/useMentionWakePreflight.ts +++ b/desktop/src/features/messages/ui/useMentionWakePreflight.ts @@ -35,6 +35,13 @@ export type ManagedAgentStartInput = pubkey: string; expectedRelayUrl?: string; expectedSignerPubkey?: string; + /** + * The user did not ask for this start — it is a prewake for a draft that + * may never be sent. The backend attaches a one-shot never-used bound to + * the spawned harness, which the first dispatched event disarms, so an + * abandoned draft ends in the same stopped state as no prewake at all. + */ + speculative?: boolean; }; type MentionWakePlan = { @@ -223,6 +230,9 @@ export function useMentionWakePreflight(options: { pubkey, expectedRelayUrl: context.expectedRelayUrl, expectedSignerPubkey: context.expectedSignerPubkey, + // Nobody has sent anything yet. Bound the harness so an + // abandoned draft cannot leak it. + speculative: true, }), ] : []; diff --git a/desktop/src/features/messages/ui/useSingleFlightManagedAgentStart.test.mjs b/desktop/src/features/messages/ui/useSingleFlightManagedAgentStart.test.mjs index 955f4803bd..a9cb8ed0c8 100644 --- a/desktop/src/features/messages/ui/useSingleFlightManagedAgentStart.test.mjs +++ b/desktop/src/features/messages/ui/useSingleFlightManagedAgentStart.test.mjs @@ -31,3 +31,22 @@ test("start flight keys coalesce only within the same tenant scope", () => { ); assert.notEqual(scoped, managedAgentStartFlightKey(AGENT)); }); + +test("a send's durable start shares the prewake's flight", () => { + // Same agent, same tenant: the send must reuse the in-flight speculative + // start rather than spawning a second one. Its own message dispatch is what + // clears the harness's never-used bound. + assert.equal( + managedAgentStartFlightKey({ + pubkey: AGENT, + expectedRelayUrl: "wss://relay.example", + expectedSignerPubkey: SIGNER, + speculative: true, + }), + managedAgentStartFlightKey({ + pubkey: AGENT, + expectedRelayUrl: "wss://relay.example", + expectedSignerPubkey: SIGNER, + }), + ); +}); diff --git a/desktop/src/features/messages/ui/useSingleFlightManagedAgentStart.ts b/desktop/src/features/messages/ui/useSingleFlightManagedAgentStart.ts index 0fd1f30386..300f42490a 100644 --- a/desktop/src/features/messages/ui/useSingleFlightManagedAgentStart.ts +++ b/desktop/src/features/messages/ui/useSingleFlightManagedAgentStart.ts @@ -8,6 +8,16 @@ import type { ManagedAgent } from "@/shared/api/types"; import { normalizePubkey } from "@/shared/lib/pubkey"; import type { ManagedAgentStartInput } from "./useMentionWakePreflight"; +/** + * Scope of an in-flight start: the agent and the tenant it is being started + * for. + * + * `speculative` is deliberately excluded. If a prewake is still in flight when + * the send path asks for a durable start of the same scope, sharing that flight + * is correct — the send's own message dispatch is what promotes the harness out + * of its never-used bound, not the flavour of the call that started it. Keying + * on the flag instead would spawn a second start for an agent already booting. + */ export function managedAgentStartFlightKey(input: ManagedAgentStartInput) { const pubkey = normalizePubkey( typeof input === "string" ? input : input.pubkey, diff --git a/desktop/src/shared/api/tauriManagedAgents.ts b/desktop/src/shared/api/tauriManagedAgents.ts index 9f77566da9..0acf0ce77b 100644 --- a/desktop/src/shared/api/tauriManagedAgents.ts +++ b/desktop/src/shared/api/tauriManagedAgents.ts @@ -18,12 +18,18 @@ export async function startManagedAgent( /** Signer identity captured with the relay scope; the backend fails * closed when the active workspace identity no longer matches. */ expectedSignerPubkey?: string; + /** Start made ahead of a send that may never happen (the composer's + * mention prewake). The backend bounds the spawned local harness so it + * self-expires unless something is dispatched to it; provider-backed + * agents ignore the flag and are never started this way. */ + speculative?: boolean; }, ): Promise { const response = await invokeTauri("start_managed_agent", { pubkey, expectedRelayUrl: options?.expectedRelayUrl ?? null, expectedSignerPubkey: options?.expectedSignerPubkey ?? null, + speculative: options?.speculative ?? false, }); return fromRawManagedAgent(response); }