forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterminal.rs
More file actions
313 lines (269 loc) · 9.48 KB
/
terminal.rs
File metadata and controls
313 lines (269 loc) · 9.48 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
use anyhow::Result;
use std::io::{self, IsTerminal};
use std::panic;
use crate::{id, session, telemetry, tui};
pub struct TuiRuntimeState {
mouse_capture: bool,
keyboard_enhanced: bool,
focus_change: bool,
}
pub fn set_current_session(session_id: &str) {
crate::set_current_session(session_id);
}
pub fn get_current_session() -> Option<String> {
crate::get_current_session()
}
pub fn install_panic_hook() {
let default_hook = panic::take_hook();
panic::set_hook(Box::new(move |info| {
default_hook(info);
if let Some(session_id) = get_current_session() {
print_session_resume_hint(&session_id);
if let Some((provider, model)) = telemetry::current_provider_model() {
telemetry::record_crash(&provider, &model, telemetry::SessionEndReason::Panic);
}
if let Ok(mut session) = session::Session::load(&session_id) {
session.mark_crashed(Some(format!("Panic: {}", info)));
let _ = session.save();
}
}
}));
}
pub fn mark_current_session_crashed(message: String) {
if let Some(session_id) = get_current_session() {
if let Some((provider, model)) = telemetry::current_provider_model() {
telemetry::record_crash(&provider, &model, telemetry::SessionEndReason::Signal);
}
if let Ok(mut session) = session::Session::load(&session_id)
&& matches!(session.status, session::SessionStatus::Active)
{
session.mark_crashed(Some(message));
let _ = session.save();
}
}
}
pub fn panic_payload_to_string(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&str>() {
(*s).to_string()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"unknown panic payload".to_string()
}
}
pub fn show_crash_resume_hint() {
let crashed = session::find_recent_crashed_sessions();
if crashed.is_empty() {
return;
}
let (id, name) = &crashed[0];
let session_label = id::extract_session_name(id).unwrap_or(name.as_str());
if crashed.len() == 1 {
eprintln!(
"\x1b[33m💥 Session \x1b[1m{}\x1b[0m\x1b[33m crashed. Resume with:\x1b[0m jcode --resume {}",
session_label, id
);
} else {
eprintln!(
"\x1b[33m💥 {} sessions crashed recently. Most recent: \x1b[1m{}\x1b[0m",
crashed.len(),
session_label
);
eprintln!("\x1b[33m Resume with:\x1b[0m jcode --resume {}", id);
eprintln!("\x1b[33m List all:\x1b[0m jcode --resume");
}
eprintln!();
}
fn init_tui_terminal() -> Result<ratatui::DefaultTerminal> {
if !io::stdin().is_terminal() || !io::stdout().is_terminal() {
anyhow::bail!("jcode TUI requires an interactive terminal (stdin/stdout must be a TTY)");
}
let is_resuming = std::env::var("JCODE_RESUMING").is_ok();
if is_resuming {
init_tui_terminal_resume()
} else {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(ratatui::init)).map_err(|payload| {
anyhow::anyhow!(
"failed to initialize terminal: {}",
panic_payload_to_string(payload.as_ref())
)
})
}
}
pub fn init_tui_runtime() -> Result<(ratatui::DefaultTerminal, TuiRuntimeState)> {
let terminal = init_tui_terminal()?;
crate::tui::mermaid::install_jcode_mermaid_hooks();
crate::tui::markdown::install_jcode_markdown_hooks();
crate::tui::mermaid::init_picker();
let perf_policy = crate::perf::tui_policy();
let mouse_capture = perf_policy.enable_mouse_capture;
let focus_change = perf_policy.enable_focus_change;
let keyboard_enhanced = if perf_policy.enable_keyboard_enhancement {
tui::enable_keyboard_enhancement()
} else {
false
};
crossterm::execute!(std::io::stdout(), crossterm::event::EnableBracketedPaste)?;
if focus_change {
crossterm::execute!(std::io::stdout(), crossterm::event::EnableFocusChange)?;
}
if mouse_capture {
crossterm::execute!(std::io::stdout(), crossterm::event::EnableMouseCapture)?;
}
Ok((
terminal,
TuiRuntimeState {
mouse_capture,
keyboard_enhanced,
focus_change,
},
))
}
pub fn cleanup_tui_runtime(state: &TuiRuntimeState, restore_terminal: bool) {
if restore_terminal {
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableBracketedPaste);
if state.focus_change {
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableFocusChange);
}
if state.mouse_capture {
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableMouseCapture);
}
if state.keyboard_enhanced {
tui::disable_keyboard_enhancement();
}
ratatui::restore();
}
crate::tui::mermaid::clear_image_state();
}
pub fn cleanup_tui_runtime_for_run_result(
state: &TuiRuntimeState,
run_result: &crate::tui::RunResult,
extra_exec: bool,
) {
let will_exec = extra_exec
|| run_result.reload_session.is_some()
|| run_result.rebuild_session.is_some()
|| run_result.update_session.is_some();
cleanup_tui_runtime(state, !will_exec);
}
pub fn print_session_resume_hint(session_id: &str) {
let session_name = id::extract_session_name(session_id).unwrap_or(session_id);
eprintln!();
eprintln!(
"\x1b[33mSession \x1b[1m{}\x1b[0m\x1b[33m - to resume:\x1b[0m",
session_name
);
eprintln!(" jcode --resume {}", session_id);
eprintln!();
}
fn init_tui_terminal_resume() -> Result<ratatui::DefaultTerminal> {
use ratatui::{Terminal, backend::CrosstermBackend};
crossterm::terminal::enable_raw_mode()
.map_err(|e| anyhow::anyhow!("failed to enable raw mode on resume: {}", e))?;
let backend = CrosstermBackend::new(io::stdout());
let mut terminal = Terminal::new(backend)
.map_err(|e| anyhow::anyhow!("failed to create terminal on resume: {}", e))?;
terminal
.clear()
.map_err(|e| anyhow::anyhow!("failed to clear terminal on resume: {}", e))?;
Ok(terminal)
}
#[cfg(unix)]
pub fn signal_name(sig: i32) -> &'static str {
match sig {
1 => "SIGHUP",
2 => "SIGINT",
3 => "SIGQUIT",
4 => "SIGILL",
6 => "SIGABRT",
9 => "SIGKILL",
11 => "SIGSEGV",
13 => "SIGPIPE",
14 => "SIGALRM",
15 => "SIGTERM",
_ => "unknown",
}
}
#[cfg(not(unix))]
pub fn signal_name(_sig: i32) -> &'static str {
"unknown"
}
#[cfg(unix)]
fn signal_crash_reason(sig: i32) -> String {
match sig {
libc::SIGHUP => "Terminal or window closed (SIGHUP)".to_string(),
libc::SIGTERM => "Terminated (SIGTERM)".to_string(),
libc::SIGINT => "Interrupted (SIGINT)".to_string(),
libc::SIGQUIT => "Quit signal (SIGQUIT)".to_string(),
_ => format!("Terminated by signal {} ({})", signal_name(sig), sig),
}
}
#[cfg(unix)]
fn handle_termination_signal(sig: i32) -> ! {
mark_current_session_crashed(signal_crash_reason(sig));
let _ = crossterm::terminal::disable_raw_mode();
let _ = crossterm::execute!(
std::io::stderr(),
crossterm::terminal::LeaveAlternateScreen,
crossterm::cursor::Show
);
if let Some(session_id) = get_current_session() {
print_session_resume_hint(&session_id);
}
std::process::exit(128 + sig);
}
#[cfg(unix)]
pub fn spawn_session_signal_watchers() {
use tokio::signal::unix::{SignalKind, signal};
fn spawn_one(sig: i32, kind: SignalKind) {
tokio::spawn(async move {
let mut stream = match signal(kind) {
Ok(s) => s,
Err(e) => {
crate::logging::error(&format!(
"Failed to install {} handler: {}",
signal_name(sig),
e
));
return;
}
};
if stream.recv().await.is_some() {
crate::logging::info(&format!("Received {} in TUI process", signal_name(sig)));
handle_termination_signal(sig);
}
});
}
spawn_one(libc::SIGHUP, SignalKind::hangup());
spawn_one(libc::SIGTERM, SignalKind::terminate());
spawn_one(libc::SIGINT, SignalKind::interrupt());
spawn_one(libc::SIGQUIT, SignalKind::quit());
}
#[cfg(not(unix))]
pub fn spawn_session_signal_watchers() {}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
static TEST_SESSION_LOCK: Mutex<()> = Mutex::new(());
#[test]
fn test_session_recovery_tracking() {
let _guard = TEST_SESSION_LOCK.lock().unwrap();
set_current_session("test_session_123");
let stored = get_current_session();
assert_eq!(stored.as_deref(), Some("test_session_123"));
}
#[test]
fn test_session_recovery_message_format() {
let _guard = TEST_SESSION_LOCK.lock().unwrap();
let test_session = "session_format_test_12345";
set_current_session(test_session);
if let Some(session_id) = get_current_session() {
let expected_cmd = format!("jcode --resume {}", session_id);
assert!(expected_cmd.starts_with("jcode --resume "));
assert!(!session_id.is_empty());
} else {
panic!("Session ID should be set");
}
}
}