Skip to main content

vtcode_core/subagents/controller_spawn_run/
background.rs

1use super::*;
2
3impl SubagentController {
4    pub(in crate::subagents) async fn background_status_for(&self, target: &str) -> Result<BackgroundSubprocessEntry> {
5        let state = self.state.read().await;
6        let record = state
7            .background_children
8            .get(target)
9            .ok_or_else(|| anyhow!("Unknown background subprocess {target}"))?;
10        Ok(record.build_status_entry())
11    }
12
13    pub(in crate::subagents) async fn ensure_background_record_running(
14        &self,
15        agent_name: &str,
16        stable_id: Option<&str>,
17        restart_attempts: u8,
18        overrides: Option<BackgroundLaunchOverrides>,
19    ) -> Result<BackgroundSubprocessEntry> {
20        let spec = self
21            .resolve_requested_spec(Some(agent_name))
22            .await
23            .with_context(|| format!("Failed to resolve background subagent '{agent_name}'"))?;
24        let record_id = stable_id
25            .map(ToOwned::to_owned)
26            .unwrap_or_else(|| background_record_id(agent_name));
27        let previous_record = {
28            let state = self.state.read().await;
29            state.background_children.get(&record_id).map(|record| {
30                (
31                    record.created_at,
32                    record.prompt.clone(),
33                    record.max_turns,
34                    record.model_override.clone(),
35                    record.reasoning_override.clone(),
36                )
37            })
38        };
39        let parent_session_id = self.parent_session_id.read().await.clone();
40        let session_id = format!(
41            "{}-{}-{}",
42            sanitize_component(parent_session_id.as_str()),
43            sanitize_component(record_id.as_str()),
44            Utc::now().format("%Y%m%dT%H%M%S%3fZ")
45        );
46        let exec_session_id = format!("exec-{session_id}");
47        let (created_at, previous_prompt, previous_max_turns, previous_model_override, previous_reasoning_override) =
48            previous_record.unwrap_or((Utc::now(), String::new(), None, None, None));
49        let prompt = overrides
50            .as_ref()
51            .and_then(|overrides| overrides.prompt.clone())
52            .filter(|value| !value.trim().is_empty())
53            .or_else(|| (!previous_prompt.trim().is_empty()).then_some(previous_prompt))
54            .or_else(|| spec.initial_prompt.clone())
55            .filter(|value| !value.trim().is_empty())
56            .unwrap_or_else(|| {
57                format!(
58                    "You are the VT Code background subagent `{}`, started without a specific task. Inspect the workspace at a high level, reply with a short readiness summary (what the project is and what you are set up to do), then end your turn; the process keeps running until it is stopped.",
59                    spec.name
60                )
61            });
62        let max_turns = normalize_background_child_max_turns(
63            overrides
64                .as_ref()
65                .and_then(|overrides| overrides.max_turns)
66                .or(previous_max_turns)
67                .or(spec.max_turns),
68            true,
69        );
70        let model_override = overrides
71            .as_ref()
72            .and_then(|overrides| overrides.model_override.clone())
73            .or(previous_model_override)
74            .or_else(|| spec.model.clone());
75        let reasoning_override = overrides
76            .as_ref()
77            .and_then(|overrides| overrides.reasoning_override.clone())
78            .or(previous_reasoning_override)
79            .or_else(|| spec.reasoning_effort.as_ref().map(|e| e.as_str().to_string()));
80
81        {
82            let mut state = self.state.write().await;
83            state.background_children.insert(
84                record_id.clone(),
85                BackgroundRecord {
86                    exit_code: None,
87                    termination_requested: false,
88                    id: record_id.clone(),
89                    agent_name: spec.name.clone(),
90                    display_label: subagent_display_label(&spec),
91                    description: spec.description.clone(),
92                    source: spec.source.label(),
93                    color: spec.color.clone(),
94                    session_id: session_id.clone(),
95                    exec_session_id: exec_session_id.clone(),
96                    desired_enabled: true,
97                    status: BackgroundSubprocessStatus::Starting,
98                    created_at,
99                    updated_at: Utc::now(),
100                    started_at: None,
101                    ended_at: None,
102                    pid: None,
103                    prompt: prompt.clone(),
104                    summary: Some("Starting background subagent".to_string()),
105                    error: None,
106                    archive_path: None,
107                    transcript_path: None,
108                    max_turns,
109                    model_override: model_override.clone(),
110                    reasoning_override: reasoning_override.clone(),
111                    restart_attempts,
112                },
113            );
114        }
115
116        let launch = build_background_launch_spec(
117            &self.config.workspace_root,
118            spec.name.as_str(),
119            parent_session_id.as_str(),
120            session_id.as_str(),
121            prompt.as_str(),
122            max_turns,
123            model_override.as_deref(),
124            reasoning_override.as_deref(),
125        )?;
126        let metadata = if launch.use_pty {
127            self.config
128                .exec_sessions
129                .create_pty_session_for_managed_background(
130                    exec_session_id.clone().into(),
131                    launch.command,
132                    self.config.workspace_root.clone(),
133                    PtySize {
134                        rows: 24,
135                        cols: 80,
136                        pixel_width: 0,
137                        pixel_height: 0,
138                    },
139                    hashbrown::HashMap::new(),
140                    None,
141                    hashbrown::HashMap::new(),
142                    false,
143                )
144                .await
145        } else {
146            self.config
147                .exec_sessions
148                .create_pipe_session_for_managed_background(
149                    exec_session_id.clone().into(),
150                    launch.command,
151                    self.config.workspace_root.clone(),
152                    hashbrown::HashMap::new(),
153                )
154                .await
155        }
156        .with_context(|| format!("Failed to spawn background subprocess for subagent '{}'", spec.name))?;
157
158        tracing::info!(
159            agent_name = spec.name.as_str(),
160            record_id = record_id.as_str(),
161            exec_session_id = exec_session_id.as_str(),
162            pid = metadata.child_pid,
163            "Spawned background subagent subprocess"
164        );
165
166        {
167            let mut state = self.state.write().await;
168            let record = state
169                .background_children
170                .get_mut(&record_id)
171                .ok_or_else(|| anyhow!("Unknown background subprocess {record_id}"))?;
172            finalize_background_launch(
173                record,
174                exec_session_id.as_str(),
175                metadata.child_pid,
176                metadata.started_at,
177                Utc::now(),
178            );
179        }
180
181        self.save_background_state().await?;
182        self.background_status_for(&record_id).await
183    }
184
185    pub(in crate::subagents) async fn refresh_background_archive_metadata(&self, target: &str) -> Result<()> {
186        let session_id = {
187            let state = self.state.read().await;
188            state
189                .background_children
190                .get(target)
191                .map(|record| record.session_id.clone())
192                .ok_or_else(|| anyhow!("Unknown background subprocess {target}"))?
193        };
194
195        if let Some(listing) = find_session_by_identifier(&session_id).await? {
196            let mut state = self.state.write().await;
197            if let Some(record) = state.background_children.get_mut(target) {
198                record.archive_path = Some(listing.path.clone());
199                record.transcript_path = Some(listing.path);
200            }
201        }
202
203        Ok(())
204    }
205
206    /// Marks this controller as closing so [`Self::spawn`] rejects new spawns.
207    ///
208    /// Used before aborting a subtree so a still-running child cannot spawn a
209    /// descendant between the descendant snapshot and the handle abort. Unlike
210    /// [`Self::signal_shutdown`] this uses the transient `closing` flag, which
211    /// is cleared again when the subtree is reopened, so a resumed child can
212    /// delegate and its controller keeps saving background state.
213    pub(in crate::subagents) async fn begin_close(&self) {
214        self.closing.store(true, Ordering::Relaxed);
215    }
216
217    /// Clears the transient close-in-progress flag. Called when a closed
218    /// subtree is reopened so its child-scoped controller can delegate again.
219    pub(in crate::subagents) async fn end_close(&self) {
220        self.closing.store(false, Ordering::Relaxed);
221    }
222
223    /// Request shutdown and await owned child tasks and matrix reconciliation.
224    /// If the caller stops waiting, a later call retains the pending handles.
225    /// Background state is not saved after shutdown begins.
226    pub async fn signal_shutdown(&self) {
227        self.shutdown_requested.store(true, Ordering::Relaxed);
228        self.request_matrix_stop();
229        // Keep child task handles in controller-owned state while awaiting them.
230        // If the caller's shutdown deadline expires, a later call can still
231        // observe their completion rather than losing ownership on drop.
232        let mut shutdown_handles = self.shutdown_handles.lock().await;
233        let mut nested = {
234            let mut state = self.state.write().await;
235            let mut nested = Vec::new();
236            for (id, record) in &mut state.children {
237                if let Some(handle) = record.handle.take() {
238                    handle.abort();
239                    assert!(shutdown_handles.insert(id.clone(), handle).is_none(), "duplicate owned subagent handle");
240                }
241                if let Some(controller) = record.child_controller.clone() {
242                    nested.push((controller, record.session_id.clone()));
243                }
244            }
245            nested
246        };
247        // Mark every child-scoped controller as permanently shut down (so its
248        // background state is not saved) and as closing (so a race cannot let
249        // a fresh grandchild outlive shutdown), then cascade.
250        for (controller, _) in &nested {
251            controller.shutdown_requested.store(true, Ordering::Relaxed);
252            controller.begin_close().await;
253            controller.stop_background_completion_monitor().await;
254        }
255        if let Err(error) = self.cancel_matrix().await {
256            self.matrix.cancellation.read().cancel();
257            tracing::warn!(%error, "failed to persist matrix shutdown cancellation");
258        }
259        self.stop_background_completion_monitor().await;
260        while let Some(id) = shutdown_handles.keys().next().cloned() {
261            if let Some(handle) = shutdown_handles.get_mut(&id) {
262                if let Err(error) = handle.await
263                    && !error.is_cancelled()
264                {
265                    tracing::warn!(%error, "subagent task failed during shutdown");
266                }
267            }
268            shutdown_handles.remove(&id);
269        }
270        // Matrix workers have their own driver task. Do not finish shutdown
271        // while that driver is still reconciling cancelled work.
272        let _ = self.wait_matrix_idle().await;
273        // A child may have installed its scoped controller just before its
274        // abort took effect. Once the child has exited the rescan is stable.
275        let late = {
276            let state = self.state.read().await;
277            state
278                .children
279                .values()
280                .filter_map(|record| {
281                    record
282                        .child_controller
283                        .clone()
284                        .map(|controller| (controller, record.session_id.clone()))
285                })
286                .collect::<Vec<_>>()
287        };
288        for (controller, session_id) in late {
289            if nested
290                .iter()
291                .any(|(known, id)| Arc::ptr_eq(known, &controller) && id == &session_id)
292            {
293                continue;
294            }
295            controller.shutdown_requested.store(true, Ordering::Relaxed);
296            controller.begin_close().await;
297            controller.stop_background_completion_monitor().await;
298            nested.push((controller, session_id));
299        }
300        // Cascade shutdown to child-scoped controllers so grandchildren tasks
301        // are aborted too; otherwise their tokio tasks keep running detached.
302        let mut nested_failed = false;
303        for (controller, session_id) in nested {
304            let ids = controller.spawn_child_ids_for_parent(&session_id).await;
305            for id in ids {
306                if let Err(err) = controller.close_tree(&id).await {
307                    nested_failed = true;
308                    tracing::warn!(node_id = id.as_str(), error = %err, "Failed to close nested subagent subtree during shutdown");
309                }
310            }
311        }
312        let mut state = self.state.write().await;
313        if !nested_failed {
314            for record in state.children.values_mut() {
315                record.status = SubagentStatus::Closed;
316                record.completed_at = Some(Utc::now());
317                record.notify.notify_waiters();
318            }
319        }
320        drop(state);
321        drop(shutdown_handles);
322    }
323
324    pub(in crate::subagents) async fn save_background_state(&self) -> Result<()> {
325        if self.shutdown_requested.load(Ordering::Relaxed) {
326            return Ok(());
327        }
328        let records = {
329            let state = self.state.read().await;
330            state
331                .background_children
332                .values()
333                .cloned()
334                .map(BackgroundRecord::into_persisted)
335                .collect()
336        };
337        persist_background_state(&self.config.workspace_root, records).await
338    }
339}