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 (the TUI
616    /// ForceCancel escape hatch). Closing after the kill is intentional:
617    /// `force_terminate_or_close` alone leaves live sessions attached, which
618    /// would keep the foreground counter elevated. Background sessions are
619    /// user-owned and are left alone. Returns `(stopped, closed, failed)` counts.
620    pub async fn force_cancel_foreground_sessions(&self) -> (usize, usize, usize) {
621        self.force_cancel_sessions_matching(|background| !background).await
622    }
623
624    /// Force-stop every exec session, background ones included: a forced stop
625    /// is "stop means stop" — the stop ending the turn also ends the work
626    /// background sessions carry. Only the forced teardown reaches this.
627    pub async fn force_cancel_all_sessions(&self) -> (usize, usize, usize) {
628        self.force_cancel_sessions_matching(|_| true).await
629    }
630
631    /// Kill each selected session's process group, then close it so it cannot
632    /// linger attached. Sessions are killed concurrently: one wedged
633    /// session's bounded close (up to [`EXEC_SESSION_CLOSE_TIMEOUT`]) must
634    /// not starve the terminate signals owed to the remaining sessions under
635    /// the escalation's 5s budget. Returns `(stopped, closed, failed)` counts.
636    async fn force_cancel_sessions_matching(&self, keep: impl Fn(bool) -> bool) -> (usize, usize, usize) {
637        let sessions = self.sessions.read().await;
638        let ids: Vec<_> = sessions
639            .values()
640            .filter(|record| keep(record.background.load(Ordering::Acquire)))
641            .map(|record| record.metadata.id.clone())
642            .collect();
643        drop(sessions);
644        let outcomes = futures::future::join_all(ids.into_iter().map(|session_id| async move {
645            // Even an apparently completed pipe may have a failed wait; ask
646            // the backend to confirm its direct child before detaching it.
647            let was_running = self.is_session_completed(&session_id).await.ok().flatten().is_none();
648            if let Err(error) = self.force_terminate_session(&session_id).await {
649                tracing::warn!(%session_id, %error, "force-cancel terminate failed");
650                return (0, 0, 1);
651            }
652            match self.close_session(&session_id).await {
653                Ok(_) if was_running => (1, 0, 0),
654                Ok(_) => (0, 1, 0),
655                Err(error) => {
656                    tracing::warn!(%session_id, %error, "force-cancel close failed");
657                    (0, 0, 1)
658                }
659            }
660        }))
661        .await;
662        outcomes.into_iter().fold((0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2))
663    }
664
665    /// Return the number of currently live background process reservations.
666    #[must_use]
667    pub fn active_background_processes(&self) -> usize {
668        self.active_background_processes.load(Ordering::Acquire)
669    }
670
671    /// Request that the current foreground session be promoted to background.
672    ///
673    /// The request is synchronous because it is called by the TUI key-event
674    /// callback. The execution wait loop consumes the request asynchronously
675    /// and performs the metadata transition without killing the process.
676    pub fn request_foreground_background(&self) -> Option<BackgroundShortcutResult> {
677        let mut request = self.background_request.lock();
678        if request.is_some() {
679            *self.background_shortcut_result.lock() = Some(BackgroundShortcutResult::Requested);
680            return Some(BackgroundShortcutResult::Requested);
681        }
682
683        // Take the foreground lock after `background_request`. Completion and
684        // close paths use the same order when clearing a pending promotion;
685        // holding both here prevents a completed session from being observed
686        // between the foreground lookup and request reservation.
687        let Some(session_id) = self.foreground_session.lock().clone() else {
688            *self.background_shortcut_result.lock() = None;
689            return None;
690        };
691
692        let result = match self.reserve_background_slot() {
693            Ok(_) => {
694                *request = Some(session_id);
695                BackgroundShortcutResult::Requested
696            }
697            Err(_) => BackgroundShortcutResult::AtCapacity,
698        };
699        *self.background_shortcut_result.lock() = Some(result);
700        Some(result)
701    }
702
703    /// Consume the result associated with the queued Ctrl+B event.
704    pub fn take_background_shortcut_result(&self) -> Option<BackgroundShortcutResult> {
705        self.background_shortcut_result.lock().take()
706    }
707
708    /// Apply a pending Ctrl+B promotion to the specified session.
709    pub(crate) async fn promote_requested_session(&self, session_id: &str) -> Result<bool> {
710        let _lifecycle_guard = self.create_lock.lock().await;
711        if !self.take_foreground_promotion_request(session_id) {
712            return Ok(false);
713        }
714
715        let record = match self.session_record(session_id).await {
716            Ok(record) => record,
717            Err(error) => {
718                self.release_reserved_background_slot(true);
719                return Err(error);
720            }
721        };
722        if record.background.load(Ordering::Acquire) {
723            self.release_reserved_background_slot(true);
724            self.clear_foreground_session(session_id);
725            return Ok(false);
726        }
727        match self.is_session_completed(session_id).await {
728            Ok(Some(_)) => {
729                self.release_reserved_background_slot(true);
730                self.clear_foreground_session(session_id);
731                return Ok(false);
732            }
733            Ok(None) => {}
734            Err(error) => {
735                self.release_reserved_background_slot(true);
736                self.set_foreground_session(ExecSessionId::new(session_id));
737                return Err(error);
738            }
739        }
740
741        record.background_slot_reserved.store(true, Ordering::Release);
742        self.release_foreground_pty_count(&record);
743        record.background.store(true, Ordering::Release);
744        record.show_in_background_drawer.store(true, Ordering::Release);
745        self.clear_foreground_session(session_id);
746        let promotion_marker = Arc::clone(&record);
747        self.start_background_watcher(record, session_id.to_string());
748        promotion_marker
749            .background_promoted_from_foreground
750            .store(true, Ordering::Release);
751        Ok(true)
752    }
753
754    pub(crate) async fn take_foreground_promotion(&self, session_id: &str) -> Result<bool> {
755        let record = self.session_record(session_id).await?;
756        Ok(record.background_promoted_from_foreground.swap(false, Ordering::AcqRel))
757    }
758
759    fn reserve_background_slot(&self) -> Result<bool> {
760        let mut current = self.active_background_processes.load(Ordering::Acquire);
761        loop {
762            if current >= MAX_BACKGROUND_PROCESSES {
763                bail!(
764                    "maximum background process limit reached ({MAX_BACKGROUND_PROCESSES}); wait for or close an existing background session before starting another"
765                );
766            }
767            match self.active_background_processes.compare_exchange(
768                current,
769                current + 1,
770                Ordering::AcqRel,
771                Ordering::Acquire,
772            ) {
773                Ok(_) => return Ok(true),
774                Err(observed) => current = observed,
775            }
776        }
777    }
778
779    fn release_reserved_background_slot(&self, reserved: bool) {
780        if reserved {
781            self.active_background_processes.fetch_sub(1, Ordering::AcqRel);
782        }
783    }
784
785    fn release_background_slot(&self, record: &ExecSessionRecord) {
786        if record.background_slot_reserved.swap(false, Ordering::AcqRel) {
787            self.active_background_processes.fetch_sub(1, Ordering::AcqRel);
788        }
789    }
790
791    fn count_foreground_pty_session(&self, record: &ExecSessionRecord) {
792        let Some(counter) = self.foreground_pty_counter.lock().as_ref().map(Arc::clone) else {
793            return;
794        };
795        counter.fetch_add(1, Ordering::Relaxed);
796        *record.foreground_pty_counter.lock() = Some(counter);
797    }
798
799    fn release_foreground_pty_count(&self, record: &ExecSessionRecord) {
800        let Some(counter) = record.foreground_pty_counter.lock().take() else {
801            return;
802        };
803        let _ = counter.try_update(Ordering::AcqRel, Ordering::Acquire, |current| current.checked_sub(1));
804    }
805
806    fn clear_foreground_and_take_pending_request(&self, session_id: &str) -> bool {
807        let mut request = self.background_request.lock();
808        let taken = request.as_deref() == Some(session_id) && request.take().is_some();
809        let mut foreground = self.foreground_session.lock();
810        if foreground.as_deref() == Some(session_id) {
811            *foreground = None;
812        }
813        drop(foreground);
814        if taken {
815            *self.background_shortcut_result.lock() = None;
816        }
817        taken
818    }
819
820    fn take_foreground_promotion_request(&self, session_id: &str) -> bool {
821        let mut request = self.background_request.lock();
822        if request.as_deref() != Some(session_id) || request.take().is_none() {
823            return false;
824        }
825        let mut foreground = self.foreground_session.lock();
826        if foreground.as_deref() == Some(session_id) {
827            *foreground = None;
828        }
829        drop(foreground);
830        *self.background_shortcut_result.lock() = None;
831        true
832    }
833
834    fn release_pending_background_request(&self, session_id: &str) {
835        if self.clear_foreground_and_take_pending_request(session_id) {
836            self.release_reserved_background_slot(true);
837        }
838    }
839
840    fn start_background_watcher(&self, record: Arc<ExecSessionRecord>, session_id: String) {
841        let manager = self.clone();
842        let record_for_task = Arc::clone(&record);
843        let task = tokio::spawn(async move {
844            loop {
845                match manager.is_session_completed(session_id.as_str()).await {
846                    Ok(Some(exit_code)) => {
847                        record_for_task.completed_at.lock().get_or_insert_with(Utc::now);
848                        manager.capture_background_completion_output(session_id.as_str()).await;
849                        if record_for_task
850                            .background_completion_published
851                            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
852                            .is_ok()
853                        {
854                            let command = bounded_completion_command(&record_for_task.metadata.command_label());
855                            let _ = manager.completion_tx.send(ExecSessionCompletionEvent {
856                                session_id: ExecSessionId::new(session_id.clone()),
857                                command,
858                                managed_background: !record_for_task.show_in_background_drawer.load(Ordering::Acquire),
859                                termination_requested: record_for_task.termination_requested.load(Ordering::Acquire),
860                                exit_code,
861                            });
862                            // Keep one wake permit when the idle loop has not
863                            // entered its wait yet; the broadcast receiver
864                            // drains every completion that accumulated behind
865                            // the single permit.
866                            manager.completion_notify.notify_one();
867                        }
868                        manager.release_background_slot(&record_for_task);
869                        break;
870                    }
871                    Ok(None) => tokio::time::sleep(tokio::time::Duration::from_millis(50)).await,
872                    Err(_) => {
873                        // A transient status error must not release the live
874                        // background reservation. Only a removed session ends
875                        // this watcher without a confirmed process exit; its
876                        // close path owns the reservation release.
877                        if manager.session_record(session_id.as_str()).await.is_err() {
878                            break;
879                        }
880                        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
881                    }
882                }
883            }
884        });
885        if let Some(previous) = record.background_watch.lock().replace(task) {
886            previous.abort();
887        }
888    }
889
890    async fn capture_background_completion_output(&self, session_id: &str) {
891        let deadline = tokio::time::Instant::now() + EXEC_SESSION_COMPLETION_DRAIN_TIMEOUT;
892        loop {
893            let _ = self.read_session_output(session_id, false).await;
894            if self.is_output_drained(session_id).await.unwrap_or(false) || tokio::time::Instant::now() >= deadline {
895                break;
896            }
897            tokio::time::sleep(EXEC_SESSION_COMPLETION_DRAIN_POLL).await;
898        }
899        // Capture bytes that raced with the final drain-state observation.
900        let _ = self.read_session_output(session_id, false).await;
901    }
902
903    fn start_foreground_watcher(&self, record: Arc<ExecSessionRecord>, session_id: String) {
904        let manager = self.clone();
905        let record_for_task = Arc::clone(&record);
906        let task = tokio::spawn(async move {
907            loop {
908                if manager.promote_requested_session(session_id.as_str()).await.unwrap_or(false) {
909                    break;
910                }
911                if record_for_task.background.load(Ordering::Acquire) {
912                    break;
913                }
914                match manager.is_session_completed(session_id.as_str()).await {
915                    Ok(Some(_)) => {
916                        manager.release_foreground_pty_count(&record_for_task);
917                        manager.release_pending_background_request(session_id.as_str());
918                        break;
919                    }
920                    Ok(None) => tokio::time::sleep(tokio::time::Duration::from_millis(50)).await,
921                    Err(_) => {
922                        if manager.session_record(session_id.as_str()).await.is_err() {
923                            break;
924                        }
925                        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
926                    }
927                }
928            }
929        });
930        if let Some(previous) = record.foreground_watch.lock().replace(task) {
931            previous.abort();
932        }
933    }
934
935    fn set_foreground_session(&self, session_id: ExecSessionId) {
936        *self.foreground_session.lock() = Some(session_id);
937    }
938
939    fn clear_foreground_session(&self, session_id: &str) {
940        let mut foreground = self.foreground_session.lock();
941        if foreground.as_deref() == Some(session_id) {
942            *foreground = None;
943        }
944    }
945
946    fn clear_focused_session_if_matches(&self, session_id: &str) {
947        let mut focused = self.focused_session.lock();
948        if focused.as_deref().is_some_and(|id| id == session_id) {
949            *focused = None;
950        }
951    }
952
953    async fn insert_session(
954        &self,
955        metadata: VTCodeExecSession,
956        backend: ExecSessionBackend,
957        pty_guard: Option<PtySessionGuard>,
958        launch_mode: ExecSessionLaunchMode,
959        background_slot_reserved: bool,
960    ) -> Result<Arc<ExecSessionRecord>> {
961        let mut sessions = self.sessions.write().await;
962        use hashbrown::hash_map::Entry;
963        match sessions.entry(metadata.id.clone()) {
964            Entry::Occupied(_) => Err(anyhow!("exec session '{}' already exists", metadata.id.as_str())),
965            Entry::Vacant(entry) => {
966                let record = Arc::new(ExecSessionRecord::new(
967                    metadata,
968                    backend,
969                    pty_guard,
970                    launch_mode,
971                    background_slot_reserved,
972                ));
973                // Foreground PTY and pipe sessions both support Ctrl+B backgrounding,
974                // so both increment the shared foreground counter driving the TUI hint.
975                if launch_mode.sets_foreground_session() {
976                    self.count_foreground_pty_session(&record);
977                }
978                entry.insert(Arc::clone(&record));
979                Ok(record)
980            }
981        }
982    }
983
984    async fn ensure_session_absent(&self, session_id: &str) -> Result<()> {
985        let sessions = self.sessions.read().await;
986        if sessions.contains_key(session_id) {
987            return Err(anyhow!("exec session '{session_id}' already exists"));
988        }
989        Ok(())
990    }
991
992    pub(crate) async fn session_record(&self, session_id: &str) -> Result<Arc<ExecSessionRecord>> {
993        let sessions = self.sessions.read().await;
994        sessions
995            .get(session_id)
996            .cloned()
997            .ok_or_else(|| missing_exec_session_error(session_id))
998    }
999}