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        if completed {
459            self.close_session(session_id).await?;
460        } else {
461            self.force_terminate_session(session_id).await?;
462        }
463        Ok(completed)
464    }
465
466    /// Focus a running background session so subsequent submitted lines are
467    /// written to its stdin instead of becoming a model prompt.
468    pub async fn focus_background_session(&self, session_id: &str) -> Result<()> {
469        let record = self.session_record(session_id).await?;
470        if !record.background.load(Ordering::Acquire) {
471            bail!("exec session '{session_id}' is a foreground session and cannot be focused from the drawer");
472        }
473        if self.is_session_completed(session_id).await?.is_some() {
474            bail!("exec session '{session_id}' has already exited and cannot receive input");
475        }
476        *self.focused_session.lock() = Some(record.metadata.id.clone());
477        Ok(())
478    }
479
480    /// Return the focused background session, if any.
481    #[must_use]
482    pub fn focused_session_id(&self) -> Option<String> {
483        self.focused_session.lock().as_ref().map(|id| id.as_str().to_string())
484    }
485
486    pub fn clear_focused_session(&self) {
487        *self.focused_session.lock() = None;
488    }
489
490    pub(crate) async fn prune_exited_session(&self, session_id: &str) -> Result<Option<VTCodeExecSession>> {
491        let record = self.session_record(session_id).await?;
492        if self.is_session_completed(session_id).await?.is_some() {
493            // Background completion owns the final output capture and parent
494            // notification. A synchronous wait/stop can observe process exit
495            // first; pruning here would abort that watcher and lose the
496            // terminal event. Retain the session until the watcher has
497            // finished, after which a later prune may close it safely.
498            let completion_pending = record.background.load(Ordering::Acquire)
499                && record
500                    .background_watch
501                    .lock()
502                    .as_ref()
503                    .is_some_and(|watch| !watch.is_finished());
504            if completion_pending {
505                return Ok(None);
506            }
507            return self.close_session(session_id).await.map(Some);
508        }
509        Ok(None)
510    }
511
512    pub(crate) async fn terminate_all_sessions_async(&self) -> Result<()> {
513        self.terminate_all_sessions_with_mode_async(PtyCloseMode::Graceful).await
514    }
515
516    /// Exit-path terminator: closes every session in `Immediate` mode so a
517    /// live PTY child is group-SIGKILLed instead of waiting out the SIGTERM
518    /// grace window. Callers still bound this with an outer timeout; the OS
519    /// reaps any remainder at process exit.
520    pub(crate) async fn terminate_all_sessions_for_exit_async(&self) -> Result<()> {
521        self.terminate_all_sessions_with_mode_async(PtyCloseMode::Immediate).await
522    }
523
524    async fn terminate_all_sessions_with_mode_async(&self, mode: PtyCloseMode) -> Result<()> {
525        let ids = {
526            let sessions = self.sessions.read().await;
527            sessions.keys().cloned().collect::<Vec<_>>()
528        };
529
530        // Parallel close: sequential closes sum per-session timeouts (12s
531        // inner cap each) into a multi-second exit tail. Concurrent closes
532        // overlap as max instead of sum; the caller's outer timeout
533        // (EXIT_BACKGROUND_SHUTDOWN_TIMEOUT) still bounds the total.
534        // Early return when empty avoids even the pipe-manager lock.
535        if ids.is_empty() {
536            return self.pipe_sessions.terminate_all_sessions().await;
537        }
538
539        let results = futures::future::join_all(ids.into_iter().map(|session_id| async move {
540            self.close_session_with_mode(&session_id, mode)
541                .await
542                .map_err(|err| format!("{session_id}: {err}"))
543        }))
544        .await;
545
546        let mut failures: Vec<String> = results.into_iter().filter_map(|r| r.err()).collect();
547
548        if let Err(err) = self.pipe_sessions.terminate_all_sessions().await {
549            failures.push(err.to_string());
550        }
551
552        if failures.is_empty() {
553            Ok(())
554        } else {
555            Err(anyhow!("failed to terminate all exec sessions: {}", failures.join("; ")))
556        }
557    }
558
559    pub(crate) async fn terminate_active_sessions_async(&self) -> Result<()> {
560        self.terminate_active_sessions_with_mode_async(PtyCloseMode::Graceful).await
561    }
562
563    /// Exit-path variant of [`Self::terminate_active_sessions_async`] using
564    /// `Immediate` PTY termination (see [`Self::terminate_all_sessions_for_exit_async`]).
565    pub(crate) async fn terminate_active_sessions_for_exit_async(&self) -> Result<()> {
566        self.terminate_active_sessions_with_mode_async(PtyCloseMode::Immediate).await
567    }
568
569    async fn terminate_active_sessions_with_mode_async(&self, mode: PtyCloseMode) -> Result<()> {
570        let ids = {
571            let sessions = self.sessions.read().await;
572            sessions
573                .values()
574                .filter(|record| !record.background.load(Ordering::Acquire))
575                .map(|record| record.metadata.id.clone())
576                .collect::<Vec<_>>()
577        };
578
579        if ids.is_empty() {
580            return Ok(());
581        }
582
583        // Parallel close for the same reason as terminate_all: avoid summing
584        // per-session timeouts on the exit path.
585        let results: Vec<Result<(), String>> =
586            futures::future::join_all(ids.into_iter().map(|session_id| async move {
587                let should_close = self
588                    .session_record(session_id.as_str())
589                    .await
590                    .map(|record| !record.background.load(Ordering::Acquire))
591                    .unwrap_or(false);
592                if !should_close {
593                    return Ok(());
594                }
595                self.close_session_with_mode(&session_id, mode)
596                    .await
597                    .map(|_| ())
598                    .map_err(|err| format!("{session_id}: {err}"))
599            }))
600            .await;
601
602        let failures: Vec<String> = results.into_iter().filter_map(|r| r.err()).collect();
603
604        if failures.is_empty() {
605            Ok(())
606        } else {
607            Err(anyhow!("failed to terminate active exec sessions: {}", failures.join("; ")))
608        }
609    }
610
611    /// Force-stop every foreground exec session and close it. Used by the TUI
612    /// ForceCancel escape hatch so a stuck PTY cannot keep the composer locked.
613    /// Closing after the kill is intentional: `force_terminate_or_close` alone
614    /// leaves live sessions attached ("remains visible until closed"), which
615    /// would keep the foreground counter elevated. Background sessions are
616    /// user-owned and are left alone. Returns `(stopped, closed, failed)`
617    /// counts where `stopped` are live kills and `closed` are already-exited
618    /// sessions removed from the map.
619    pub async fn force_cancel_foreground_sessions(&self) -> (usize, usize, usize) {
620        let ids = {
621            let sessions = self.sessions.read().await;
622            sessions
623                .values()
624                .filter(|record| !record.background.load(Ordering::Acquire))
625                .map(|record| record.metadata.id.clone())
626                .collect::<Vec<_>>()
627        };
628
629        let mut stopped = 0usize;
630        let mut closed = 0usize;
631        let mut failed = 0usize;
632        for session_id in ids {
633            let was_running = self.is_session_completed(session_id.as_str()).await.ok().flatten().is_none();
634            if was_running {
635                if let Err(error) = self.force_terminate_session(session_id.as_str()).await {
636                    tracing::warn!(%session_id, %error, "force-cancel terminate failed");
637                }
638            }
639            match self.close_session(session_id.as_str()).await {
640                Ok(_) => {
641                    if was_running {
642                        stopped += 1;
643                    } else {
644                        closed += 1;
645                    }
646                }
647                Err(error) => {
648                    tracing::warn!(%session_id, %error, "force-cancel close failed");
649                    failed += 1;
650                }
651            }
652        }
653        (stopped, closed, failed)
654    }
655
656    /// Return the number of currently live background process reservations.
657    #[must_use]
658    pub fn active_background_processes(&self) -> usize {
659        self.active_background_processes.load(Ordering::Acquire)
660    }
661
662    /// Request that the current foreground session be promoted to background.
663    ///
664    /// The request is synchronous because it is called by the TUI key-event
665    /// callback. The execution wait loop consumes the request asynchronously
666    /// and performs the metadata transition without killing the process.
667    pub fn request_foreground_background(&self) -> Option<BackgroundShortcutResult> {
668        let mut request = self.background_request.lock();
669        if request.is_some() {
670            *self.background_shortcut_result.lock() = Some(BackgroundShortcutResult::Requested);
671            return Some(BackgroundShortcutResult::Requested);
672        }
673
674        // Take the foreground lock after `background_request`. Completion and
675        // close paths use the same order when clearing a pending promotion;
676        // holding both here prevents a completed session from being observed
677        // between the foreground lookup and request reservation.
678        let Some(session_id) = self.foreground_session.lock().clone() else {
679            *self.background_shortcut_result.lock() = None;
680            return None;
681        };
682
683        let result = match self.reserve_background_slot() {
684            Ok(_) => {
685                *request = Some(session_id);
686                BackgroundShortcutResult::Requested
687            }
688            Err(_) => BackgroundShortcutResult::AtCapacity,
689        };
690        *self.background_shortcut_result.lock() = Some(result);
691        Some(result)
692    }
693
694    /// Consume the result associated with the queued Ctrl+B event.
695    pub fn take_background_shortcut_result(&self) -> Option<BackgroundShortcutResult> {
696        self.background_shortcut_result.lock().take()
697    }
698
699    /// Apply a pending Ctrl+B promotion to the specified session.
700    pub(crate) async fn promote_requested_session(&self, session_id: &str) -> Result<bool> {
701        let _lifecycle_guard = self.create_lock.lock().await;
702        if !self.take_foreground_promotion_request(session_id) {
703            return Ok(false);
704        }
705
706        let record = match self.session_record(session_id).await {
707            Ok(record) => record,
708            Err(error) => {
709                self.release_reserved_background_slot(true);
710                return Err(error);
711            }
712        };
713        if record.background.load(Ordering::Acquire) {
714            self.release_reserved_background_slot(true);
715            self.clear_foreground_session(session_id);
716            return Ok(false);
717        }
718        match self.is_session_completed(session_id).await {
719            Ok(Some(_)) => {
720                self.release_reserved_background_slot(true);
721                self.clear_foreground_session(session_id);
722                return Ok(false);
723            }
724            Ok(None) => {}
725            Err(error) => {
726                self.release_reserved_background_slot(true);
727                self.set_foreground_session(ExecSessionId::new(session_id));
728                return Err(error);
729            }
730        }
731
732        record.background_slot_reserved.store(true, Ordering::Release);
733        self.release_foreground_pty_count(&record);
734        record.background.store(true, Ordering::Release);
735        record.show_in_background_drawer.store(true, Ordering::Release);
736        self.clear_foreground_session(session_id);
737        let promotion_marker = Arc::clone(&record);
738        self.start_background_watcher(record, session_id.to_string());
739        promotion_marker
740            .background_promoted_from_foreground
741            .store(true, Ordering::Release);
742        Ok(true)
743    }
744
745    pub(crate) async fn take_foreground_promotion(&self, session_id: &str) -> Result<bool> {
746        let record = self.session_record(session_id).await?;
747        Ok(record.background_promoted_from_foreground.swap(false, Ordering::AcqRel))
748    }
749
750    fn reserve_background_slot(&self) -> Result<bool> {
751        let mut current = self.active_background_processes.load(Ordering::Acquire);
752        loop {
753            if current >= MAX_BACKGROUND_PROCESSES {
754                bail!(
755                    "maximum background process limit reached ({MAX_BACKGROUND_PROCESSES}); wait for or close an existing background session before starting another"
756                );
757            }
758            match self.active_background_processes.compare_exchange(
759                current,
760                current + 1,
761                Ordering::AcqRel,
762                Ordering::Acquire,
763            ) {
764                Ok(_) => return Ok(true),
765                Err(observed) => current = observed,
766            }
767        }
768    }
769
770    fn release_reserved_background_slot(&self, reserved: bool) {
771        if reserved {
772            self.active_background_processes.fetch_sub(1, Ordering::AcqRel);
773        }
774    }
775
776    fn release_background_slot(&self, record: &ExecSessionRecord) {
777        if record.background_slot_reserved.swap(false, Ordering::AcqRel) {
778            self.active_background_processes.fetch_sub(1, Ordering::AcqRel);
779        }
780    }
781
782    fn count_foreground_pty_session(&self, record: &ExecSessionRecord) {
783        let Some(counter) = self.foreground_pty_counter.lock().as_ref().map(Arc::clone) else {
784            return;
785        };
786        counter.fetch_add(1, Ordering::Relaxed);
787        *record.foreground_pty_counter.lock() = Some(counter);
788    }
789
790    fn release_foreground_pty_count(&self, record: &ExecSessionRecord) {
791        let Some(counter) = record.foreground_pty_counter.lock().take() else {
792            return;
793        };
794        let _ = counter.try_update(Ordering::AcqRel, Ordering::Acquire, |current| current.checked_sub(1));
795    }
796
797    fn clear_foreground_and_take_pending_request(&self, session_id: &str) -> bool {
798        let mut request = self.background_request.lock();
799        let taken = request.as_deref() == Some(session_id) && request.take().is_some();
800        let mut foreground = self.foreground_session.lock();
801        if foreground.as_deref() == Some(session_id) {
802            *foreground = None;
803        }
804        drop(foreground);
805        if taken {
806            *self.background_shortcut_result.lock() = None;
807        }
808        taken
809    }
810
811    fn take_foreground_promotion_request(&self, session_id: &str) -> bool {
812        let mut request = self.background_request.lock();
813        if request.as_deref() != Some(session_id) || request.take().is_none() {
814            return false;
815        }
816        let mut foreground = self.foreground_session.lock();
817        if foreground.as_deref() == Some(session_id) {
818            *foreground = None;
819        }
820        drop(foreground);
821        *self.background_shortcut_result.lock() = None;
822        true
823    }
824
825    fn release_pending_background_request(&self, session_id: &str) {
826        if self.clear_foreground_and_take_pending_request(session_id) {
827            self.release_reserved_background_slot(true);
828        }
829    }
830
831    fn start_background_watcher(&self, record: Arc<ExecSessionRecord>, session_id: String) {
832        let manager = self.clone();
833        let record_for_task = Arc::clone(&record);
834        let task = tokio::spawn(async move {
835            loop {
836                match manager.is_session_completed(session_id.as_str()).await {
837                    Ok(Some(exit_code)) => {
838                        record_for_task.completed_at.lock().get_or_insert_with(Utc::now);
839                        manager.capture_background_completion_output(session_id.as_str()).await;
840                        if record_for_task
841                            .background_completion_published
842                            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
843                            .is_ok()
844                        {
845                            let command = bounded_completion_command(&record_for_task.metadata.command_label());
846                            let _ = manager.completion_tx.send(ExecSessionCompletionEvent {
847                                session_id: ExecSessionId::new(session_id.clone()),
848                                command,
849                                managed_background: !record_for_task.show_in_background_drawer.load(Ordering::Acquire),
850                                termination_requested: record_for_task.termination_requested.load(Ordering::Acquire),
851                                exit_code,
852                            });
853                            // Keep one wake permit when the idle loop has not
854                            // entered its wait yet; the broadcast receiver
855                            // drains every completion that accumulated behind
856                            // the single permit.
857                            manager.completion_notify.notify_one();
858                        }
859                        manager.release_background_slot(&record_for_task);
860                        break;
861                    }
862                    Ok(None) => tokio::time::sleep(tokio::time::Duration::from_millis(50)).await,
863                    Err(_) => {
864                        // A transient status error must not release the live
865                        // background reservation. Only a removed session ends
866                        // this watcher without a confirmed process exit; its
867                        // close path owns the reservation release.
868                        if manager.session_record(session_id.as_str()).await.is_err() {
869                            break;
870                        }
871                        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
872                    }
873                }
874            }
875        });
876        if let Some(previous) = record.background_watch.lock().replace(task) {
877            previous.abort();
878        }
879    }
880
881    async fn capture_background_completion_output(&self, session_id: &str) {
882        let deadline = tokio::time::Instant::now() + EXEC_SESSION_COMPLETION_DRAIN_TIMEOUT;
883        loop {
884            let _ = self.read_session_output(session_id, false).await;
885            if self.is_output_drained(session_id).await.unwrap_or(false) || tokio::time::Instant::now() >= deadline {
886                break;
887            }
888            tokio::time::sleep(EXEC_SESSION_COMPLETION_DRAIN_POLL).await;
889        }
890        // Capture bytes that raced with the final drain-state observation.
891        let _ = self.read_session_output(session_id, false).await;
892    }
893
894    fn start_foreground_watcher(&self, record: Arc<ExecSessionRecord>, session_id: String) {
895        let manager = self.clone();
896        let record_for_task = Arc::clone(&record);
897        let task = tokio::spawn(async move {
898            loop {
899                if manager.promote_requested_session(session_id.as_str()).await.unwrap_or(false) {
900                    break;
901                }
902                if record_for_task.background.load(Ordering::Acquire) {
903                    break;
904                }
905                match manager.is_session_completed(session_id.as_str()).await {
906                    Ok(Some(_)) => {
907                        manager.release_foreground_pty_count(&record_for_task);
908                        manager.release_pending_background_request(session_id.as_str());
909                        break;
910                    }
911                    Ok(None) => tokio::time::sleep(tokio::time::Duration::from_millis(50)).await,
912                    Err(_) => {
913                        if manager.session_record(session_id.as_str()).await.is_err() {
914                            break;
915                        }
916                        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
917                    }
918                }
919            }
920        });
921        if let Some(previous) = record.foreground_watch.lock().replace(task) {
922            previous.abort();
923        }
924    }
925
926    fn set_foreground_session(&self, session_id: ExecSessionId) {
927        *self.foreground_session.lock() = Some(session_id);
928    }
929
930    fn clear_foreground_session(&self, session_id: &str) {
931        let mut foreground = self.foreground_session.lock();
932        if foreground.as_deref() == Some(session_id) {
933            *foreground = None;
934        }
935    }
936
937    fn clear_focused_session_if_matches(&self, session_id: &str) {
938        let mut focused = self.focused_session.lock();
939        if focused.as_deref().is_some_and(|id| id == session_id) {
940            *focused = None;
941        }
942    }
943
944    async fn insert_session(
945        &self,
946        metadata: VTCodeExecSession,
947        backend: ExecSessionBackend,
948        pty_guard: Option<PtySessionGuard>,
949        launch_mode: ExecSessionLaunchMode,
950        background_slot_reserved: bool,
951    ) -> Result<Arc<ExecSessionRecord>> {
952        let mut sessions = self.sessions.write().await;
953        use hashbrown::hash_map::Entry;
954        match sessions.entry(metadata.id.clone()) {
955            Entry::Occupied(_) => Err(anyhow!("exec session '{}' already exists", metadata.id.as_str())),
956            Entry::Vacant(entry) => {
957                let record = Arc::new(ExecSessionRecord::new(
958                    metadata,
959                    backend,
960                    pty_guard,
961                    launch_mode,
962                    background_slot_reserved,
963                ));
964                // Foreground PTY and pipe sessions both support Ctrl+B backgrounding,
965                // so both increment the shared foreground counter driving the TUI hint.
966                if launch_mode.sets_foreground_session() {
967                    self.count_foreground_pty_session(&record);
968                }
969                entry.insert(Arc::clone(&record));
970                Ok(record)
971            }
972        }
973    }
974
975    async fn ensure_session_absent(&self, session_id: &str) -> Result<()> {
976        let sessions = self.sessions.read().await;
977        if sessions.contains_key(session_id) {
978            return Err(anyhow!("exec session '{session_id}' already exists"));
979        }
980        Ok(())
981    }
982
983    pub(crate) async fn session_record(&self, session_id: &str) -> Result<Arc<ExecSessionRecord>> {
984        let sessions = self.sessions.read().await;
985        sessions
986            .get(session_id)
987            .cloned()
988            .ok_or_else(|| missing_exec_session_error(session_id))
989    }
990}