Skip to content

Commit a0dd28d

Browse files
matt2eclaude
andcommitted
feat(desktop): lazily activate workspace agents on visit
Extract agent activation out of the one-shot boot restore into a relay-filtered step that runs on every workspace apply (Phase 2 of lazy multi-workspace agents, building on the Phase 1 relay pinning): - Rename restore_managed_agents_on_launch to activate_workspace_agents, taking the applied workspace relay and starting only local start-on-launch agents pinned to that relay (normalized match; a blank pin matches the visited workspace, mirroring the effective_agent_relay_url defense-in-depth fallback). - Call it from every apply_workspace instead of only the first — boot restore becomes the session's first activation. The one-shot managed_agent_restore_pending flag now gates only the mesh-llm Share Compute restore. - Track activated relays in AppState (activated_agent_relays) so each workspace activates at most once per app session: bouncing A→B→A never resurrects agents the user manually stopped in A. Nothing is stopped on switch — each workspace's agents keep running against their own relay. - Gate the boot-time repos-dir/identity-recovery safety checks behind a new session-wide managed_agent_activation_enabled flag, and run the stale-process/orphan sweeps only on the session's first activation so a later activation cannot reap a concurrent activation's not-yet-tracked children. Tested: cargo test --manifest-path desktop/src-tauri/Cargo.toml (1424 passed, incl. 7 new activation unit tests), clippy -D warnings, rustfmt, cargo check --features mesh-llm. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent 98390db commit a0dd28d

7 files changed

Lines changed: 310 additions & 67 deletions

