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