Skip to content

Commit ff16a80

Browse files
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7wpfleger96
andcommitted
fix(desktop): pass-2 review corrections (round 3) — captured respawn, behavioral tests, residue
Global-config respawn: replace live-scope wrappers with one transition epoch. restart_under_captured_epoch acquires managed_agent_runtime_transition + managed_agents_store_lock, validates captured generation, stops, builds a captured spawn context (records/personas/global config/owner hex/scope_id from captured_scope), spawns/registers, saves — no live wrapper past the stop. persist_last_error takes captured_scope, validates generation under its own acquired store lock, never called while that lock is held, fails closed on poison. Two tauri::test::mock_app() tests: fresh-scope no-runtime → Skipped (proves generation guard passes + path proceeds), stale-scope → Skipped at generation step (switch-between-stop-and-spawn test, calls production fn). Behavioral tests on production paths: tauri = { version = "2", features = ["test"] } added to dev-dependencies. compensate_drain_for extracted with injectable start_fn; tests call it directly (compensate_drain_for is the production core). capture_agent_snapshot_import_entry and capture_team_snapshot_import_entry extracted as testable entry guards; tests call the real production functions (no-scope reject, owner-mismatch reject, matching-owner passes + relay verified, stale-generation rejects validate_scope_generation). registerNestNotifications extracted from useNestNotifications; test imports and calls the real function, asserts all three event registrations, workspace-degraded toast payload, unlisten cleanup per event. fail_if_client_mesh_active and mesh_stop_client tested via tauri::test::mock_builder() with real AppHandle (no-runtime, client-runtime, no-runtime stop paths). Generalized fail_if_client_mesh_active and mesh_stop_client to tauri::Runtime to allow mock_app usage. Residue: _compensation_gate_removed placeholder deleted from AppState. identity.rs:346-348 comment corrected (guard passed by value, not dropped). mesh_llm_scope.rs:59-64 stale re-arm comment replaced with accurate Option A note. Duplicate generation bump at identity.rs:544 removed (clear_active_scope calls next_scope_generation internally; no second bump needed). File-size gate: AgentSnapshotImportEntry + capture_agent_snapshot_import_entry extracted to import_entry.rs (import.rs: 995 lines); TeamSnapshotImportEntry + capture_team_snapshot_import_entry extracted to team_snapshot_entry.rs (team_snapshot.rs: 997 lines). Both within the 1000-line ratchet. Co-authored-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]>
1 parent 6dc4e29 commit ff16a80

30 files changed

Lines changed: 1696 additions & 923 deletions

‎desktop/src-tauri/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ strip-ansi-escapes = "0.2"
146146
tracing = "0.1"
147147

