返回 CodeWhale
host_terminal.rs
根目录 / crates / runtime / src / host_terminal.rs
1 //! The one port through which runtime code causes terminal side effects.
2 //!
3 //! The terminal UI is the only owner of the terminal: it alone toggles raw
4 //! mode and writes escape sequences. Runtime code (tools, the engine, the
5 //! runtime API) never links a terminal library; when it needs a terminal
6 //! effect it asks the installed [`HostTerminal`]. The composition root
7 //! installs the TUI's implementation once at startup, for every host it
8 //! launches today (interactive TUI, `exec`, the runtime API server), so
9 //! behavior is unchanged from when the calls were inline.
10 //!
11 //! With nothing installed every method is a no-op. That is the intended
12 //! future shape for stdio hosts (ACP, MCP server, app-server), whose stdout is
13 //! a JSON-RPC stream that must never receive terminal bytes.
14 //!
15 //! Known limitations: the install is process-global and first-wins; a
16 //! process cannot swap hosts after startup, and tests that need the real
17 //! terminal behavior must go through the TUI's own implementation.
18
19 use std::sync::OnceLock;
20
21 use codewhale_config::notifications::NotificationsConfig;
22
23 /// Terminal side effects the runtime may request from its host.
24 pub trait HostTerminal: Send + Sync {
25 /// Leave raw mode if it is on, so an interactive child process sees a
26 /// cooked terminal. Returns whether raw mode was on (and must be resumed).
27 fn suspend_raw_mode(&self) -> bool;
28
29 /// Re-enter raw mode after [`HostTerminal::suspend_raw_mode`] returned
30 /// `true`.
31 fn resume_raw_mode(&self);
32
33 /// Deliver a model-authored notification (the `notify` tool) now,
34 /// honoring the installed notification settings. Returns the delivery
35 /// receipt the tool reports to the model.
36 fn notify_model(&self, title: &str, body: Option<&str>) -> &'static str;
37
38 /// Record whether the terminal has focus; attention policy reads it.
39 fn set_terminal_focused(&self, focused: bool);
40
41 /// Install the process-wide notification method, category gate, sound
42 /// policy and attention condition from `[notifications]`.
43 fn apply_notification_settings(&self, config: &NotificationsConfig);
44
45 fn begin_turn_chrome(&self) {}
46 }
47
48 struct NoHostTerminal;
49
50 impl HostTerminal for NoHostTerminal {
51 fn suspend_raw_mode(&self) -> bool {
52 false
53 }
54
55 fn resume_raw_mode(&self) {}
56
57 fn notify_model(&self, _title: &str, _body: Option<&str>) -> &'static str {
58 "notification not sent: no terminal host"
59 }
60
61 fn set_terminal_focused(&self, _focused: bool) {}
62
63 fn apply_notification_settings(&self, _config: &NotificationsConfig) {}
64 }
65
66 static HOST: OnceLock<Box<dyn HostTerminal>> = OnceLock::new();
67
68 /// Install the process's terminal host. The first install wins; later calls
69 /// are ignored and return `false`.
70 pub fn install(host: Box<dyn HostTerminal>) -> bool {
71 HOST.set(host).is_ok()
72 }
73
74 /// The installed terminal host, or a no-op host when none is installed.
75 #[must_use]
76 pub fn host() -> &'static dyn HostTerminal {
77 match HOST.get() {
78 Some(host) => host.as_ref(),
79 None => &NoHostTerminal,
80 }
81 }
82
83 /// Raw mode suspended for the lifetime of this guard (issue #1690).
84 ///
85 /// Created by [`suspend_raw_mode`]; dropping it resumes raw mode only if it
86 /// was on when the guard was created.
87 #[must_use = "raw mode is resumed when the guard drops"]
88 pub struct RawModeSuspension {
89 /// The host that suspended raw mode resumes it.
90 host: &'static dyn HostTerminal,
91 resume: bool,
92 }
93
94 /// Leave raw mode around an interactive child; resume it when the returned
95 /// guard drops, only if it was on to begin with.
96 pub fn suspend_raw_mode() -> RawModeSuspension {
97 suspend_raw_mode_on(host())
98 }
99
100 fn suspend_raw_mode_on(host: &'static dyn HostTerminal) -> RawModeSuspension {
101 RawModeSuspension {
102 host,
103 resume: host.suspend_raw_mode(),
104 }
105 }
106
107 impl Drop for RawModeSuspension {
108 fn drop(&mut self) {
109 if self.resume {
110 self.host.resume_raw_mode();
111 }
112 }
113 }
114
115 #[cfg(test)]
116 mod tests {
117 use super::*;
118 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
119
120 /// Records raw-mode calls. Each test owns its own `static` instance, so
121 /// they never share counters.
122 struct CountingHost {
123 raw: AtomicBool,
124 suspends: AtomicUsize,
125 resumes: AtomicUsize,
126 }
127
128 impl CountingHost {
129 const fn new(raw: bool) -> Self {
130 Self {
131 raw: AtomicBool::new(raw),
132 suspends: AtomicUsize::new(0),
133 resumes: AtomicUsize::new(0),
134 }
135 }
136 }
137
138 impl HostTerminal for CountingHost {
139 fn suspend_raw_mode(&self) -> bool {
140 self.suspends.fetch_add(1, Ordering::SeqCst);
141 self.raw.swap(false, Ordering::SeqCst)
142 }
143
144 fn resume_raw_mode(&self) {
145 self.resumes.fetch_add(1, Ordering::SeqCst);
146 self.raw.store(true, Ordering::SeqCst);
147 }
148
149 fn notify_model(&self, _title: &str, _body: Option<&str>) -> &'static str {
150 "unused"
151 }
152
153 fn set_terminal_focused(&self, _focused: bool) {}
154
155 fn apply_notification_settings(&self, _config: &NotificationsConfig) {}
156 }
157
158 #[test]
159 fn no_host_suspension_is_a_no_op() {
160 // No host is installed in this test binary: suspending reports raw
161 // mode off, so the guard never asks to resume it.
162 let guard = suspend_raw_mode();
163 assert!(!guard.resume);
164 }
165
166 #[test]
167 fn raw_mode_that_was_on_is_resumed_exactly_once_when_the_guard_drops() {
168 static HOST: CountingHost = CountingHost::new(true);
169 let guard = suspend_raw_mode_on(&HOST);
170 assert!(
171 !HOST.raw.load(Ordering::SeqCst),
172 "raw mode is off while suspended"
173 );
174 assert_eq!(HOST.resumes.load(Ordering::SeqCst), 0);
175 drop(guard);
176 assert!(
177 HOST.raw.load(Ordering::SeqCst),
178 "raw mode is back on after the guard"
179 );
180 assert_eq!(HOST.suspends.load(Ordering::SeqCst), 1);
181 assert_eq!(HOST.resumes.load(Ordering::SeqCst), 1);
182 }
183
184 #[test]
185 fn raw_mode_that_was_off_is_never_turned_on_by_the_guard() {
186 static HOST: CountingHost = CountingHost::new(false);
187 drop(suspend_raw_mode_on(&HOST));
188 assert_eq!(HOST.suspends.load(Ordering::SeqCst), 1);
189 assert_eq!(HOST.resumes.load(Ordering::SeqCst), 0);
190 assert!(!HOST.raw.load(Ordering::SeqCst));
191 }
192 }
193
193 lines RUST