File tree

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,10 @@ const overrides = new Map([
361361
["src/features/settings/ui/ProfileSettingsCard.tsx", 1033],
362362
// keyring-dev-isolation: keyring_service() fn (7 lines) replaces the const
363363
// to return "buzz-desktop-dev" in debug builds. Load-bearing isolation fix.
364-
["src-tauri/src/app_state.rs", 1042],
364+
// lazy-workspace-activation: managed_agent_activation_enabled +
365+
// activated_agent_relays fields (with once-per-session contract docs) add
366+
// ~14 lines. Queued to split identity resolution out of app_state.rs.
367+
["src-tauri/src/app_state.rs", 1056],
365368
// multi-slot splitting + no-op suppression (#1309): the ReadStateManager
366369
// class grew from ~700 lines to ~1019 with the addition of
367370
// splitContextsIntoBudgetedSlots (pure fn + 5 tests), publishSplitSlots,

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

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::{
2-
collections::HashMap,
2+
collections::{HashMap, HashSet},
33
io::Write,
44
sync::{
55
atomic::{AtomicBool, AtomicU16},
@@ -21,10 +21,22 @@ pub struct AppState {
2121
/// Workspace-provided relay URL override. Set by `apply_workspace` on app
2222
/// init and takes priority over env vars and compile-time defaults.
2323
pub relay_url_override: Mutex<Option<String>>,
24-
/// Set during backend setup when managed agents are eligible for launch
25-
/// restore. `apply_workspace` consumes it after installing the workspace
26-
/// relay and identity, so agents never start against the fallback relay.
24+
/// One-shot gate consumed by the first `apply_workspace` after boot to
25+
/// restore Share Compute (mesh-llm). Agent activation itself is governed
26+
/// by `managed_agent_activation_enabled` + `activated_agent_relays` and
27+
/// runs on every `apply_workspace`.
2728
pub managed_agent_restore_pending: AtomicBool,
29+
/// Session-wide gate for lazy agent activation. Set during backend setup
30+
/// only when the boot-time repos-dir and identity-recovery safety checks
31+
/// allow agents to start; when false, no `apply_workspace` may auto-start
32+
/// agents this session.
33+
pub managed_agent_activation_enabled: AtomicBool,
34+
/// Normalized relay URLs whose workspaces were already activated this app
35+
/// session. A workspace's agents lazily start on the first visit and at
36+
/// most once per session — bouncing A→B→A must not resurrect agents the
37+
/// user manually stopped in A. Never stops agents: switching away leaves
38+
/// the other workspace's agents running against their own relay.
39+
pub activated_agent_relays: Mutex<HashSet<String>>,
2840
/// One-shot gate: first `apply_workspace` runs `pin_blank_agent_relays`.
2941
pub agent_relay_stamp_pending: AtomicBool,
3042
/// Shared shutdown signal checked by launch-time agent restoration.
@@ -163,6 +175,8 @@ pub fn build_app_state() -> AppState {
163175
.unwrap_or_else(|_| reqwest::Client::new()),
164176
relay_url_override: Mutex::new(None),
165177
managed_agent_restore_pending: AtomicBool::new(false),
178+
managed_agent_activation_enabled: AtomicBool::new(false),
179+
activated_agent_relays: Mutex::new(HashSet::new()),
166180
agent_relay_stamp_pending: AtomicBool::new(true),
167181
shutdown_started: AtomicBool::new(false),
168182
managed_agent_restore_transition: Mutex::new(()),

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

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ use tauri::{AppHandle, Emitter, Manager, State};
55

66
use crate::app_state::AppState;
77
use crate::managed_agents::{
8-
effective_repos_dir, ensure_repos_symlink, load_managed_agents, nest_dir,
9-
rebind_agent_relay_urls, restore_managed_agents_on_launch, save_managed_agents,
10-
stamp_blank_agent_relay_urls, try_regenerate_nest, write_persisted_repos_dir,
8+
activate_workspace_agents, effective_repos_dir, ensure_repos_symlink, load_managed_agents,
9+
nest_dir, rebind_agent_relay_urls, save_managed_agents, stamp_blank_agent_relay_urls,
10+
try_regenerate_nest, write_persisted_repos_dir,
1111
};
1212
use crate::relay;
1313

@@ -107,6 +107,7 @@ pub async fn apply_workspace(
107107
app: AppHandle,
108108
) -> Result<(), String> {
109109
let restore_app = app.clone();
110+
let activation_relay_url = relay_url.clone();
110111
tokio::task::spawn_blocking(move || {
111112
let state = app.state::<AppState>();
112113

@@ -192,26 +193,33 @@ pub async fn apply_workspace(
192193
.await
193194
.map_err(|e| format!("spawn_blocking failed: {e}"))??;
194195

195-
let state = restore_app.state::<AppState>();
196-
if state
196+
// Lazy per-workspace activation: runs on EVERY apply, and self-gates so
197+
// each workspace's agents start at most once per app session (launch
198+
// restore is simply the first activation). Nothing is stopped on switch —
199+
// the previous workspace's agents keep running against their own relay.
200+
// The one-shot restore flag is consumed only for Share Compute (mesh-llm),
201+
// which must be up before its dependent agents spawn.
202+
#[cfg(feature = "mesh-llm")]
203+
let mesh_restore_pending = restore_app
204+
.state::<AppState>()
197205
.managed_agent_restore_pending
198-
.swap(false, Ordering::AcqRel)
199-
{
200-
let app = restore_app.clone();
201-
tauri::async_runtime::spawn(async move {
202-
let state = app.state::<AppState>();
203-
#[cfg(feature = "mesh-llm")]
206+
.swap(false, Ordering::AcqRel);
207+
let app = restore_app.clone();
208+
tauri::async_runtime::spawn(async move {
209+
let state = app.state::<AppState>();
210+
#[cfg(feature = "mesh-llm")]
211+
if mesh_restore_pending {
204212
if let Err(error) = crate::commands::mesh_llm::restore_mesh_sharing(&app, &state).await
205213
{
206214
eprintln!("buzz-desktop: failed to restore Share Compute: {error}");
207215
}
208-
if let Err(error) =
209-
restore_managed_agents_on_launch(&app, &state.shutdown_started).await
210-
{
211-
eprintln!("buzz-desktop: failed to restore managed agents: {error}");
212-
}
213-
});
214-
}
216+
}
217+
if let Err(error) =
218+
activate_workspace_agents(&app, &state.shutdown_started, &activation_relay_url).await
219+
{
220+
eprintln!("buzz-desktop: failed to activate workspace agents: {error}");
221+
}
222+
});
215223

216224
Ok(())
217225
}

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

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,7 @@ pub fn run() {
525525
// Backfill the pinned persona snapshot for any pre-existing agent
526526
// that predates the record-authoritative-spawn cutover (persona_id
527527
// set but no source_version). Must run before
528-
// restore_managed_agents_on_launch so no agent spawns from an empty
528+
// activate_workspace_agents so no agent spawns from an empty
529529
// snapshot. Synchronous and best-effort — a failure here must not
530530
// block launch, but a missing persona is logged loudly inside.
531531
if let Err(e) = backfill_persona_snapshots(&app_handle) {
@@ -654,16 +654,22 @@ pub fn run() {
654654
});
655655
}
656656

657-
// Defer launch-time agent restoration until `apply_workspace` has
658-
// installed the active workspace relay and identity. Starting here
659-
// would race React initialization and send agents whose saved record
660-
// has no relay override to the localhost fallback. Preserve the
661-
// boot-time repos and identity recovery safety gates by only marking
662-
// restoration pending when both allow it.
657+
// Defer agent activation until `apply_workspace` has installed a
658+
// workspace relay and identity. Starting here would race React
659+
// initialization and send agents whose saved record has no relay
660+
// override to the localhost fallback. Each workspace's agents then
661+
// lazily activate on its first visit (`activate_workspace_agents`);
662+
// the boot restore is simply the first activation. Preserve the
663+
// boot-time repos and identity recovery safety gates by only
664+
// enabling activation (and the one-shot mesh-llm restore) when
665+
// both allow it.
663666
if restore_agents && !recovery_mode {
664667
state
665668
.managed_agent_restore_pending
666669
.store(true, Ordering::Release);
670+
state
671+
.managed_agent_activation_enabled
672+
.store(true, Ordering::Release);
667673
}
668674

669675
// Periodic sweep: reap orphaned agents from dead instances every 60s.

0 commit comments

Comments
 (0)