Skip to main content

agentmux_srv_core/backend/blockcontroller/
core.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared helpers used by all block controllers (persistent, subprocess, acp).
5//!
6//! Extracted to avoid copy-paste across the four controller files. Each
7//! controller keeps only its transport-specific logic (PTY / stream-json / ACP)
8//! and delegates the common mechanics here.
9
10use std::collections::HashMap;
11use std::sync::Arc;
12
13use crate::backend::eventbus::EventBus;
14use crate::backend::storage::store::Store;
15
16/// Block metadata key for the persisted agent session ID.
17/// Used by the "My Agents" reattach path on the frontend: after a tab reload
18/// the picker reads `block.meta["agent:sessionid"]` and passes it as the
19/// `--resume` value so the CLI picks up the prior conversation.
20pub const META_SESSION_ID: &str = "agent:sessionid";
21
22/// Block metadata key for the last classified agent failure.
23/// Written on every non-zero / in-band-error exit; cleared on clean success.
24/// The frontend reads this on pane mount so the recovery banner survives
25/// tab switches and page reloads without requiring the MPS event to be
26/// received in real time.
27pub const META_LAST_FAILURE: &str = "agent:last_failure";
28/// The field of the stored failure that says when it was recorded (unix ms).
29pub(crate) const META_FAILURE_AT_MS: &str = "atMs";
30/// Where a pane's model API calls go when that is not srv's own address: `{service, url}`
31/// (`connectivity::endpoint_meta`). Absent for a pane that calls the default.
32pub(crate) const META_API_ENDPOINT: &str = "agent:api_endpoint";
33
34/// Expand the working directory, create it if missing, set it on `cmd`, and
35/// apply all env-var overrides from `env_vars`.
36///
37/// Call this from each controller's spawn routine BEFORE any transport-specific
38/// `Command` flags (e.g. `CREATE_NO_WINDOW` on Windows, which must come after
39/// the env setup in some implementations).
40pub(crate) fn apply_working_dir(
41    cmd: &mut tokio::process::Command,
42    block_id: &str,
43    working_dir: &str,
44    env_vars: &HashMap<String, String>,
45) {
46    if !working_dir.is_empty() {
47        let expanded_dir = expand_home_dir(working_dir);
48        let dir_path = std::path::Path::new(&expanded_dir);
49        if !dir_path.exists() {
50            if let Err(e) = std::fs::create_dir_all(dir_path) {
51                tracing::warn!(
52                    block_id = %block_id,
53                    dir = %expanded_dir,
54                    error = %e,
55                    "failed to create working directory",
56                );
57            }
58        }
59        if dir_path.exists() {
60            cmd.current_dir(&expanded_dir);
61            // Warn loudly if the agent workspace contains a nested .git (e.g.
62            // an unintended `git clone` inside ~/.agentmux/agents/). A stale
63            // nested clone can confuse agents into reading old code and waste
64            // gigabytes of disk. Single fs::metadata call — no directory walk.
65            let looks_like_agent_workspace = expanded_dir.contains("/.agentmux/agents/")
66                || expanded_dir.contains("\\.agentmux\\agents\\");
67            if looks_like_agent_workspace {
68                let git_dir = dir_path.join(".git");
69                if git_dir.exists() {
70                    tracing::warn!(
71                        block_id = %block_id,
72                        cwd = %expanded_dir,
73                        ".git detected inside agent workspace — this is usually \
74                         an unintended nested clone and can waste gigabytes of \
75                         disk. Clean up with: rm -rf {}/.git",
76                        expanded_dir,
77                    );
78                }
79            }
80        }
81    }
82    // Strip this instance's identity before applying the caller's overlay.
83    // `tokio::process::Command` inherits srv's environment wholesale, so an
84    // agent pane — and every process the agent launches from its shell tool —
85    // otherwise receives this instance's channel, data dir and cache dir.
86    // See `backend::pane_env`.
87    crate::backend::pane_env::sanitize_process_command(cmd);
88
89    for (k, v) in env_vars {
90        // A login variable the endpoint step emptied is taken out of the child itself: the inherited copy of
91        // srv's own environment is the person's, and must not reach a server the agent was pointed at.
92        if v.is_empty() && crate::backend::spawn_env::endpoint::is_account_variable(k) {
93            cmd.env_remove(k);
94            continue;
95        }
96        let expanded = crate::backend::base::expand_home_dir_safe(v);
97        cmd.env(k, expanded.to_string_lossy().as_ref());
98    }
99}
100
101/// Expand a leading `~/` or bare `~` to the user's home directory.
102pub fn expand_home_dir(dir: &str) -> String {
103    if let Some(under_override) = crate::backend::base::expand_under_home_override(dir) {
104        return under_override.to_string_lossy().to_string();
105    }
106    if dir.starts_with("~/") || dir == "~" {
107        if let Some(home) = dirs::home_dir() {
108            return home
109                .join(dir.trim_start_matches("~/"))
110                .to_string_lossy()
111                .to_string();
112        }
113    }
114    dir.to_string()
115}
116
117/// Persist a newly captured session ID to block metadata and broadcast the
118/// `waveobj:update` event so the frontend reflects the change immediately.
119///
120/// Every controller that captures a session id goes through this one path
121/// (persistent/stdout_reader.rs and stderr_reader.rs, subprocess/host_spawn.rs
122/// and container_spawn.rs, acp.rs, app_server_controller.rs); ACP used to only set
123/// `inner.session_id` in memory.
124///
125/// Also writes through to the matching `db_agent_instances` row's
126/// `session_id` column (SPEC_PANE_CLOSE_REOPEN_CONTINUITY_GUARANTEE_2026_07_27.md
127/// §4.1). Without this, that column was set to `""` at instance creation and
128/// never updated again in production — `ListRecentSessionsCommand` prefers
129/// the local row over the shared registry whenever both exist, so the "My
130/// Agents" picker's reattach flow (`AgentPicker.tsx`'s `handleReattach`) was
131/// handed an empty session id even mid-session, and — per
132/// `agent-model.ts`'s own documented invariant that an empty
133/// `continueSessionId` clears `agent:sessionid` on the new block — silently
134/// started a genuinely fresh conversation instead of resuming. Best-effort:
135/// logs and continues on failure, since the block-meta write above (the
136/// live-turn source of truth) already succeeded.
137///
138/// No-ops silently when `mstore` is `None` (e.g. in unit tests that don't wire
139/// up a store).
140pub(crate) fn persist_session_id(
141    block_id: &str,
142    sid: &str,
143    mstore: &Option<Arc<Store>>,
144    event_bus: &Option<Arc<EventBus>>,
145) {
146    let Some(ref store) = mstore else {
147        return;
148    };
149    let oref_str = format!("block:{}", block_id);
150    let mut meta_update = crate::backend::obj::MetaMapType::new();
151    meta_update.insert(
152        META_SESSION_ID.to_string(),
153        serde_json::Value::String(sid.to_string()),
154    );
155    match crate::backend::wcore::object_meta::update_object_meta(store, &oref_str, &meta_update) {
156        Err(e) => {
157            tracing::warn!(
158                block_id = %block_id,
159                error = %e,
160                "failed to persist agent:sessionid",
161            );
162        }
163        Ok(_) => {
164            sync_instance_session_id(store, block_id, sid);
165
166            let Some(ref event_bus) = event_bus else {
167                return;
168            };
169            broadcast_block_update(store, event_bus, block_id);
170        }
171    }
172}
173
174/// Forget the session a pane would resume, for a pane with no controller (a stopped agent): its next start has no id
175/// to resume and begins a new session. A running pane's controller does this itself in `start_fresh_session`, which
176/// also stops its process; this is for the pane that has nothing to stop.
177pub fn forget_saved_session(block_id: &str, mstore: &Arc<Store>, event_bus: &Arc<EventBus>) {
178    persist_session_id(block_id, "", &Some(mstore.clone()), &Some(event_bus.clone()));
179}
180
181/// Write `sid` into the `db_agent_instances` row for `block_id`, if one
182/// exists. Best-effort — no-ops (with a debug log, not a warn — most turns
183/// on a block with no matching instance row are expected, e.g. terminal
184/// panes never have one) when there's nothing to update.
185fn sync_instance_session_id(store: &Arc<Store>, block_id: &str, sid: &str) {
186    let instance = match store.instance_get_by_block_id(block_id) {
187        Ok(Some(i)) => i,
188        Ok(None) => return,
189        Err(e) => {
190            tracing::debug!(
191                block_id = %block_id,
192                error = %e,
193                "sync_instance_session_id: instance lookup failed"
194            );
195            return;
196        }
197    };
198    let upd = crate::backend::storage::InstanceUpdate {
199        session_id: Some(sid.to_string()),
200        ..Default::default()
201    };
202    if let Err(e) = store.instance_update_partial(&instance.id, &upd) {
203        tracing::warn!(
204            block_id = %block_id,
205            instance_id = %instance.id,
206            error = %e,
207            "sync_instance_session_id: failed to write session_id"
208        );
209    }
210}
211
212/// What a finished turn says about its provider's model API (`connectivity`). Called where a turn ends, not from
213/// [`persist_last_failure`], which is also called to clear a stored failure when no request was made. Claude's own
214/// frames report theirs.
215pub(crate) fn report_provider_turn(
216    block_id: &str,
217    failure: Option<&crate::agents::failure::AgentFailure>,
218    mstore: &Option<Arc<Store>>,
219) {
220    let Some(store) = mstore else { return };
221    if let Ok(block) = store.must_get::<crate::backend::obj::Block>(block_id) {
222        let provider = crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "");
223        let url = block.meta.get(META_API_ENDPOINT).and_then(|v| v.get("url")).and_then(|v| v.as_str());
224        crate::connectivity::observe_provider_turn(&provider, failure, url);
225    }
226}
227
228/// Works out, as a pane's CLI starts, which model API address it was given (`env` is what the process
229/// gets), tracks that address as its own service when it is not srv's, and keeps it in the block's meta
230/// for the pane and for the turn reports. Returns the service the pane's calls go to, or `None` for a
231/// provider srv doesn't track.
232pub(crate) fn attach_model_api(
233    block_id: &str,
234    env: &HashMap<String, String>,
235    mstore: &Option<Arc<Store>>,
236    event_bus: &Option<Arc<EventBus>>,
237) -> Option<crate::connectivity::Service> {
238    let store = mstore.as_ref()?;
239    let block = store.must_get::<crate::backend::obj::Block>(block_id).ok()?;
240    let provider = crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "");
241    let api = crate::connectivity::model_api_of(&provider)?;
242    let service = crate::connectivity::service_for_env(api, env);
243    let endpoint = crate::connectivity::endpoint_meta(&service);
244    let stored = block.meta.get(META_API_ENDPOINT).filter(|v| !v.is_null());
245    if endpoint.as_ref() != stored {
246        let mut update = crate::backend::obj::MetaMapType::new();
247        update.insert(META_API_ENDPOINT.to_string(), endpoint.unwrap_or(serde_json::Value::Null));
248        match crate::backend::wcore::object_meta::update_object_meta(store, &format!("block:{block_id}"), &update) {
249            Ok(_) => {
250                if let Some(bus) = event_bus {
251                    broadcast_block_update(store, bus, block_id);
252                }
253            }
254            Err(e) => tracing::warn!(block_id = %block_id, error = %e, "failed to persist agent:api_endpoint"),
255        }
256    }
257    if matches!(service, crate::connectivity::Service::ModelApiAt(..)) {
258        crate::connectivity::track(service.clone());
259    }
260    Some(service)
261}
262
263/// Persist or clear the last agent failure in block metadata.
264///
265/// Pass `Some(failure)` on a failed exit to write `agent:last_failure` into the
266/// block's meta so the pane can recover the recovery banner on any future load
267/// without needing the ephemeral MPS event. Pass `None` on a clean exit to
268/// remove the key (setting it to JSON null triggers `merge_meta`'s delete path).
269/// Broadcasts a `waveobj:update` so active frontend subscribers see the change
270/// immediately via the block atom, not just on next full load.
271pub fn persist_last_failure(
272    block_id: &str,
273    failure: Option<&crate::agents::failure::AgentFailure>,
274    mstore: &Option<Arc<Store>>,
275    event_bus: &Option<Arc<EventBus>>,
276) {
277    let Some(ref store) = mstore else {
278        return;
279    };
280    // On a clean exit (failure=None), only write null (which merge_meta uses to
281    // delete the key) if the key actually exists — otherwise every successful
282    // turn would trigger a redundant DB write + waveobj:update broadcast.
283    if failure.is_none() {
284        let key_exists = store
285            .must_get::<crate::backend::obj::Block>(block_id)
286            .ok()
287            .and_then(|b| b.meta.get(META_LAST_FAILURE).cloned())
288            .map(|v| !v.is_null())
289            .unwrap_or(false);
290        if !key_exists {
291            return;
292        }
293    }
294    // Every classified agent failure gets exactly one log line, here at the
295    // shared choke point rather than at the call sites. Deliberately does not
296    // enumerate or count them: a draft of the accompanying spec said "three",
297    // review found more, a recount said "nine", and review caught that the
298    // recount was wrong too. Every path funnels through this function, so this
299    // covers them all — including the ones nobody counted correctly, and the
300    // next one added.
301    //
302    // Before this, a classified failure left NO trace in the srv log at all:
303    // none of those sites logged, and the only logged classification was
304    // `agents/runner.rs`'s "agent run failed", which is a different path that a
305    // controller-driven turn never takes. That made a whole class of question
306    // unanswerable from logs — "did my cron agent hit a 429 overnight?" had no
307    // answer, and an empty grep looked like "it never happens" rather than
308    // "it is never recorded". See
309    // docs/specs/SPEC_HEADLESS_TRANSIENT_RETRY_2026_08_31.md §Phase 0.
310    //
311    // A usage limit carries when it lifts, from the provider's own report
312    // (`agents::limit_reset`), here too so every path stores it.
313    let enriched = failure.map(|f| crate::agents::limit_reset::with_reset(block_id, f));
314    let failure = enriched.as_ref();
315    // A usage limit with a known reset gets its wake (`limit_wake`).
316    if let Some(f) = failure {
317        crate::backend::limit_wake::on_failure(block_id, f, store);
318    }
319    // Logged only for `Some` — this is also called with `None` after every
320    // clean turn, and that is not an event worth a line.
321    if let Some(f) = failure {
322        tracing::warn!(
323            target: "agent-failure",
324            block_id = %block_id,
325            code = ?f.code,
326            retryable = f.retryable,
327            resets_at_ms = ?f.resets_at_ms,
328            "agent failure classified: {}",
329            f.title,
330        );
331    }
332
333    let oref_str = format!("block:{}", block_id);
334    let mut meta_update = crate::backend::obj::MetaMapType::new();
335    let val = match failure {
336        Some(f) => match serde_json::to_value(f) {
337            Ok(mut v) => {
338                // When it was recorded, so the agent's state has a `since` that survives a restart;
339                // the same failure hit again keeps the first time.
340                let first_at = store
341                    .must_get::<crate::backend::obj::Block>(block_id)
342                    .ok()
343                    .and_then(|b| b.meta.get(META_LAST_FAILURE).cloned())
344                    .filter(|old| old.get("code") == v.get("code"))
345                    .and_then(|old| old.get(META_FAILURE_AT_MS).cloned());
346                if let Some(o) = v.as_object_mut() {
347                    o.insert(
348                        META_FAILURE_AT_MS.to_string(),
349                        first_at.unwrap_or_else(|| serde_json::json!(agentmux_common::time::now_ms_u64())),
350                    );
351                }
352                v
353            }
354            Err(e) => {
355                tracing::warn!(
356                    block_id = %block_id,
357                    error = %e,
358                    "failed to serialize AgentFailure for agent:last_failure — skipping meta write",
359                );
360                return;
361            }
362        },
363        None => serde_json::Value::Null, // null → merge_meta removes the key
364    };
365    meta_update.insert(META_LAST_FAILURE.to_string(), val);
366    match crate::backend::wcore::object_meta::update_object_meta(store, &oref_str, &meta_update) {
367        Err(e) => {
368            tracing::warn!(
369                block_id = %block_id,
370                error = %e,
371                "failed to persist agent:last_failure",
372            );
373        }
374        Ok(_) => {
375            if failure.is_none() {
376                // A cleared failure can free held messages (a limited agent's clean turn).
377                crate::backend::reactive::held_jekt_wake().notify_one();
378            }
379            let Some(ref bus) = event_bus else {
380                return;
381            };
382            broadcast_block_update(store, bus, block_id);
383        }
384    }
385}
386
387/// Broadcast the block's current state as a `waveobj:update` on `block:<id>`,
388/// so an open pane sees a meta write live. Does nothing if the block can't be read.
389pub fn broadcast_block_update(store: &Store, event_bus: &EventBus, block_id: &str) {
390    let Ok(block) = store.must_get::<crate::backend::obj::Block>(block_id) else {
391        return;
392    };
393    let update = crate::backend::obj::MuxObjUpdate {
394        updatetype: "update".into(),
395        otype: "block".into(),
396        oid: block_id.to_string(),
397        obj: Some(crate::backend::obj::mux_obj_to_value(&block)),
398    };
399    event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::MuxObjUpdated>(&update, format!("block:{block_id}")));
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405    use crate::backend::obj::{Block, MetaMapType};
406    use crate::backend::storage::store::AgentDefinition;
407
408    /// Minimal definition satisfying `db_agent_instances`'s FK on
409    /// `definition_id` — field values otherwise irrelevant to these tests.
410    fn sample_agent(id: &str) -> AgentDefinition {
411        AgentDefinition {
412            icon: "✦".to_string(),
413            ..crate::backend::storage::agents::test_agent_def(id, id, "claude", "host", 0, "")
414        }
415    }
416
417    /// A block for `provider` with the given extra meta, in a fresh store.
418    fn pane_of(provider: &str, extra: serde_json::Value) -> (Arc<Store>, String) {
419        let store = Arc::new(Store::open_in_memory().unwrap());
420        let block_id = "66666666-6666-6666-6666-666666666666".to_string();
421        let mut meta = MetaMapType::new();
422        meta.insert("view".to_string(), serde_json::json!("agent"));
423        meta.insert("agentProvider".to_string(), serde_json::json!(provider));
424        for (k, v) in extra.as_object().cloned().unwrap_or_default() {
425            meta.insert(k, v);
426        }
427        let mut block = Block { oid: block_id.clone(), parentoref: String::new(), version: 1, runtimeopts: None, stickers: None, meta, subblockids: None };
428        store.insert(&mut block).unwrap();
429        (store, block_id)
430    }
431
432    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
433        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
434    }
435
436    #[test]
437    fn a_pane_pointed_at_a_proxy_keeps_its_service_in_its_meta_and_is_tracked() {
438        let (store, block_id) = pane_of("claude", serde_json::json!({}));
439        let mstore = Some(store.clone());
440        let service = attach_model_api(&block_id, &env(&[("ANTHROPIC_BASE_URL", "https://proxy.example.com")]), &mstore, &None).unwrap();
441        assert_eq!(service.id(), "model_api:anthropic@proxy.example.com");
442        let block: Block = store.get(&block_id).unwrap().unwrap();
443        assert_eq!(
444            block.meta.get(META_API_ENDPOINT),
445            Some(&serde_json::json!({ "service": "model_api:anthropic@proxy.example.com", "url": "https://proxy.example.com" }))
446        );
447        assert!(
448            crate::connectivity::status().services.iter().any(|s| s.service == "model_api:anthropic@proxy.example.com"),
449            "its address is listed from the start, not only after a request"
450        );
451    }
452
453    #[test]
454    fn a_pane_moved_back_to_the_default_address_loses_the_entry() {
455        let (store, block_id) = pane_of("claude", serde_json::json!({ META_API_ENDPOINT: { "service": "model_api:anthropic@old.example.com", "url": "https://old.example.com" } }));
456        let mstore = Some(store.clone());
457        let service = attach_model_api(&block_id, &env(&[]), &mstore, &None).unwrap();
458        assert_eq!(service, crate::connectivity::Service::ModelApi(&crate::connectivity::ANTHROPIC));
459        let block: Block = store.get(&block_id).unwrap().unwrap();
460        assert!(block.meta.get(META_API_ENDPOINT).is_none_or(|v| v.is_null()));
461    }
462
463    #[test]
464    fn a_provider_srv_does_not_track_has_no_service() {
465        let (store, block_id) = pane_of("opencode", serde_json::json!({}));
466        assert!(attach_model_api(&block_id, &env(&[("ANTHROPIC_BASE_URL", "https://proxy.example.com")]), &Some(store), &None).is_none());
467    }
468
469    /// SPEC_PANE_CLOSE_REOPEN_CONTINUITY_GUARANTEE_2026_07_27.md §4.1: this
470    /// is the end-to-end assertion that `persist_session_id` (the live-turn
471    /// call site every controller uses) keeps `db_agent_instances.session_id`
472    /// current, not just the block's own `agent:sessionid` meta — closing the
473    /// gap where "My Agents"'s reattach flow saw a permanently-empty local
474    /// session id.
475    #[test]
476    fn persist_session_id_writes_through_to_the_instance_row() {
477        let store = Arc::new(Store::open_in_memory().unwrap());
478        let block_id = "55555555-5555-5555-5555-555555555555";
479        let mut block = Block {
480            oid: block_id.to_string(),
481            parentoref: String::new(),
482            version: 1,
483            runtimeopts: None,
484            stickers: None,
485            meta: {
486                let mut m = MetaMapType::new();
487                m.insert("view".to_string(), serde_json::json!("agent"));
488                m
489            },
490            subblockids: None,
491        };
492        store.insert(&mut block).unwrap();
493
494        let mut def = sample_agent("def-live");
495        store.agent_def_insert(&mut def).unwrap();
496
497        let inst = crate::backend::storage::agents::test_agent_instance("inst-live", "def-live", block_id, 1000);
498        store.instance_create(&inst).unwrap();
499
500        persist_session_id(block_id, "sess-abc", &Some(store.clone()), &None);
501
502        // Block meta: the pre-existing behavior.
503        let updated_block: Block = store.get(block_id).unwrap().unwrap();
504        assert_eq!(
505            updated_block.meta.get(META_SESSION_ID).and_then(|v| v.as_str()),
506            Some("sess-abc"),
507        );
508
509        // Instance row: the new write-through.
510        let updated_instance = store.instance_get_by_block_id(block_id).unwrap().unwrap();
511        assert_eq!(updated_instance.session_id, "sess-abc");
512    }
513
514    /// A block with no matching instance row (e.g. a terminal pane) must not
515    /// cause persist_session_id to error or panic — sync_instance_session_id
516    /// is best-effort and silently no-ops.
517    #[test]
518    fn persist_session_id_is_a_noop_for_a_block_with_no_instance_row() {
519        let store = Arc::new(Store::open_in_memory().unwrap());
520        let block_id = "66666666-6666-6666-6666-666666666666";
521        let mut block = Block {
522            oid: block_id.to_string(),
523            parentoref: String::new(),
524            version: 1,
525            runtimeopts: None,
526            stickers: None,
527            meta: MetaMapType::new(),
528            subblockids: None,
529        };
530        store.insert(&mut block).unwrap();
531
532        // Must not panic.
533        persist_session_id(block_id, "sess-xyz", &Some(store.clone()), &None);
534
535        let updated_block: Block = store.get(block_id).unwrap().unwrap();
536        assert_eq!(
537            updated_block.meta.get(META_SESSION_ID).and_then(|v| v.as_str()),
538            Some("sess-xyz"),
539            "block meta write still happens regardless of instance-row presence",
540        );
541    }
542}