Skip to main content

agentmux_srv_core/backend/blockcontroller/shell/
post_spawn.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What `start` does once the shell's PTY child exists: records it, registers the pane with
5//! jekt and seeds its working directory.
6
7use super::controller::ShellController;
8use crate::backend::obj::{self, MetaMapType};
9
10impl ShellController {
11    /// Registers the child's PID with the per-pane metrics and records its spawn metadata.
12    pub(super) fn record_spawn(
13        &self,
14        pid: Option<u32>,
15        is_agent: bool,
16        prog_name: &str,
17        agent_id: Option<String>,
18        spawn_ts_ms: i64,
19    ) {
20        {
21            let mut inner = self.inner.lock().unwrap();
22            if let Some(pid) = pid {
23                super::super::pidregistry::register(&self.block_id, pid);
24                if is_agent {
25                    crate::backend::process_tracker::registry::track_spawned_agent(
26                        &self.block_id,
27                        pid,
28                    );
29                } else {
30                    crate::backend::process_tracker::registry::track_spawned(&self.block_id, pid);
31                }
32                inner.child_pid = Some(pid);
33            }
34            inner.spawn_ts_ms = Some(spawn_ts_ms);
35            inner.shell_name = prog_name.to_string();
36            inner.is_agent_pane = is_agent;
37            inner.agent_id = agent_id;
38        }
39    }
40
41    /// Maps `agent_id` to this pane in the jekt handler (and the cross-instance registry), so
42    /// jekt can deliver to this PTY without a separate register call.
43    pub(super) fn register_agent_with_jekt(&self, agent_id: &str) {
44        // Identity M2: a PTY pane has no `db_agents` row, so no UID —
45        // registered by name only, counted (spec §4.4.1 row 4).
46        match crate::backend::reactive::get_global_handler().register_agent_full(
47            agent_id,
48            &self.block_id,
49            Some(&self.tab_id),
50            0,
51            None,
52            None,
53            "registration.no_uid.shell_pane",
54        ) {
55            Ok(()) => {
56                tracing::info!(
57                    block_id = %self.block_id,
58                    agent_id = %agent_id,
59                    "jekt: auto-registered"
60                );
61                // Also write to cross-instance file registry, and its
62                // host-global sibling (Tier 2b, issue #1916) — this
63                // auto-register path bypasses the HTTP register handler
64                // entirely, so it needs its own mirror call too.
65                if let Ok(local_url) = std::env::var("AGENTMUX_LOCAL_URL") {
66                    let data_dir = crate::backend::base::get_mux_data_dir();
67                    crate::backend::reactive::registry::write(
68                        &data_dir,
69                        agent_id,
70                        &local_url,
71                        &self.block_id,
72                    );
73                    crate::backend::reactive::registry::write_shared_from_env(
74                        agent_id,
75                        &local_url,
76                        &self.block_id,
77                    );
78                }
79            }
80            Err(e) => tracing::warn!(
81                block_id = %self.block_id,
82                agent_id = %agent_id,
83                error = %e,
84                "jekt: auto-register failed"
85            ),
86        }
87    }
88
89    /// Seeds `cmd:cwd` in the block meta right after spawn so drag-and-drop works before the shell
90    /// emits its first OSC 7 (or for shells without integration).
91    pub(super) fn seed_cmd_cwd(&self, cwd: &str, remote: bool) {
92        tracing::info!(
93            block_id = %self.block_id,
94            mstore_present = self.mstore.is_some(),
95            event_bus_present = self.event_bus.is_some(),
96            "[dnd-debug] pre-seed state after spawn"
97        );
98
99        // Seed cmd:cwd in block meta immediately after spawn so drag-and-drop works
100        // before the shell emits its first OSC 7 (or for shells without integration).
101        // Not for an SSH, WSL or container pane: its cwd is a path on the other side, and
102        // this machine's directory would be sent there on the next launch.
103        if let Some(store) = self.mstore.as_ref().filter(|_| !remote) {
104            let effective_cwd = cwd.to_string(); // spawn_cwd: never empty for a local shell
105            tracing::debug!(block_id = %self.block_id, cwd = %effective_cwd, "seeding cmd:cwd");
106            if !effective_cwd.is_empty() {
107                let oref_str = format!("block:{}", self.block_id);
108                let mut meta_update = MetaMapType::new();
109                meta_update.insert(
110                    super::super::META_KEY_CMD_CWD.to_string(),
111                    serde_json::Value::String(effective_cwd),
112                );
113                // Only set if not already populated — don't clobber a restored session CWD
114                match store.must_get::<crate::backend::obj::Block>(&self.block_id) {
115                    Ok(block)
116                        if obj::meta_get_string(
117                            &block.meta,
118                            super::super::META_KEY_CMD_CWD,
119                            "",
120                        )
121                        .is_empty() =>
122                    {
123                        match crate::backend::wcore::object_meta::update_object_meta(
124                            store,
125                            &oref_str,
126                            &meta_update,
127                        ) {
128                            Ok(()) => {
129                                // Re-read updated block and broadcast obj:update so the
130                                // frontend Jotai atom refreshes (update_object_meta only writes
131                                // to SQLite — it does NOT send a WebSocket event on its own).
132                                if let Ok(updated_block) =
133                                    store.must_get::<crate::backend::obj::Block>(&self.block_id)
134                                {
135                                    if let Some(ref event_bus) = self.event_bus {
136                                        let update = obj::MuxObjUpdate {
137                                            updatetype: "update".into(),
138                                            otype: "block".into(),
139                                            oid: self.block_id.clone(),
140                                            obj: Some(obj::mux_obj_to_value(&updated_block)),
141                                        };
142                                        event_bus.broadcast_event(
143                                            &crate::backend::eventbus::EventBus::typed_ws_event::<
144                                                crate::backend::mps_events::MuxObjUpdated,
145                                            >(
146                                                &update, oref_str.clone()
147                                            ),
148                                        );
149                                        tracing::info!(block_id = %self.block_id, "cmd:cwd seeded and broadcast to frontend");
150                                    } else {
151                                        tracing::warn!(block_id = %self.block_id, "cmd:cwd written to store but no event_bus to broadcast — frontend won't update");
152                                    }
153                                }
154                            }
155                            Err(e) => {
156                                tracing::warn!(block_id = %self.block_id, error = %e, "failed to seed cmd:cwd in store");
157                            }
158                        }
159                    }
160                    Ok(_) => {
161                        tracing::debug!(block_id = %self.block_id, "cmd:cwd already set, skipping seed");
162                    }
163                    Err(e) => {
164                        tracing::warn!(block_id = %self.block_id, error = %e, "failed to read block for cmd:cwd seed");
165                    }
166                }
167            }
168        }
169    }
170}