1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//! PTY-related ToolRegistry accessors.
use std::collections::HashSet;
use std::future::Future;
use std::sync::Arc;
use anyhow::Result;
use crate::config::PtyConfig;
use crate::tools::exec_session::ExecSessionManager;
use crate::tools::pty::PtyManager;
use super::ToolRegistry;
use super::pty;
impl ToolRegistry {
pub fn pty_manager(&self) -> &PtyManager {
self.pty_sessions.manager()
}
pub fn pty_config(&self) -> &PtyConfig {
self.pty_sessions.config()
}
pub fn can_start_pty_session(&self) -> bool {
self.pty_sessions.can_start_session()
}
pub fn start_pty_session(&self) -> Result<pty::PtySessionGuard> {
self.pty_sessions.start_session()
}
pub fn end_pty_session(&self) {
self.pty_sessions.end_session();
}
pub fn active_pty_sessions(&self) -> usize {
self.pty_sessions.active_sessions()
}
pub fn terminate_all_pty_sessions(&self) {
self.pty_sessions.terminate_all();
}
/// Inline-delegating wrapper over [`pty::PtySessionManager::terminate_all_async`].
/// Returns the inner future directly to avoid an extra coroutine state machine
/// (per the async-state-machine bloat audit, section 16).
pub fn terminate_all_pty_sessions_async(&self) -> impl Future<Output = Result<()>> + '_ {
self.pty_sessions.terminate_all_async()
}
/// Terminates every exec session, then retires verification bookkeeping
/// for the sessions that are actually gone (see
/// [`Self::terminate_exec_sessions_and_observe_cleanup`]).
pub async fn terminate_all_exec_sessions_async(&self) -> Result<()> {
self.terminate_exec_sessions_and_observe_cleanup(false, false).await
}
/// Exit-path variant: terminates every exec session with `Immediate` PTY
/// semantics (group SIGKILL, no SIGTERM grace window) so user-initiated
/// exit is not parked ~600 ms per live PTY session.
pub async fn terminate_all_exec_sessions_for_exit_async(&self) -> Result<()> {
self.terminate_exec_sessions_and_observe_cleanup(false, true).await
}
/// Terminates only foreground exec sessions after a turn interruption,
/// preserving user-owned background sessions, then retires verification
/// bookkeeping for the sessions that are actually gone.
pub async fn terminate_active_exec_sessions_async(&self) -> Result<()> {
self.terminate_exec_sessions_and_observe_cleanup(true, false).await
}
/// Exit-path variant of [`Self::terminate_active_exec_sessions_async`]
/// using `Immediate` PTY termination.
pub async fn terminate_active_exec_sessions_for_exit_async(&self) -> Result<()> {
self.terminate_exec_sessions_and_observe_cleanup(true, true).await
}
/// Shared bulk-termination path: snapshots the in-scope session ids,
/// terminates, then retires verification bookkeeping for the sessions
/// that are actually gone. Only gone ids are observed so a live mutator
/// (e.g. when termination partially fails) keeps its pending boundary.
/// Verification debt (`generation`) is preserved; only the
/// terminated-session block is released so fresh checks can satisfy it.
async fn terminate_exec_sessions_and_observe_cleanup(&self, active_only: bool, immediate: bool) -> Result<()> {
let before = self.scoped_exec_session_ids(active_only).await;
let result = if immediate {
if active_only {
self.exec_sessions.terminate_active_sessions_for_exit_async().await
} else {
self.exec_sessions.terminate_all_sessions_for_exit_async().await
}
} else if active_only {
self.exec_sessions.terminate_active_sessions_async().await
} else {
self.exec_sessions.terminate_all_sessions_async().await
};
self.observe_terminated_exec_sessions(before).await;
result
}
pub fn exec_session_manager(&self) -> ExecSessionManager {
self.exec_sessions.clone()
}
/// Force-stop every foreground exec session and close it (TUI
/// ForceCancel escape hatch), then retire verification bookkeeping for
/// the sessions that are actually gone so a force-cancelled mutator
/// cannot strand `pending_mutation_sessions` forever. Returns
/// `(stopped, closed, failed)` counts from the session manager.
/// Background sessions are user-owned and are left alone.
pub async fn force_cancel_foreground_sessions_and_observe_cleanup(&self) -> (usize, usize, usize) {
let before = self.scoped_exec_session_ids(true).await;
let counts = self.exec_sessions.force_cancel_foreground_sessions().await;
self.observe_terminated_exec_sessions(before).await;
counts
}
/// Snapshot the ids of in-scope exec sessions (foreground only when
/// `active_only`) for post-cleanup reconciliation.
async fn scoped_exec_session_ids(&self, active_only: bool) -> Vec<String> {
self.exec_sessions
.list_sessions()
.await
.into_iter()
.filter(|session| !active_only || !session.background)
.map(|session| session.id.as_str().to_owned())
.collect()
}
/// Retire verification bookkeeping for snapshotted ids that are gone
/// now. Only gone ids are observed so a live mutator (e.g. when
/// termination partially fails) keeps its pending boundary. Verification
/// debt is preserved; only the terminated-session block is released.
async fn observe_terminated_exec_sessions(&self, before: Vec<String>) {
if before.is_empty() {
return;
}
let remaining: HashSet<String> = self
.exec_sessions
.list_sessions()
.await
.into_iter()
.map(|session| session.id.as_str().to_owned())
.collect();
let terminated: Vec<String> = before.into_iter().filter(|id| !remaining.contains(id)).collect();
if !terminated.is_empty() {
self.observe_completion_exec_sessions_terminated(&terminated);
}
}
/// Set the active PTY sessions counter for tracking
pub fn set_active_pty_sessions(&self, counter: Arc<std::sync::atomic::AtomicUsize>) {
self.exec_sessions.set_foreground_pty_counter(Arc::clone(&counter));
if let Ok(mut guard) = self.active_pty_sessions.write() {
*guard = Some(counter);
}
}
/// Increment active PTY sessions count
pub fn increment_active_pty_sessions(&self) {
if let Some(counter) = self
.active_pty_sessions
.read()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.map(Arc::clone)
{
counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
}
/// Decrement active PTY sessions count
pub fn decrement_active_pty_sessions(&self) {
if let Some(counter) = self
.active_pty_sessions
.read()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.map(Arc::clone)
{
counter.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
/// Get the current active PTY sessions count
pub fn active_pty_sessions_count(&self) -> usize {
self.active_pty_sessions
.read()
.ok()
.and_then(|g| g.as_ref().map(|c| c.load(std::sync::atomic::Ordering::Relaxed)))
.unwrap_or(0)
}
}