Skip to main content

agent_hub_runtime/core/terminal/
mod.rs

1//! Interactive PTY resources shared by desktop adapters and core callers.
2mod agent_input;
3pub mod clipboard;
4pub(crate) mod interactive;
5pub(crate) mod launch_command;
6mod process;
7mod script;
8pub use script::prepare_script;
9mod session;
10mod shell;
11use anyhow::{bail, Result};
12use portable_pty::{CommandBuilder, PtySize};
13use serde::{Deserialize, Serialize};
14use session::Session;
15pub use shell::{prepare_shell, LaunchState, ShellIntegration};
16use std::{
17    collections::{HashMap, HashSet},
18    path::PathBuf,
19    sync::{Arc, Mutex},
20};
21
22/// Maximum number of active or reserved terminal panes per workspace window.
23pub const TERMINAL_PANE_LIMIT: usize = 99;
24
25#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
26pub struct TerminalSize {
27    pub rows: u16,
28    pub cols: u16,
29}
30
31#[derive(Debug, Deserialize, Serialize)]
32pub struct TerminalDisplay {
33    pub fg: Option<String>,
34    pub bg: Option<String>,
35    pub cursor: Option<String>,
36}
37impl TerminalSize {
38    pub fn validate(self) -> Result<()> {
39        self.pty().map(|_| ())
40    }
41
42    fn pty(self) -> Result<PtySize> {
43        if self.rows == 0 || self.cols == 0 || self.rows > 1000 || self.cols > 2000 {
44            bail!("Terminal dimensions are outside the supported range");
45        }
46        Ok(PtySize {
47            rows: self.rows,
48            cols: self.cols,
49            pixel_width: 0,
50            pixel_height: 0,
51        })
52    }
53}
54
55pub struct TerminalSpec {
56    pub project_id: String,
57    pub cwd: PathBuf,
58    pub command: CommandBuilder,
59    pub integration: Option<ShellIntegration>,
60    pub size: TerminalSize,
61}
62
63/// A terminal and any resource created exclusively for its lifetime.
64pub struct PreparedTerminal {
65    pub spec: TerminalSpec,
66    pub resource: Option<Box<dyn Send>>,
67    pub core_terminal: Option<CoreTerminalIdentity>,
68}
69
70impl From<TerminalSpec> for PreparedTerminal {
71    fn from(spec: TerminalSpec) -> Self {
72        Self {
73            spec,
74            resource: None,
75            core_terminal: None,
76        }
77    }
78}
79
80#[derive(Clone, Debug, Serialize)]
81pub struct CoreTerminalIdentity {
82    pub session: String,
83    pub pane_id: String,
84    pub terminal_id: String,
85    #[serde(skip)]
86    pub(crate) preserve_on_detach: Arc<std::sync::atomic::AtomicBool>,
87}
88
89#[derive(Clone, Debug, Serialize)]
90pub struct TerminalSession {
91    pub id: String,
92    pub project_id: String,
93    pub cwd: String,
94    pub exited: bool,
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub core_terminal: Option<CoreTerminalIdentity>,
97}
98
99#[derive(Clone, Debug, Serialize)]
100#[serde(tag = "kind", rename_all = "snake_case")]
101pub enum TerminalEvent {
102    Output { seq: u64, data: String },
103    HerdrActivity { active: bool },
104    Exit { code: u32 },
105    Error { message: String },
106}
107
108type Sink = Arc<dyn Fn(TerminalEvent) -> bool + Send + Sync>;
109#[derive(Default)]
110struct Sessions {
111    items: HashMap<String, Arc<Session>>,
112    pending: HashMap<String, usize>,
113    generations: HashMap<String, u64>,
114    closed_owners: HashSet<String>,
115    shutting_down: bool,
116}
117#[derive(Default)]
118pub struct TerminalManager {
119    sessions: Mutex<Sessions>,
120}
121
122impl TerminalManager {
123    pub fn create(
124        &self,
125        owner: &str,
126        spec: TerminalSpec,
127        sink: impl Fn(TerminalEvent) -> bool + Send + Sync + 'static,
128    ) -> Result<TerminalSession> {
129        self.create_with(owner, || Ok(spec), sink)
130    }
131
132    /// Reserve capacity before preparing a slow external program.
133    pub fn create_with(
134        &self,
135        owner: &str,
136        prepare: impl FnOnce() -> Result<TerminalSpec>,
137        sink: impl Fn(TerminalEvent) -> bool + Send + Sync + 'static,
138    ) -> Result<TerminalSession> {
139        self.create_prepared(owner, || prepare().map(PreparedTerminal::from), sink)
140    }
141
142    pub fn create_prepared(
143        &self,
144        owner: &str,
145        prepare: impl FnOnce() -> Result<PreparedTerminal>,
146        sink: impl Fn(TerminalEvent) -> bool + Send + Sync + 'static,
147    ) -> Result<TerminalSession> {
148        let generation = {
149            let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
150            if sessions.shutting_down || sessions.closed_owners.contains(owner) {
151                bail!("Terminal manager is shutting down");
152            }
153            if sessions.items.values().filter(|s| s.owner == owner).count()
154                + sessions.pending.get(owner).copied().unwrap_or(0)
155                >= TERMINAL_PANE_LIMIT
156            {
157                bail!("Close an existing terminal before opening another (limit: {TERMINAL_PANE_LIMIT})");
158            }
159            *sessions.pending.entry(owner.into()).or_default() += 1;
160            *sessions.generations.entry(owner.into()).or_default()
161        };
162        let created = prepare().and_then(|spec| Session::spawn(owner, spec, Arc::new(sink)));
163        let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
164        if let Some(pending) = sessions.pending.get_mut(owner) {
165            *pending -= 1;
166        }
167        let session = created?;
168        if sessions.shutting_down || sessions.generations.get(owner) != Some(&generation) {
169            drop(sessions);
170            session.close();
171            bail!("Terminal manager is shutting down");
172        }
173        let snapshot = session.snapshot();
174        sessions.items.insert(snapshot.id.clone(), session);
175        Ok(snapshot)
176    }
177
178    fn session(&self, owner: &str, id: &str) -> Result<Arc<Session>> {
179        let sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
180        let session = sessions
181            .items
182            .get(id)
183            .ok_or_else(|| anyhow::anyhow!("Terminal is closed"))?;
184        if session.owner != owner {
185            bail!("Terminal belongs to another window");
186        }
187        Ok(session.clone())
188    }
189    pub fn write(&self, owner: &str, id: &str, bytes: Vec<u8>) -> Result<()> {
190        self.session(owner, id)?.write(bytes)
191    }
192    pub fn mark_native_agent(&self, owner: &str, id: &str) -> Result<()> {
193        self.session(owner, id)?.mark_native_agent();
194        Ok(())
195    }
196    pub fn agent_prompt(&self, owner: &str, id: &str, prompt: &str) -> Result<()> {
197        self.session(owner, id)?.agent_prompt(prompt)
198    }
199    pub fn resize(&self, owner: &str, id: &str, size: TerminalSize) -> Result<()> {
200        self.session(owner, id)?.resize(size.pty()?)
201    }
202    pub fn ack(&self, owner: &str, id: &str, seq: u64) -> Result<()> {
203        self.session(owner, id)?.ack(seq)
204    }
205    pub fn launch_state(&self, owner: &str, id: &str) -> Result<LaunchState> {
206        Ok(self.session(owner, id)?.launch_state())
207    }
208    pub fn list(&self, owner: &str) -> Result<Vec<TerminalSession>> {
209        Ok(self
210            .sessions
211            .lock()
212            .unwrap_or_else(|e| e.into_inner())
213            .items
214            .values()
215            .filter(|s| s.owner == owner)
216            .map(|s| s.snapshot())
217            .collect())
218    }
219    pub fn close(&self, owner: &str, id: &str) -> Result<()> {
220        self.remove(owner, id, false)
221    }
222    pub fn detach(&self, owner: &str, id: &str) -> Result<()> {
223        self.remove(owner, id, true)
224    }
225    fn remove(&self, owner: &str, id: &str, preserve_core: bool) -> Result<()> {
226        let session = self.session(owner, id)?;
227        self.sessions
228            .lock()
229            .unwrap_or_else(|e| e.into_inner())
230            .items
231            .remove(id);
232        if preserve_core {
233            session.detach();
234        } else {
235            session.close();
236        }
237        Ok(())
238    }
239    /// Reopen a trusted workspace identity before accepting new terminal requests.
240    pub fn open_owner(&self, owner: &str) {
241        self.sessions
242            .lock()
243            .unwrap_or_else(|e| e.into_inner())
244            .closed_owners
245            .remove(owner);
246    }
247    /// Atomically reject pending launches and detach PTYs; run cleanup off the UI thread.
248    pub fn detach_owner(&self, owner: &str) -> impl FnOnce() + Send + 'static {
249        let items = {
250            let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
251            sessions.closed_owners.insert(owner.into());
252            *sessions.generations.entry(owner.into()).or_default() += 1;
253            let ids: Vec<_> = sessions
254                .items
255                .iter()
256                .filter(|(_, s)| s.owner == owner)
257                .map(|(id, _)| id.clone())
258                .collect();
259            ids.into_iter()
260                .filter_map(|id| sessions.items.remove(&id))
261                .collect::<Vec<_>>()
262        };
263        move || {
264            for session in items {
265                session.detach();
266            }
267        }
268    }
269    /// Release only the PTYs owned by a closing workspace.
270    pub fn close_owner(&self, owner: &str) {
271        self.detach_owner(owner)();
272    }
273    pub fn close_all(&self) {
274        let items = {
275            let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
276            sessions.shutting_down = true;
277            std::mem::take(&mut sessions.items)
278        };
279        for session in items.into_values() {
280            session.detach();
281        }
282    }
283}
284impl Drop for TerminalManager {
285    fn drop(&mut self) {
286        self.close_all();
287    }
288}