Skip to main content

vtcode_core/tools/exec_session/manager/
mod.rs

1//! `ExecSessionManager`: unified pipe/PTY session management.
2
3use super::*;
4
5mod create;
6
7#[derive(Default)]
8pub(crate) struct SessionPreviewState {
9    pub(crate) retained: RetainedSessionPreview,
10    pub(crate) pending: Option<String>,
11}
12
13#[derive(Clone)]
14pub struct ExecSessionManager {
15    pipe_sessions: PipeSessionManager,
16    pty_sessions: PtySessionManager,
17    sessions: Arc<RwLock<HashMap<ExecSessionId, Arc<ExecSessionRecord>>>>,
18    create_lock: Arc<Mutex<()>>,
19    active_background_processes: Arc<AtomicUsize>,
20    pub(crate) foreground_pty_counter: Arc<ParkingMutex<Option<Arc<AtomicUsize>>>>,
21    pub(crate) foreground_session: Arc<ParkingMutex<Option<ExecSessionId>>>,
22    focused_session: Arc<ParkingMutex<Option<ExecSessionId>>>,
23    background_request: Arc<ParkingMutex<Option<ExecSessionId>>>,
24    background_shortcut_result: Arc<ParkingMutex<Option<BackgroundShortcutResult>>>,
25    completion_tx: broadcast::Sender<ExecSessionCompletionEvent>,
26    completion_notify: Arc<Notify>,
27}
28
29impl ExecSessionManager {
30    #[must_use]
31    pub fn new(workspace_root: PathBuf, pty_sessions: PtySessionManager) -> Self {
32        let (completion_tx, _) = broadcast::channel(64);
33        Self {
34            pipe_sessions: PipeSessionManager::new(workspace_root),
35            pty_sessions,
36            sessions: Arc::new(RwLock::new(HashMap::new())),
37            create_lock: Arc::new(Mutex::new(())),
38            active_background_processes: Arc::new(AtomicUsize::new(0)),
39            foreground_pty_counter: Arc::new(ParkingMutex::new(None)),
40            foreground_session: Arc::new(ParkingMutex::new(None)),
41            focused_session: Arc::new(ParkingMutex::new(None)),
42            background_request: Arc::new(ParkingMutex::new(None)),
43            background_shortcut_result: Arc::new(ParkingMutex::new(None)),
44            completion_tx,
45            completion_notify: Arc::new(Notify::new()),
46        }
47    }
48
49    /// Subscribe to confirmed terminal transitions for background exec sessions.
50    pub fn subscribe_completion(&self) -> broadcast::Receiver<ExecSessionCompletionEvent> {
51        self.completion_tx.subscribe()
52    }
53
54    /// Wake an idle interaction loop when a background exec session completes.
55    #[must_use]
56    pub fn completion_notify(&self) -> Arc<Notify> {
57        Arc::clone(&self.completion_notify)
58    }
59
60    pub(crate) fn set_foreground_pty_counter(&self, counter: Arc<AtomicUsize>) {
61        *self.foreground_pty_counter.lock() = Some(counter);
62    }
63
64    pub(crate) async fn snapshot_session(&self, session_id: &str) -> Result<VTCodeExecSession> {
65        let record = self.session_record(session_id).await?;
66        match record.backend {
67            ExecSessionBackend::Pipe => self.pipe_sessions.session_record(session_id).await.map(|r| {
68                let mut metadata = r.metadata.clone();
69                metadata.background = record.background.load(Ordering::Acquire);
70                let exit_code = if r.handle.has_exited() {
71                    r.handle.exit_code()
72                } else {
73                    None
74                };
75                metadata.exit_code = exit_code;
76                metadata.lifecycle_state = Some(if exit_code.is_some() {
77                    crate::tools::types::VTCodeSessionLifecycleState::Exited
78                } else {
79                    crate::tools::types::VTCodeSessionLifecycleState::Running
80                });
81                metadata
82            }),
83            ExecSessionBackend::Pty => self.pty_sessions.manager().snapshot_session(session_id).map(|metadata| {
84                let mut metadata = VTCodeExecSession::from(metadata);
85                metadata.background = record.background.load(Ordering::Acquire);
86                metadata
87            }),
88        }
89    }
90
91    pub(crate) async fn termination_requested(&self, session_id: &str) -> bool {
92        self.session_record(session_id)
93            .await
94            .is_ok_and(|record| record.termination_requested.load(Ordering::Acquire))
95    }
96
97    /// Return one retained background session snapshot for the Local Agents drawer.
98    pub async fn background_session_snapshot(&self, session_id: &str) -> Result<ExecSessionUiSnapshot> {
99        let record = self.session_record(session_id).await?;
100        if !record.background.load(Ordering::Acquire) || !record.show_in_background_drawer.load(Ordering::Acquire) {
101            bail!("exec session '{session_id}' is a foreground session and is not visible in the background drawer");
102        }
103
104        // Capture output that has not yet been consumed by the tool wait loop
105        // before reading the retained preview. Drained output is remembered by
106        // `read_session_output`, so this remains inspectable after a tool turn.
107        let _ = self.read_session_output(session_id, false).await?;
108        let metadata = self.snapshot_session(session_id).await?;
109        let updated_at = {
110            let mut completed_at = record.completed_at.lock();
111            if metadata.exit_code.is_some() {
112                completed_at.get_or_insert_with(Utc::now);
113            }
114            (*completed_at).or(metadata.started_at).unwrap_or_else(Utc::now)
115        };
116        Ok(ExecSessionUiSnapshot {
117            updated_at,
118            metadata,
119            preview: record.preview(),
120            termination_requested: record.termination_requested.load(Ordering::Acquire),
121        })
122    }
123
124    /// Return all background raw command sessions, including exited sessions
125    /// that have not been explicitly closed.
126    pub async fn background_session_snapshots(&self) -> Vec<ExecSessionUiSnapshot> {
127        let ids = {
128            let sessions = self.sessions.read().await;
129            sessions
130                .values()
131                .filter(|record| {
132                    record.background.load(Ordering::Acquire)
133                        && record.show_in_background_drawer.load(Ordering::Acquire)
134                })
135                .map(|record| record.metadata.id.clone())
136                .collect::<Vec<_>>()
137        };
138
139        let mut snapshots = Vec::new();
140        for id in ids {
141            if let Ok(snapshot) = self.background_session_snapshot(id.as_str()).await {
142                snapshots.push(snapshot);
143            }
144        }
145        snapshots.sort_by(|left, right| match (left.metadata.started_at, right.metadata.started_at) {
146            (Some(left), Some(right)) => right.cmp(&left),
147            (Some(_), None) => std::cmp::Ordering::Less,
148            (None, Some(_)) => std::cmp::Ordering::Greater,
149            (None, None) => right.metadata.id.cmp(&left.metadata.id),
150        });
151        snapshots
152    }
153
154    pub(crate) async fn list_sessions(&self) -> Vec<VTCodeExecSession> {
155        let sessions = self.sessions.read().await;
156        let mut listed = sessions
157            .values()
158            .map(|record| {
159                let mut metadata = record.metadata.clone();
160                metadata.background = record.background.load(Ordering::Acquire);
161                metadata
162            })
163            .collect::<Vec<_>>();
164        listed.sort_by(|left, right| left.id.cmp(&right.id));
165        listed
166    }
167
168    /// Bounded snapshot of exec sessions that are still running (not exited).
169    ///
170    /// Used for turn-end diagnostics and telemetry. Ordered newest-first by
171    /// `started_at` (sessions without a timestamp last), capped so a
172    /// pathological session count cannot inflate the recorded state.
173    /// Completion is checked against the backend (not the cached metadata) so
174    /// a session that exited after its last metadata refresh is correctly
175    /// excluded. Cross-turn resume hints use the foreground-only variant
176    /// below so retained background work does not become mandatory follow-up.
177    pub(crate) async fn in_progress_exec_sessions(&self, cap: usize) -> Vec<VTCodeExecSession> {
178        self.collect_in_progress_exec_sessions(cap, true).await
179    }
180
181    /// Bounded snapshot of running foreground sessions for cross-turn resume
182    /// hints. Retained background sessions are deliberately excluded because
183    /// they are not work the next turn must settle before proceeding.
184    pub(crate) async fn in_progress_foreground_exec_sessions(&self, cap: usize) -> Vec<VTCodeExecSession> {
185        self.collect_in_progress_exec_sessions(cap, false).await
186    }
187
188    async fn collect_in_progress_exec_sessions(&self, cap: usize, include_background: bool) -> Vec<VTCodeExecSession> {
189        if cap == 0 {
190            return Vec::new();
191        }
192        let ids = {
193            let sessions = self.sessions.read().await;
194            sessions.keys().cloned().collect::<Vec<_>>()
195        };
196        let mut in_progress = Vec::new();
197        for id in ids {
198            let Ok(session) = self.snapshot_session(id.as_str()).await else {
199                continue;
200            };
201            if session.exit_code.is_none() && (include_background || !session.background) {
202                in_progress.push(session);
203            }
204        }
205        in_progress.sort_by(|left, right| match (left.started_at, right.started_at) {
206            (Some(left), Some(right)) => right.cmp(&left),
207            (Some(_), None) => std::cmp::Ordering::Less,
208            (None, Some(_)) => std::cmp::Ordering::Greater,
209            (None, None) => right.id.cmp(&left.id),
210        });
211        in_progress.truncate(cap);
212        in_progress
213    }
214
215    pub(crate) async fn read_session_output(&self, session_id: &str, drain: bool) -> Result<Option<String>> {
216        let record = self.session_record(session_id).await?;
217        // Serialize the backend read with the preview update. A peek followed
218        // by a concurrent drain must not leave the same chunk pending after
219        // it has already been retained.
220        let _output_read_guard = record.output_read_lock.lock().await;
221        let output = match record.backend {
222            ExecSessionBackend::Pipe => self.pipe_sessions.read_session_output(session_id, drain).await,
223            ExecSessionBackend::Pty => self.pty_sessions.manager().read_session_output(session_id, drain),
224        }?;
225        record.remember_output(output.as_deref(), drain);
226        Ok(output)
227    }
228
229    pub(crate) async fn output_stats(&self, session_id: &str) -> Result<Option<PipeOutputStats>> {
230        let record = self.session_record(session_id).await?;
231        match record.backend {
232            ExecSessionBackend::Pipe => self.pipe_sessions.output_stats(session_id).await.map(Some),
233            ExecSessionBackend::Pty => self.pty_sessions.manager().output_stats(session_id).map(|stats| {
234                stats.map(|stats| PipeOutputStats {
235                    total_bytes: stats.total_bytes,
236                    truncated: stats.truncated,
237                    spool_path: stats.spool_path,
238                    spool_available: stats.spool_available,
239                    spool_complete: stats.spool_complete,
240                    spool_integrity: stats.spool_integrity,
241                })
242            }),
243        }
244    }
245
246    pub async fn send_input_to_session(&self, session_id: &str, data: &[u8], append_newline: bool) -> Result<usize> {
247        let record = self.session_record(session_id).await?;
248        match record.backend {
249            ExecSessionBackend::Pipe => {
250                self.pipe_sessions.send_input_to_session(session_id, data, append_newline).await
251            }
252            ExecSessionBackend::Pty => {
253                self.pty_sessions
254                    .manager()
255                    .send_input_to_session(session_id, data, append_newline)
256            }
257        }
258    }
259
260    pub async fn is_session_completed(&self, session_id: &str) -> Result<Option<i32>> {
261        let record = self.session_record(session_id).await?;
262        let completed = match record.backend {
263            ExecSessionBackend::Pipe => self.pipe_sessions.is_session_completed(session_id).await,
264            ExecSessionBackend::Pty => self.pty_sessions.manager().is_session_completed(session_id),
265        }?;
266        if completed.is_some() {
267            self.release_pending_background_request(session_id);
268            self.clear_focused_session_if_matches(session_id);
269        }
270        Ok(completed)
271    }
272
273    pub(crate) async fn activity_receiver(&self, session_id: &str) -> Result<Option<watch::Receiver<u64>>> {
274        let record = self.session_record(session_id).await?;
275        match record.backend {
276            ExecSessionBackend::Pipe => self.pipe_sessions.activity_receiver(session_id).await.map(Some),
277            ExecSessionBackend::Pty => Ok(None),
278        }
279    }
280
281    pub(crate) async fn is_output_drained(&self, session_id: &str) -> Result<bool> {
282        let record = self.session_record(session_id).await?;
283        let drained = match record.backend {
284            ExecSessionBackend::Pipe => self.pipe_sessions.is_output_drained(session_id).await,
285            ExecSessionBackend::Pty => self.pty_sessions.manager().is_output_drained(session_id),
286        }?;
287        Ok(drained)
288    }
289
290    pub async fn terminate_session(&self, session_id: &str) -> Result<()> {
291        let record = self.session_record(session_id).await?;
292        self.clear_focused_session_if_matches(session_id);
293        record.termination_requested.store(true, Ordering::Release);
294        let result = match record.backend {
295            ExecSessionBackend::Pipe => self.pipe_sessions.terminate_session(session_id).await,
296            ExecSessionBackend::Pty => {
297                let manager = self.pty_sessions.manager().clone();
298                let id = session_id.to_string();
299                tokio::task::spawn_blocking(move || manager.terminate_session(&id))
300                    .await
301                    .map_err(|join_error| anyhow!("exec session terminate task failed: {join_error}"))?
302            }
303        };
304        if result.is_err() {
305            record.termination_requested.store(false, Ordering::Release);
306        }
307        result
308    }
309
310    pub async fn force_terminate_session(&self, session_id: &str) -> Result<()> {
311        let record = self.session_record(session_id).await?;
312        self.clear_focused_session_if_matches(session_id);
313        record.termination_requested.store(true, Ordering::Release);
314        let result = match record.backend {
315            ExecSessionBackend::Pipe => self.pipe_sessions.force_terminate_session(session_id).await,
316            ExecSessionBackend::Pty => {
317                // PTY terminate performs a bounded child reap that sleeps;
318                // keep it off the async worker so ForceCancel over N sessions
319                // cannot stall the runloop.
320                let manager = self.pty_sessions.manager().clone();
321                let id = session_id.to_string();
322                tokio::task::spawn_blocking(move || manager.force_terminate_session(&id))
323                    .await
324                    .map_err(|join_error| anyhow!("exec session force-terminate task failed: {join_error}"))?
325            }
326        };
327        if result.is_err() {
328            record.termination_requested.store(false, Ordering::Release);
329        }
330        result
331    }
332
333    pub async fn close_session(&self, session_id: &str) -> Result<VTCodeExecSession> {
334        self.close_session_with_mode(session_id, PtyCloseMode::Graceful).await
335    }
336
337    /// Close with an explicit termination mode. `Immediate` is reserved for
338    /// exit-driven teardown: it skips the `exit\n` courtesy and the SIGTERM
339    /// grace window so a live PTY child cannot cost ~600 ms of shell-return
340    /// latency per session. The OS reaps survivors at process exit.
341    pub async fn close_session_with_mode(&self, session_id: &str, mode: PtyCloseMode) -> Result<VTCodeExecSession> {
342        // Serialize removal with Ctrl+B promotion and new session creation so
343        // a promotion cannot reserve a slot on a record that close has already
344        // detached from the unified session map.
345        let (record, pending_background_request) = {
346            let _lifecycle_guard = self.create_lock.lock().await;
347            let record = {
348                let mut sessions = self.sessions.write().await;
349                sessions
350                    .remove(session_id)
351                    .ok_or_else(|| missing_exec_session_error(session_id))?
352            };
353
354            let pending_background_request = self.clear_foreground_and_take_pending_request(session_id);
355            self.clear_focused_session_if_matches(session_id);
356            (record, pending_background_request)
357        };
358
359        // Capacity release must happen even if backend close times out: the
360        // record is already detached, so leaving counters elevated pins
361        // `Running PTY command...` and the composer lock forever.
362        let close_result = self.close_session_backend_bounded(session_id, &record, mode).await;
363
364        self.release_foreground_pty_count(&record);
365        if pending_background_request {
366            self.release_reserved_background_slot(true);
367        } else {
368            self.release_background_slot(&record);
369        }
370
371        let mut metadata = close_result?;
372        metadata.background = record.background.load(Ordering::Acquire);
373        Ok(metadata)
374    }
375
376    /// Abort lifecycle watchers and close the backend under a hard timeout.
377    ///
378    /// Watcher abort and the blocking PTY close are themselves the hang sites
379    /// (unbounded `join`/`wait`, or a watcher stuck in a sync section), so
380    /// this entire unit is time-bounded and the PTY close runs on
381    /// `spawn_blocking` to keep the async worker responsive. Pipe close stays
382    /// on the runtime (already async and internally timed).
383    async fn close_session_backend_bounded(
384        &self,
385        session_id: &str,
386        record: &Arc<ExecSessionRecord>,
387        mode: PtyCloseMode,
388    ) -> Result<VTCodeExecSession> {
389        let background_watch = record.background_watch.lock().take();
390        if let Some(watch) = background_watch {
391            watch.abort();
392            if tokio::time::timeout(EXEC_SESSION_WATCH_ABORT_TIMEOUT, watch).await.is_err() {
393                tracing::warn!(%session_id, "background watcher did not stop within abort timeout");
394            }
395        }
396        let foreground_watch = record.foreground_watch.lock().take();
397        if let Some(watch) = foreground_watch {
398            watch.abort();
399            if tokio::time::timeout(EXEC_SESSION_WATCH_ABORT_TIMEOUT, watch).await.is_err() {
400                tracing::warn!(%session_id, "foreground watcher did not stop within abort timeout");
401            }
402        }
403
404        // Do not close the backend while an output peek/drain is still using
405        // it. The unified record has already been removed, so this lock only
406        // waits for in-flight readers acquired before close. The acquire is
407        // itself time-bounded: an abandoned peek holding the lock must not
408        // make close (and the runloop) wait forever.
409        let _output_read_guard =
410            match tokio::time::timeout(EXEC_SESSION_OUTPUT_READ_LOCK_TIMEOUT, record.output_read_lock.lock()).await {
411                Ok(guard) => Some(guard),
412                Err(_elapsed) => {
413                    tracing::warn!(
414                        %session_id,
415                        "output read lock not available within timeout; closing session anyway"
416                    );
417                    None
418                }
419            };
420        let metadata = match record.backend {
421            ExecSessionBackend::Pipe => {
422                let pipe_sessions = self.pipe_sessions.clone();
423                let session_id_owned = session_id.to_string();
424                tokio::time::timeout(EXEC_SESSION_CLOSE_TIMEOUT, async move {
425                    pipe_sessions.close_session(&session_id_owned).await
426                })
427                .await
428            }
429            ExecSessionBackend::Pty => {
430                let pty_manager = self.pty_sessions.manager().clone();
431                let session_id_owned = session_id.to_string();
432                tokio::time::timeout(EXEC_SESSION_CLOSE_TIMEOUT, async move {
433                    tokio::task::spawn_blocking(move || {
434                        pty_manager
435                            .close_session_with_mode(&session_id_owned, mode)
436                            .map(VTCodeExecSession::from)
437                    })
438                    .await
439                    .map_err(|join_error| anyhow!("exec session close task failed: {join_error}"))?
440                })
441                .await
442            }
443        };
444
445        match metadata {
446            Ok(result) => result,
447            Err(_elapsed) => Err(anyhow!(
448                "exec session '{session_id}' close timed out after {}s; record detached and counters released",
449                EXEC_SESSION_CLOSE_TIMEOUT.as_secs()
450            )),
451        }
452    }
453
454    /// Force-stop an active session, or close it when it has already exited.
455    /// Returns `true` when the session was already complete and was closed.
456    pub async fn force_terminate_or_close(&self, session_id: &str) -> Result<bool> {
457        let completed = self.is_session_completed(session_id).await?.is_some();
458        // A completed pipe wait can represent an error rather than an
459        // observed exit; confirm before either retaining or closing it.
460        self.force_terminate_session(session_id).await?;
461        if completed {
462            self.close_session(session_id).await?;
463        }
464        Ok(completed)
465    }
466
467    /// Focus a running background session so subsequent submitted lines are
468    /// written to its stdin instead of becoming a model prompt.
469    pub async fn focus_background_session(&self, session_id: &str) -> Result<()> {
470        let record = self.session_record(session_id).await?;
471        if !record.background.load(Ordering::Acquire) {
472            bail!("exec session '{session_id}' is a foreground session and cannot be focused from the drawer");
473        }
474        if self.is_session_completed(session_id).await?.is_some() {
475            bail!("exec session '{session_id}' has already exited and cannot receive input");
476        }
477        *self.focused_session.lock() = Some(record.metadata.id.clone());
478        Ok(())
479    }
480
481    /// Return the focused background session, if any.
482    #[must_use]
483    pub fn focused_session_id(&self) -> Option<String> {
484        self.focused_session.lock().as_ref().map(|id| id.as_str().to_string())
485    }
486
487    pub fn clear_focused_session(&self) {
488        *self.focused_session.lock() = None;
489    }
490
491    pub(crate) async fn prune_exited_session(&self, session_id: &str) -> Result<Option<VTCodeExecSession>> {
492        let record = self.session_record(session_id).await?;
493        if self.is_session_completed(session_id).await?.is_some() {
494            // Background completion owns the final output capture and parent
495            // notification. A synchronous wait/stop can observe process exit
496            // first; pruning here would abort that watcher and lose the
497            // terminal event. Retain the session until the watcher has
498            // finished, after which a later prune may close it safely.
499            let completion_pending = record.background.load(Ordering::Acquire)
500                && record
501                    .background_watch
502                    .lock()
503                    .as_ref()
504                    .is_some_and(|watch| !watch.is_finished());
505            if completion_pending {
506                return Ok(None);
507            }
508            return self.close_session(session_id).await.map(Some);
509        }
510        Ok(None)
511    }
512
513    pub(crate) async fn terminate_all_sessions_async(&self) -> Result<()> {
514        self.terminate_all_sessions_with_mode_async(PtyCloseMode::Graceful).await
515    }
516
517    /// Exit-path terminator: closes every session in `Immediate` mode so a
518    /// live PTY child is group-SIGKILLed instead of waiting out the SIGTERM
519    /// grace window. Callers still bound this with an outer timeout; the OS
520    /// reaps any remainder at process exit.
521    pub(crate) async fn terminate_all_sessions_for_exit_async(&self) -> Result<()> {
522        self.terminate_all_sessions_with_mode_async(PtyCloseMode::Immediate).await
523    }
524
525    async fn terminate_all_sessions_with_mode_async(&self, mode: PtyCloseMode) -> Result<()> {
526        let ids = {
527            let sessions = self.sessions.read().await;
528            sessions.keys().cloned().collect::<Vec<_>>()
529        };
530
531        // Parallel close: sequential closes sum per-session timeouts (12s
532        // inner cap each) into a multi-second exit tail. Concurrent closes
533        // overlap as max instead of sum; the caller's outer timeout
534        // (EXIT_BACKGROUND_SHUTDOWN_TIMEOUT) still bounds the total.
535        // Early return when empty avoids even the pipe-manager lock.
536        if ids.is_empty() {
537            return self.pipe_sessions.terminate_all_sessions().await;
538        }
539
540        let results = futures::future::join_all(ids.into_iter().map(|session_id| async move {
541            self.close_session_with_mode(&session_id, mode)
542                .await
543                .map_err(|err| format!("{session_id}: {err}"))
544        }))
545        .await;
546
547        let mut failures: Vec<String> = results.into_iter().filter_map(|r| r.err()).collect();
548
549        if let Err(err) = self.pipe_sessions.terminate_all_sessions().await {
550            failures.push(err.to_string());
551        }
552
553        if failures.is_empty() {
554            Ok(())
555        } else {
556            Err(anyhow!("failed to terminate all exec sessions: {}", failures.join("; ")))
557        }
558    }
559
560    pub(crate) async fn terminate_active_sessions_async(&self) -> Result<()> {
561        self.terminate_active_sessions_with_mode_async(PtyCloseMode::Graceful).await
562    }
563
564    /// Exit-path variant of [`Self::terminate_active_sessions_async`] using
565    /// `Immediate` PTY termination (see [`Self::terminate_all_sessions_for_exit_async`]).
566    pub(crate) async fn terminate_active_sessions_for_exit_async(&self) -> Result<()> {
567        self.terminate_active_sessions_with_mode_async(PtyCloseMode::Immediate).await
568    }
569
570    async fn terminate_active_sessions_with_mode_async(&self, mode: PtyCloseMode) -> Result<()> {
571        let ids = {
572            let sessions = self.sessions.read().await;
573            sessions
574                .values()
575                .filter(|record| !record.background.load(Ordering::Acquire))
576                .map(|record| record.metadata.id.clone())
577                .collect::<Vec<_>>()
578        };
579
580        if ids.is_empty() {
581            return Ok(());
582        }
583
584        // Parallel close for the same reason as terminate_all: avoid summing
585        // per-session timeouts on the exit path.
586        let results: Vec<Result<(), String>> =
587            futures::future::join_all(ids.into_iter().map(|session_id| async move {
588                let should_close = self
589                    .session_record(session_id.as_str())
590                    .await
591                    .map(|record| !record.background.load(Ordering::Acquire))
592                    .unwrap_or(false);
593                if !should_close {
594                    return Ok(());
595                }
596                self.close_session_with_mode(&session_id, mode)
597                    .await
598                    .map(|_| ())
599                    .map_err(|err| format!("{session_id}: {err}"))
600            }))
601            .await;
602
603        let failures: Vec<String> = results.into_iter().filter_map(|r| r.err()).collect();
604
605        if failures.is_empty() {
606            Ok(())
607        } else {
608            Err(anyhow!("failed to terminate active exec sessions: {}", failures.join("; ")))
609        }
610    }
611
612    /// Force-stop every foreground exec session and close it. Used by the TUI
613    /// ForceCancel escape hatch so a stuck PTY cannot keep the composer locked.
614    /// Closing after the kill is intentional: `force_terminate_or_close` alone
615    /// leaves live sessions attached ("remains visible until closed"), which
616    /// would keep the foreground counter elevated. Background sessions are
617    /// user-owned and are left alone. Returns `(stopped, closed, failed)`
618    /// counts where `stopped` are live kills and `closed` are already-exited
619    /// sessions removed from the map.
620    pub async fn force_cancel_foreground_sessions(&self) -> (usize, usize, usize) {
621        let ids = {
622            let sessions = self.sessions.read().await;
623            sessions
624                .values()
625                .filter(|record| !record.background.load(Ordering::Acquire))
626                .map(|record| record.metadata.id.clone())
627                .collect::<Vec<_>>()
628        };
629
630        let mut stopped = 0usize;
631        let mut closed = 0usize;
632        let mut failed = 0usize;
633        for session_id in ids {
634            let was_running = self.is_session_completed(session_id.as_str()).await.ok().flatten().is_none();
635            // Even an apparently completed pipe may have a failed wait; ask
636            // the backend to confirm its direct child before detaching it.
637            if let Err(error) = self.force_terminate_session(session_id.as_str()).await {
638                tracing::warn!(%session_id, %error, "force-cancel terminate failed");
639                failed += 1;
640                continue;
641            }
642            match self.close_session(session_id.as_str()).await {
643                Ok(_) => {
644                    if was_running {
645                        stopped += 1;
646                    } else {
647                        closed += 1;
648                    }
649                }
650                Err(error) => {
651                    tracing::warn!(%session_id, %error, "force-cancel close failed");
652                    failed += 1;
653                }
654            }
655        }
656        (stopped, closed, failed)
657    }
658
659    /// Return the number of currently live background process reservations.
660    #[must_use]
661    pub fn active_background_processes(&self) -> usize {
662        self.active_background_processes.load(Ordering::Acquire)
663    }
664
665    /// Request that the current foreground session be promoted to background.
666    ///
667    /// The request is synchronous because it is called by the TUI key-event
668    /// callback. The execution wait loop consumes the request asynchronously
669    /// and performs the metadata transition without killing the process.
670    pub fn request_foreground_background(&self) -> Option<BackgroundShortcutResult> {
671        let mut request = self.background_request.lock();
672        if request.is_some() {
673            *self.background_shortcut_result.lock() = Some(BackgroundShortcutResult::Requested);
674            return Some(BackgroundShortcutResult::Requested);
675        }
676
677        // Take the foreground lock after `background_request`. Completion and
678        // close paths use the same order when clearing a pending promotion;
679        // holding both here prevents a completed session from being observed
680        // between the foreground lookup and request reservation.
681        let Some(session_id) = self.foreground_session.lock().clone() else {
682            *self.background_shortcut_result.lock() = None;
683            return None;
684        };
685
686        let result = match self.reserve_background_slot() {
687            Ok(_) => {
688                *request = Some(session_id);
689                BackgroundShortcutResult::Requested
690            }
691            Err(_) => BackgroundShortcutResult::AtCapacity,
692        };
693        *self.background_shortcut_result.lock() = Some(result);
694        Some(result)
695    }
696
697    /// Consume the result associated with the queued Ctrl+B event.
698    pub fn take_background_shortcut_result(&self) -> Option<BackgroundShortcutResult> {
699        self.background_shortcut_result.lock().take()
700    }
701
702    /// Apply a pending Ctrl+B promotion to the specified session.
703    pub(crate) async fn promote_requested_session(&self, session_id: &str) -> Result<bool> {
704        let _lifecycle_guard = self.create_lock.lock().await;
705        if !self.take_foreground_promotion_request(session_id) {
706            return Ok(false);
707        }
708
709        let record = match self.session_record(session_id).await {
710            Ok(record) => record,
711            Err(error) => {
712                self.release_reserved_background_slot(true);
713                return Err(error);
714            }
715        };
716        if record.background.load(Ordering::Acquire) {
717            self.release_reserved_background_slot(true);
718            self.clear_foreground_session(session_id);
719            return Ok(false);
720        }
721        match self.is_session_completed(session_id).await {
722            Ok(Some(_)) => {
723                self.release_reserved_background_slot(true);
724                self.clear_foreground_session(session_id);
725                return Ok(false);
726            }
727            Ok(None) => {}
728            Err(error) => {
729                self.release_reserved_background_slot(true);
730                self.set_foreground_session(ExecSessionId::new(session_id));
731                return Err(error);
732            }
733        }
734
735        record.background_slot_reserved.store(true, Ordering::Release);
736        self.release_foreground_pty_count(&record);
737        record.background.store(true, Ordering::Release);
738        record.show_in_background_drawer.store(true, Ordering::Release);
739        self.clear_foreground_session(session_id);
740        let promotion_marker = Arc::clone(&record);
741        self.start_background_watcher(record, session_id.to_string());
742        promotion_marker
743            .background_promoted_from_foreground
744            .store(true, Ordering::Release);
745        Ok(true)
746    }
747
748    pub(crate) async fn take_foreground_promotion(&self, session_id: &str) -> Result<bool> {
749        let record = self.session_record(session_id).await?;
750        Ok(record.background_promoted_from_foreground.swap(false, Ordering::AcqRel))
751    }
752
753    fn reserve_background_slot(&self) -> Result<bool> {
754        let mut current = self.active_background_processes.load(Ordering::Acquire);
755        loop {
756            if current >= MAX_BACKGROUND_PROCESSES {
757                bail!(
758                    "maximum background process limit reached ({MAX_BACKGROUND_PROCESSES}); wait for or close an existing background session before starting another"
759                );
760            }
761            match self.active_background_processes.compare_exchange(
762                current,
763                current + 1,
764                Ordering::AcqRel,
765                Ordering::Acquire,
766            ) {
767                Ok(_) => return Ok(true),
768                Err(observed) => current = observed,
769            }
770        }
771    }
772
773    fn release_reserved_background_slot(&self, reserved: bool) {
774        if reserved {
775            self.active_background_processes.fetch_sub(1, Ordering::AcqRel);
776        }
777    }
778
779    fn release_background_slot(&self, record: &ExecSessionRecord) {
780        if record.background_slot_reserved.swap(false, Ordering::AcqRel) {
781            self.active_background_processes.fetch_sub(1, Ordering::AcqRel);
782        }
783    }
784
785    fn count_foreground_pty_session(&self, record: &ExecSessionRecord) {
786        let Some(counter) = self.foreground_pty_counter.lock().as_ref().map(Arc::clone) else {
787            return;
788        };
789        counter.fetch_add(1, Ordering::Relaxed);
790        *record.foreground_pty_counter.lock() = Some(counter);
791    }
792
793    fn release_foreground_pty_count(&self, record: &ExecSessionRecord) {
794        let Some(counter) = record.foreground_pty_counter.lock().take() else {
795            return;
796        };
797        let _ = counter.try_update(Ordering::AcqRel, Ordering::Acquire, |current| current.checked_sub(1));
798    }
799
800    fn clear_foreground_and_take_pending_request(&self, session_id: &str) -> bool {
801        let mut request = self.background_request.lock();
802        let taken = request.as_deref() == Some(session_id) && request.take().is_some();
803        let mut foreground = self.foreground_session.lock();
804        if foreground.as_deref() == Some(session_id) {
805            *foreground = None;
806        }
807        drop(foreground);
808        if taken {
809            *self.background_shortcut_result.lock() = None;
810        }
811        taken
812    }
813
814    fn take_foreground_promotion_request(&self, session_id: &str) -> bool {
815        let mut request = self.background_request.lock();
816        if request.as_deref() != Some(session_id) || request.take().is_none() {
817            return false;
818        }
819        let mut foreground = self.foreground_session.lock();
820        if foreground.as_deref() == Some(session_id) {
821            *foreground = None;
822        }
823        drop(foreground);
824        *self.background_shortcut_result.lock() = None;
825        true
826    }
827
828    fn release_pending_background_request(&self, session_id: &str) {
829        if self.clear_foreground_and_take_pending_request(session_id) {
830            self.release_reserved_background_slot(true);
831        }
832    }
833
834    fn start_background_watcher(&self, record: Arc<ExecSessionRecord>, session_id: String) {
835        let manager = self.clone();
836        let record_for_task = Arc::clone(&record);
837        let task = tokio::spawn(async move {
838            loop {
839                match manager.is_session_completed(session_id.as_str()).await {
840                    Ok(Some(exit_code)) => {
841                        record_for_task.completed_at.lock().get_or_insert_with(Utc::now);
842                        manager.capture_background_completion_output(session_id.as_str()).await;
843                        if record_for_task
844                            .background_completion_published
845                            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
846                            .is_ok()
847                        {
848                            let command = bounded_completion_command(&record_for_task.metadata.command_label());
849                            let _ = manager.completion_tx.send(ExecSessionCompletionEvent {
850                                session_id: ExecSessionId::new(session_id.clone()),
851                                command,
852                                managed_background: !record_for_task.show_in_background_drawer.load(Ordering::Acquire),
853                                termination_requested: record_for_task.termination_requested.load(Ordering::Acquire),
854                                exit_code,
855                            });
856                            // Keep one wake permit when the idle loop has not
857                            // entered its wait yet; the broadcast receiver
858                            // drains every completion that accumulated behind
859                            // the single permit.
860                            manager.completion_notify.notify_one();
861                        }
862                        manager.release_background_slot(&record_for_task);
863                        break;
864                    }
865                    Ok(None) => tokio::time::sleep(tokio::time::Duration::from_millis(50)).await,
866                    Err(_) => {
867                        // A transient status error must not release the live
868                        // background reservation. Only a removed session ends
869                        // this watcher without a confirmed process exit; its
870                        // close path owns the reservation release.
871                        if manager.session_record(session_id.as_str()).await.is_err() {
872                            break;
873                        }
874                        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
875                    }
876                }
877            }
878        });
879        if let Some(previous) = record.background_watch.lock().replace(task) {
880            previous.abort();
881        }
882    }
883
884    async fn capture_background_completion_output(&self, session_id: &str) {
885        let deadline = tokio::time::Instant::now() + EXEC_SESSION_COMPLETION_DRAIN_TIMEOUT;
886        loop {
887            let _ = self.read_session_output(session_id, false).await;
888            if self.is_output_drained(session_id).await.unwrap_or(false) || tokio::time::Instant::now() >= deadline {
889                break;
890            }
891            tokio::time::sleep(EXEC_SESSION_COMPLETION_DRAIN_POLL).await;
892        }
893        // Capture bytes that raced with the final drain-state observation.
894        let _ = self.read_session_output(session_id, false).await;
895    }
896
897    fn start_foreground_watcher(&self, record: Arc<ExecSessionRecord>, session_id: String) {
898        let manager = self.clone();
899        let record_for_task = Arc::clone(&record);
900        let task = tokio::spawn(async move {
901            loop {
902                if manager.promote_requested_session(session_id.as_str()).await.unwrap_or(false) {
903                    break;
904                }
905                if record_for_task.background.load(Ordering::Acquire) {
906                    break;
907                }
908                match manager.is_session_completed(session_id.as_str()).await {
909                    Ok(Some(_)) => {
910                        manager.release_foreground_pty_count(&record_for_task);
911                        manager.release_pending_background_request(session_id.as_str());
912                        break;
913                    }
914                    Ok(None) => tokio::time::sleep(tokio::time::Duration::from_millis(50)).await,
915                    Err(_) => {
916                        if manager.session_record(session_id.as_str()).await.is_err() {
917                            break;
918                        }
919                        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
920                    }
921                }
922            }
923        });
924        if let Some(previous) = record.foreground_watch.lock().replace(task) {
925            previous.abort();
926        }
927    }
928
929    fn set_foreground_session(&self, session_id: ExecSessionId) {
930        *self.foreground_session.lock() = Some(session_id);
931    }
932
933    fn clear_foreground_session(&self, session_id: &str) {
934        let mut foreground = self.foreground_session.lock();
935        if foreground.as_deref() == Some(session_id) {
936            *foreground = None;
937        }
938    }
939
940    fn clear_focused_session_if_matches(&self, session_id: &str) {
941        let mut focused = self.focused_session.lock();
942        if focused.as_deref().is_some_and(|id| id == session_id) {
943            *focused = None;
944        }
945    }
946
947    async fn insert_session(
948        &self,
949        metadata: VTCodeExecSession,
950        backend: ExecSessionBackend,
951        pty_guard: Option<PtySessionGuard>,
952        launch_mode: ExecSessionLaunchMode,
953        background_slot_reserved: bool,
954    ) -> Result<Arc<ExecSessionRecord>> {
955        let mut sessions = self.sessions.write().await;
956        use hashbrown::hash_map::Entry;
957        match sessions.entry(metadata.id.clone()) {
958            Entry::Occupied(_) => Err(anyhow!("exec session '{}' already exists", metadata.id.as_str())),
959            Entry::Vacant(entry) => {
960                let record = Arc::new(ExecSessionRecord::new(
961                    metadata,
962                    backend,
963                    pty_guard,
964                    launch_mode,
965                    background_slot_reserved,
966                ));
967                // Foreground PTY and pipe sessions both support Ctrl+B backgrounding,
968                // so both increment the shared foreground counter driving the TUI hint.
969                if launch_mode.sets_foreground_session() {
970                    self.count_foreground_pty_session(&record);
971                }
972                entry.insert(Arc::clone(&record));
973                Ok(record)
974            }
975        }
976    }
977
978    async fn ensure_session_absent(&self, session_id: &str) -> Result<()> {
979        let sessions = self.sessions.read().await;
980        if sessions.contains_key(session_id) {
981            return Err(anyhow!("exec session '{session_id}' already exists"));
982        }
983        Ok(())
984    }
985
986    pub(crate) async fn session_record(&self, session_id: &str) -> Result<Arc<ExecSessionRecord>> {
987        let sessions = self.sessions.read().await;
988        sessions
989            .get(session_id)
990            .cloned()
991            .ok_or_else(|| missing_exec_session_error(session_id))
992    }
993}