148148
[dev-dependencies]
149+
tauri = { version = "2", features = ["test"] }
149150
tauri-utils = "2"
150151
# `test-util` enables tokio's paused-clock (`start_paused`) so the relay
151152
# admission gate tests can assert exact wait durations without real sleeps.

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

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,6 @@ pub struct AppState {
4646
/// Never perform network I/O while holding this lock.
4747
pub managed_agent_runtime_transition: Mutex<()>,
4848
pub managed_agents_store_lock: Mutex<()>,
49-
/// `compensate_drain` reacquires `managed_agent_runtime_transition` and
50-
/// `managed_agents_store_lock` directly and holds them across all journal
51-
/// restarts, so no concurrent start or reconcile can interleave. The old
52-
/// AtomicBool gate is removed; this field is a zero-cost placeholder that
53-
/// preserves struct layout stability during this refactor pass.
54-
#[allow(dead_code)]
55-
_compensation_gate_removed: (),
5649
pub channel_templates_store_lock: Mutex<()>,
5750
pub managed_agent_processes: Mutex<HashMap<ManagedAgentRuntimeKey, ManagedAgentPairRuntime>>,
5851
pub huddle_state: Mutex<HuddleState>,
@@ -227,7 +220,6 @@ pub fn build_app_state() -> AppState {
227220
workspace_transition: AsyncMutex::new(()),
228221
active_agent_scope: Mutex::new(None),
229222
managed_agents_store_lock: Mutex::new(()),
230-
_compensation_gate_removed: (),
231223
channel_templates_store_lock: Mutex::new(()),
232224
managed_agent_processes: Mutex::new(HashMap::new()),
233225
session_config_cache: Mutex::new(HashMap::new()),

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

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,9 @@ fn test_live_import_with_active_scope_clears_scope_and_bumps_generation() {
6464

6565
let generation_before_import = crate::managed_agents::scope::current_scope_generation();
6666

67-
// Simulate the live-import path: clear scope and bump generation.
67+
// Simulate the live-import path: clear scope. `clear_active_scope()`
68+
// bumps the generation internally — no additional bump needed.
6869
state.clear_active_scope();
69-
// `clear_active_scope` calls `next_scope_generation()` internally;
70-
// bumping again here models the extra call in import_identity.
71-
crate::managed_agents::scope::next_scope_generation();
7270

7371
let generation_after_import = crate::managed_agents::scope::current_scope_generation();
7472

@@ -90,9 +88,9 @@ fn test_live_import_with_active_scope_clears_scope_and_bumps_generation() {
9088
/// from identity import. Verifies the claim ledger cannot be written without an
9189
/// explicit relay selection.
9290
///
93-
/// This test verifies the structural invariant: `clear_active_scope()` and
94-
/// `next_scope_generation()` (the two operations identity import performs) do
95-
/// not touch the filesystem claim ledger.
91+
/// This test verifies the structural invariant: `clear_active_scope()` —
92+
/// the single operation identity import performs — does not touch the
93+
/// filesystem claim ledger.
9694
#[test]
9795
fn test_fallback_relay_never_claims_during_identity_import() {
9896
let tmp = tempfile::tempdir().unwrap();
@@ -105,9 +103,9 @@ fn test_fallback_relay_never_claims_during_identity_import() {
105103
std::fs::write(agents_dir.join("managed-agents.json"), b"[]").unwrap();
106104
std::fs::write(agents_dir.join("teams.json"), b"[]").unwrap();
107105

108-
// Simulate the import-before-first-apply path: clear + bump.
106+
// Simulate the import-before-first-apply path: clear scope.
107+
// `clear_active_scope()` bumps the generation internally.
109108
state.clear_active_scope();
110-
crate::managed_agents::scope::next_scope_generation();
111109

112110
// No claim file must exist: the fallback JSON claim path.
113111
let fallback_claim = tmp.path().join("agents").join("legacy-claim.json");

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

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -266,9 +266,7 @@ async fn ensure_relay_mesh_for_record(
266266

267267
#[path = "agents_scoped.rs"]
268268
mod scoped;
269-
pub(crate) use scoped::{
270-
start_local_agent_pairs_with_preflight, start_local_agent_pairs_with_preflight_at,
271-
};
269+
pub(crate) use scoped::start_local_agent_pairs_with_preflight;
272270

273271
pub(super) async fn start_local_agent_with_preflight(
274272
app: &AppHandle,

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

Lines changed: 0 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -97,91 +97,3 @@ pub(crate) async fn start_local_agent_pairs_with_preflight(
9797
&crate::managed_agents::load_global_agent_config(app).unwrap_or_default(),
9898
)
9999
}
100-
101-
/// Scoped variant of [`start_local_agent_pairs_with_preflight`]: uses captured
102-
/// `definitions_dir` for all reads and writes so a concurrent workspace switch
103-
/// cannot redirect operations to the new scope.
104-
///
105-
/// Validates scope generation inside the store lock before writing, so a switch
106-
/// between the generation check at the call site and the actual write is caught.
107-
///
108-
/// Called from `global_agent_config.rs` respawn path where a `definitions_dir`
109-
/// was captured before the stop phase.
110-
pub(crate) async fn start_local_agent_pairs_with_preflight_at(
111-
app: &super::AppHandle,
112-
state: &super::AppState,
113-
pubkey: &str,
114-
relay_urls: &[String],
115-
captured_scope: &crate::managed_agents::scope::WorkspaceAgentScope,
116-
) -> Result<(), String> {
117-
let definitions_dir = &captured_scope.definitions_dir;
118-
119-
let record_snapshot = {
120-
let _store_guard = state
121-
.managed_agents_store_lock
122-
.lock()
123-
.map_err(|e| e.to_string())?;
124-
crate::managed_agents::storage::load_managed_agents_at(definitions_dir)?
125-
.into_iter()
126-
.find(|record| record.pubkey == pubkey)
127-
.ok_or_else(|| format!("agent {pubkey} not found in captured scope"))?
128-
};
129-
if record_snapshot.backend != super::BackendKind::Local {
130-
return Err(format!("agent {pubkey} is not a local agent"));
131-
}
132-
let personas_for_preflight =
133-
crate::managed_agents::load_personas_at(definitions_dir).unwrap_or_default();
134-
let global_for_preflight =
135-
crate::managed_agents::global_config::load_global_agent_config_at(definitions_dir)
136-
.unwrap_or_default();
137-
let mesh_model_id =
138-
crate::managed_agents::effective_config::resolve_effective_relay_mesh_model_id(
139-
&record_snapshot,
140-
&personas_for_preflight,
141-
&global_for_preflight,
142-
);
143-
super::ensure_relay_mesh_for_record(app, mesh_model_id.as_deref(), false).await?;
144-
145-
{
146-
let _store_guard = state
147-
.managed_agents_store_lock
148-
.lock()
149-
.map_err(|e| e.to_string())?;
150-
// Revalidate generation under the store lock — the workspace may have
151-
// switched between the preflight check above and this write.
152-
crate::managed_agents::scope::validate_scope_generation(captured_scope)
153-
.map_err(|e| format!("start_local_agent_pairs_with_preflight_at: {e}"))?;
154-
let mut records = crate::managed_agents::storage::load_managed_agents_at(definitions_dir)?;
155-
let record = super::find_managed_agent_mut(&mut records, pubkey)?;
156-
let personas = crate::managed_agents::load_personas_at(definitions_dir).unwrap_or_default();
157-
if let Some(persona_id) = record.persona_id.clone() {
158-
if let Some(persona) = personas.iter().find(|persona| persona.id == persona_id) {
159-
crate::managed_agents::persona_events::apply_persona_snapshot(record, persona);
160-
record.updated_at = crate::util::now_iso();
161-
}
162-
}
163-
crate::managed_agents::storage::save_managed_agents_at(definitions_dir, &records)?;
164-
if let Some(saved_record) = records.iter().find(|record| record.pubkey == pubkey) {
165-
super::retain_managed_agent_pending(app, state, saved_record);
166-
}
167-
}
168-
169-
let mut errors = Vec::new();
170-
for relay_url in relay_urls {
171-
if let Err(error) = crate::managed_agents::start_managed_agent_runtime_pair_lazy(
172-
pubkey.to_string(),
173-
relay_url.clone(),
174-
app.clone(),
175-
) {
176-
errors.push(format!("{relay_url}: {error}"));
177-
}
178-
}
179-
if !errors.is_empty() {
180-
Err(format!(
181-
"failed to restart one or more managed-agent runtime pairs: {}",
182-
errors.join("; ")
183-
))
184-
} else {
185-
Ok(())
186-
}
187-
}

0 commit comments

Comments
 (0)