返回 CodeWhale
terminal.rs
根目录 / crates / tui / src / tui / ui / terminal.rs
1 //! Terminal lifecycle: raw mode, alternate screen, keyboard-enhancement and
2 //! bracketed-paste flags, viewport recapture, and the input-event pump's
3 //! polling primitives.
4 //!
5 //! Moved verbatim out of `ui.rs`.
6
7 use super::*;
8
9 pub(crate) fn next_terminal_event(
10 input: &TerminalInputPump,
11 pending: &mut VecDeque<ObservedTerminalEvent>,
12 timeout: Duration,
13 ) -> io::Result<Option<ObservedTerminalEvent>> {
14 if let Some(event) = pending.pop_front() {
15 return Ok(Some(event));
16 }
17 let event = input.recv_timeout(timeout)?;
18 if let Some(observed) = event.as_ref() {
19 observe_terminal_attention(&observed.event);
20 }
21 Ok(event)
22 }
23
24 pub(crate) fn try_next_terminal_event(
25 input: &TerminalInputPump,
26 pending: &mut VecDeque<ObservedTerminalEvent>,
27 ) -> io::Result<Option<ObservedTerminalEvent>> {
28 if let Some(event) = pending.pop_front() {
29 return Ok(Some(event));
30 }
31 let event = input.try_recv()?;
32 if let Some(observed) = event.as_ref() {
33 observe_terminal_attention(&observed.event);
34 }
35 Ok(event)
36 }
37
38 /// Drain input that Codewhale already read before releasing the terminal.
39 ///
40 /// Ordinary buffered input is discarded so it cannot leak into the child.
41 /// Escape and Ctrl+C are different: they are cancellation authority. If one
42 /// is pending, preserve the complete input sequence and refuse the handoff so
43 /// the normal event loop can process it.
44 pub(crate) fn prepare_terminal_input_handoff(
45 input: &TerminalInputPump,
46 pending: &mut VecDeque<ObservedTerminalEvent>,
47 ) -> io::Result<bool> {
48 let mut drained = VecDeque::new();
49 while let Some(event) = input.try_recv()? {
50 drained.push_back(event);
51 }
52 let interrupted = pending
53 .iter()
54 .chain(drained.iter())
55 .any(|observed| terminal_event_interrupts_child_handoff(&observed.event));
56 if interrupted {
57 pending.extend(drained);
58 return Ok(false);
59 }
60 pending.clear();
61 Ok(true)
62 }
63
64 fn terminal_event_interrupts_child_handoff(event: &Event) -> bool {
65 let Event::Key(key) = event else {
66 return false;
67 };
68 if key.kind == KeyEventKind::Release {
69 return false;
70 }
71 let mut key = *key;
72 normalize_raw_ctrl_c(&mut key);
73 matches!(key.code, KeyCode::Esc)
74 || matches!(key.code, KeyCode::Char('c')) && key.modifiers.contains(KeyModifiers::CONTROL)
75 }
76
77 pub(crate) fn collect_pending_terminal_events(
78 input: &TerminalInputPump,
79 pending: &mut VecDeque<ObservedTerminalEvent>,
80 ) -> io::Result<()> {
81 while let Some(observed) = input.try_recv()? {
82 // Focus is notification authority, not merely a render event. Apply
83 // it at pump receipt so a queued FocusGained cannot sit behind an
84 // engine TurnComplete and produce a false background notification.
85 observe_terminal_attention(&observed.event);
86 pending.push_back(observed);
87 }
88 Ok(())
89 }
90
91 fn observe_terminal_attention(event: &Event) {
92 match event {
93 Event::FocusGained => crate::tui::notifications::set_terminal_focused(true),
94 Event::FocusLost => {
95 crate::tui::notifications::set_terminal_focused(false);
96 crate::tui::hover_layer::clear_pointer();
97 }
98 _ => {}
99 }
100 }
101
102 /// Refuse to enter raw mode unless both interactive streams are TTYs.
103 ///
104 /// Keeping this check independent from `std::io` makes the launch contract
105 /// testable without trying to manipulate the test runner's own terminal.
106 pub(crate) fn require_interactive_terminal(stdin_is_tty: bool, stdout_is_tty: bool) -> Result<()> {
107 if stdin_is_tty && stdout_is_tty {
108 return Ok(());
109 }
110 Err(anyhow::anyhow!(
111 "Codewhale TUI requires an interactive terminal (stdin and stdout must be a TTY).\n\
112 Open a real terminal (Terminal.app, iTerm, Windows Terminal, …) and run `codew` \
113 or `codewhale` there — not from a pipe, cron job, or non-TTY launcher.\n\
114 For headless prompts use `codewhale exec \"…\"` instead."
115 ))
116 }
117
118 /// Refuse to enter terminal modes from a background Unix process group.
119 ///
120 /// A TTY can still report `isatty(3) == true` after a shell has suspended the
121 /// process. Reading from that background group triggers `SIGTTIN`; enabling
122 /// mouse or keyboard protocols before that stop poisons the shell with raw
123 /// escape reports. Check foreground ownership before the first mode change.
124 #[cfg(unix)]
125 pub(crate) fn require_foreground_terminal_owner() -> Result<()> {
126 // SAFETY: both calls are read-only process/terminal queries on the
127 // controlling stdin descriptor and require no borrowed memory.
128 let (terminal_pgid, process_pgid) =
129 unsafe { (libc::tcgetpgrp(libc::STDIN_FILENO), libc::getpgrp()) };
130 if terminal_pgid < 0 {
131 return Err(anyhow::anyhow!(
132 "Codewhale TUI could not verify foreground terminal ownership: {}",
133 io::Error::last_os_error()
134 ));
135 }
136 validate_foreground_process_group(terminal_pgid, process_pgid)
137 }
138
139 #[cfg(not(unix))]
140 pub(crate) fn require_foreground_terminal_owner() -> Result<()> {
141 Ok(())
142 }
143
144 #[cfg(unix)]
145 pub(crate) fn validate_foreground_process_group(
146 terminal_pgid: libc::pid_t,
147 process_pgid: libc::pid_t,
148 ) -> Result<()> {
149 if terminal_pgid == process_pgid {
150 return Ok(());
151 }
152 Err(anyhow::anyhow!(
153 "Codewhale TUI cannot start from a background or suspended terminal job \
154 (terminal foreground process group {terminal_pgid}, Codewhale process group {process_pgid}).\n\
155 Run `fg` to foreground the job or launch `codew` in a new terminal. \
156 For automated prompts use `codewhale exec \"…\"` instead."
157 ))
158 }
159
160 pub(crate) fn subagent_terminal_projection_from_mailbox(
161 message: &MailboxMessage,
162 ) -> Option<(&str, SubAgentStatus, Option<String>)> {
163 match message {
164 MailboxMessage::Completed { agent_id, summary } => Some((
165 agent_id.as_str(),
166 SubAgentStatus::Completed,
167 Some(summary.clone()),
168 )),
169 MailboxMessage::Failed { agent_id, error } => Some((
170 agent_id.as_str(),
171 SubAgentStatus::Failed(error.clone()),
172 Some(error.clone()),
173 )),
174 MailboxMessage::BudgetExhausted { agent_id, summary } => Some((
175 agent_id.as_str(),
176 SubAgentStatus::BudgetExhausted,
177 Some(summary.clone()),
178 )),
179 MailboxMessage::Interrupted { agent_id, reason } => Some((
180 agent_id.as_str(),
181 SubAgentStatus::Interrupted(reason.clone()),
182 Some(reason.clone()),
183 )),
184 MailboxMessage::Cancelled { agent_id } => Some((
185 agent_id.as_str(),
186 SubAgentStatus::Cancelled,
187 Some("cancelled".to_string()),
188 )),
189 _ => None,
190 }
191 }
192
193 pub(crate) fn terminal_input_recovery_relevant(app: &App, has_running_agents: bool) -> bool {
194 app.is_loading
195 || has_running_agents
196 || app.is_compacting
197 || app.is_purging
198 || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"))
199 || active_turn_has_running_tool(app)
200 }
201
202 /// Which screen the live terminal is on, for teardown paths that cannot see
203 /// `App` (the `TerminalCleanupGuard` drop, the panic hook).
204 static LIVE_ALT_SCREEN: AtomicBool = AtomicBool::new(false);
205
206 fn set_live_alt_screen(on_alt_screen: bool) {
207 LIVE_ALT_SCREEN.store(on_alt_screen, Ordering::Release);
208 }
209
210 pub(crate) fn live_alt_screen() -> bool {
211 LIVE_ALT_SCREEN.load(Ordering::Acquire)
212 }
213
214 static RESTORED_BY_PANIC: AtomicBool = AtomicBool::new(false);
215
216 pub fn mark_terminal_restored_by_panic() {
217 RESTORED_BY_PANIC.store(true, Ordering::Release);
218 }
219
220 pub(crate) fn take_terminal_restored_by_panic() -> bool {
221 RESTORED_BY_PANIC.swap(false, Ordering::AcqRel)
222 }
223
224 pub(crate) fn rearm_terminal_if_restored_by_panic<O, F>(
225 events_paused: bool,
226 owns_foreground_terminal: O,
227 rearm: F,
228 ) -> Result<bool>
229 where
230 O: FnOnce() -> bool,
231 F: FnOnce() -> Result<()>,
232 {
233 if !RESTORED_BY_PANIC.load(Ordering::Acquire)
234 || events_paused
235 || !owns_foreground_terminal()
236 || !take_terminal_restored_by_panic()
237 {
238 return Ok(false);
239 }
240 rearm()?;
241 Ok(true)
242 }
243
244 /// Enter the alternate screen and, only once the escape went out, record it
245 /// as live. Every alternate-screen entry in the crate goes through here so
246 /// `live_alt_screen()` never says a screen the terminal is not on.
247 pub(crate) fn enter_alt_screen<W: Write>(writer: &mut W) -> io::Result<()> {
248 execute!(writer, EnterAlternateScreen)?;
249 set_live_alt_screen(true);
250 Ok(())
251 }
252
253 /// Leave the alternate screen; the counterpart of [`enter_alt_screen`].
254 pub(crate) fn leave_alt_screen<W: Write>(writer: &mut W) -> io::Result<()> {
255 execute!(writer, LeaveAlternateScreen)?;
256 set_live_alt_screen(false);
257 Ok(())
258 }
259
260 pub(crate) fn build_app_terminal(backend: ColorCompatBackend<Stdout>) -> io::Result<AppTerminal> {
261 Terminal::new(backend)
262 }
263
264 pub(crate) fn pause_terminal(
265 terminal: &mut AppTerminal,
266 use_mouse_capture: bool,
267 use_bracketed_paste: bool,
268 ) -> Result<()> {
269 // Focus reporting is about to be disabled. Fail closed to "focused" so
270 // a child process or external editor cannot leave stale background state
271 // that later emits a surprise Codewhale notification.
272 crate::tui::notifications::set_terminal_focused(true);
273 // #443: pop keyboard enhancement flags before handing the terminal
274 // to a child process so it doesn't inherit a half-configured input
275 // mode. Best-effort — terminals that didn't accept the flags
276 // silently ignore the pop. Matches the shutdown and panic paths.
277 pop_keyboard_enhancement_flags(terminal.backend_mut());
278 disable_alternate_scroll_mode(terminal.backend_mut());
279 // Every teardown step is attempted even when an earlier one fails: one
280 // failed write must not leave mouse capture or raw mode on for the child
281 // (U03-09). The first failure is still returned so the caller refuses the
282 // handoff.
283 let mut first_error: Option<io::Error> = None;
284 let mut attempt = |result: io::Result<()>| {
285 if let Err(error) = result {
286 first_error.get_or_insert(error);
287 }
288 };
289 attempt(execute!(terminal.backend_mut(), DisableFocusChange));
290 attempt(disable_raw_mode());
291 attempt(leave_alt_screen(terminal.backend_mut()));
292 #[cfg(windows)]
293 codewhale_runtime::logging::restore_verbose_state();
294 if use_mouse_capture {
295 attempt(execute!(terminal.backend_mut(), DisableMouseCapture));
296 }
297 if use_bracketed_paste {
298 disable_bracketed_paste_mode(terminal.backend_mut());
299 }
300 match first_error {
301 Some(error) => Err(error.into()),
302 None => Ok(()),
303 }
304 }
305
306 pub(crate) fn resume_terminal(
307 terminal: &mut AppTerminal,
308 use_mouse_capture: bool,
309 use_bracketed_paste: bool,
310 sync_output_enabled: bool,
311 ) -> Result<()> {
312 // No trustworthy focus transition exists while reporting is disabled.
313 // Resume from the quiet/focused state and wait for a real FocusLost.
314 crate::tui::notifications::set_terminal_focused(true);
315 let _ = take_terminal_restored_by_panic();
316 enable_raw_mode()?;
317 enter_alt_screen(terminal.backend_mut())?;
318 // Re-entering alt-screen after mode recovery — suppress verbose
319 // CLI logging again so eprintln! doesn't leak into the TUI.
320 #[cfg(windows)]
321 codewhale_runtime::logging::set_verbose(false);
322 recover_terminal_modes(
323 terminal.backend_mut(),
324 use_mouse_capture,
325 use_bracketed_paste,
326 );
327 // Cache the real terminal size *before* resetting the viewport, so that
328 // reset_terminal_viewport → terminal.clear() → autoresize() → backend.size()
329 // picks up the cached size instead of falling through to
330 // crossterm::terminal::size() which may return stale buffer metadata
331 // (especially on Windows after a secondary EnterAlternateScreen).
332 if let Ok((cols, rows)) = crossterm::terminal::size() {
333 terminal
334 .backend_mut()
335 .set_terminal_size(Size::new(cols, rows));
336 }
337 reset_terminal_viewport(terminal, sync_output_enabled)?;
338 Ok(())
339 }
340
341 pub(crate) fn reset_terminal_viewport(
342 terminal: &mut AppTerminal,
343 sync_output_enabled: bool,
344 ) -> Result<()> {
345 // Reset scroll margins and origin mode before clearing. Some interactive
346 // child processes leave DECSTBM/DECOM behind; if ratatui's diff renderer
347 // then writes "row 0", terminals can place it relative to the leaked
348 // scroll region and the whole viewport appears shifted down. We
349 // deliberately do *not* emit CSI 2J/3J here — see TERMINAL_ORIGIN_RESET
350 // for why; the immediately-following ratatui `terminal.clear()` flushes a
351 // single clear via the diff renderer, which the alt-screen buffer absorbs
352 // without visible flicker on the affected terminals.
353 //
354 // Wrap the reset+clear sequence in DEC 2026 synchronized-output mode
355 // (`\x1b[?2026h` … `\x1b[?2026l`) so GPU-accelerated terminals
356 // (Ghostty, VSCode, Kitty, WezTerm) defer rendering until the whole
357 // frame is staged. Terminals that don't support it silently ignore.
358 // The wrap is opt-out via `synchronized_output = "off"` for terminals
359 // that mishandle the sequence (Ptyxis 50.x on VTE 0.84.x flashes the
360 // whole viewport on each wrapped frame).
361 if sync_output_enabled {
362 let _ = terminal.backend_mut().write_all(BEGIN_SYNC_UPDATE);
363 }
364
365 let result = (|| -> Result<()> {
366 terminal.backend_mut().write_all(TERMINAL_ORIGIN_RESET)?;
367 terminal.clear()?;
368 Ok(())
369 })();
370
371 // Always end the synchronized update, regardless of success or failure.
372 if sync_output_enabled {
373 let _ = terminal.backend_mut().write_all(END_SYNC_UPDATE);
374 }
375 let _ = terminal.backend_mut().flush();
376 result
377 }
378
379 pub(crate) fn push_keyboard_enhancement_flags<W: Write>(writer: &mut W) {
380 // crossterm's PushKeyboardEnhancementFlags command unconditionally
381 // returns Unsupported on Windows (is_ansi_code_supported() == false), so
382 // the ANSI escape is written directly on that platform. Modern Windows
383 // terminals (VSCode integrated terminal, Windows Terminal ≥1.17) honour
384 // the kitty keyboard protocol but crossterm's event reader does not
385 // decode CSI u sequences on Windows (issue #1599). Write \033[>0u to
386 // probe the protocol without enabling any flags — Enter stays as \n.
387 #[cfg(windows)]
388 {
389 if let Err(err) = write!(writer, "\x1b[>0u").and_then(|()| writer.flush()) {
390 tracing::debug!(
391 target: "kitty_keyboard",
392 ?err,
393 "PushKeyboardEnhancementFlags direct write failed on Windows"
394 );
395 }
396 }
397 #[cfg(not(windows))]
398 if let Err(err) = execute!(
399 writer,
400 PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
401 ) {
402 tracing::debug!(
403 target: "kitty_keyboard",
404 ?err,
405 "PushKeyboardEnhancementFlags ignored (terminal lacks support)"
406 );
407 }
408 }
409
410 pub(crate) fn pop_keyboard_enhancement_flags<W: Write>(writer: &mut W) {
411 // Mirror of push_keyboard_enhancement_flags: crossterm's
412 // PopKeyboardEnhancementFlags also has is_ansi_code_supported() == false
413 // on Windows, so write the pop escape directly to restore the terminal to
414 // its pre-launch keyboard mode.
415 // pub(crate) so the panic hook in main.rs and external_editor.rs can
416 // also call the Windows-aware path instead of using the raw crossterm
417 // execute!() macro which silently no-ops on Windows.
418 #[cfg(windows)]
419 {
420 if let Err(err) = write!(writer, "\x1b[<1u").and_then(|()| writer.flush()) {
421 tracing::debug!(
422 target: "kitty_keyboard",
423 ?err,
424 "PopKeyboardEnhancementFlags direct write failed on Windows"
425 );
426 }
427 }
428 #[cfg(not(windows))]
429 let _ = execute!(writer, PopKeyboardEnhancementFlags);
430 }
431
432 pub(crate) fn set_alternate_scroll_mode<W: Write>(writer: &mut W, enabled: bool) {
433 let sequence = if enabled {
434 ENABLE_ALT_SCROLL_MODE
435 } else {
436 DISABLE_ALT_SCROLL_MODE
437 };
438 if let Err(err) = writer.write_all(sequence).and_then(|()| writer.flush()) {
439 tracing::debug!(
440 ?err,
441 enabled,
442 "alternate-scroll terminal mode change ignored"
443 );
444 }
445 }
446
447 pub(crate) fn disable_alternate_scroll_mode<W: Write>(writer: &mut W) {
448 set_alternate_scroll_mode(writer, false);
449 }
450
451 /// Best-effort terminal restoration for emergency exit paths
452 /// (panic hook, signal handlers). Mirrors the normal teardown in
453 /// `run_event_loop` but tolerates any subset of modes not actually being
454 /// active — every step is discarded on failure so a half-initialized TUI
455 /// (e.g. SIGINT during startup before `EnterAlternateScreen`) still gets
456 /// raw mode + kitty keyboard flags cleared, which is what causes the
457 /// `^[[>5u` shell pollution reported in #1583.
458 pub fn emergency_restore_terminal() {
459 let mut stdout = std::io::stdout();
460 codewhale_tui_kit::cursor_accent::restore_cursor_accent();
461 pop_keyboard_enhancement_flags(&mut stdout);
462 disable_alternate_scroll_mode(&mut stdout);
463 let _ = execute!(stdout, DisableFocusChange);
464 disable_bracketed_paste_mode(&mut stdout);
465 let _ = execute!(stdout, DisableMouseCapture);
466 let _ = disable_raw_mode();
467 let _ = leave_alt_screen(&mut stdout);
468 }
469
470 /// On Windows, ensure the console input handle has `ENABLE_WINDOW_INPUT`
471 /// (0x0008) set. crossterm's `enable_raw_mode()` removes this flag, which
472 /// breaks IME composition (Chinese/Japanese/Korean input methods cannot
473 /// commit characters) on some Windows configurations (e.g. Windows Terminal
474 /// in conhost compatibility mode, or the legacy console with VT input).
475 ///
476 /// Best-effort and idempotent. Silently ignored if the console handle or
477 /// mode query fails.
478 #[cfg(target_os = "windows")]
479 pub(crate) fn enable_windows_ime_console_mode() {
480 use windows::Win32::System::Console::CONSOLE_MODE;
481 const ENABLE_WINDOW_INPUT: CONSOLE_MODE = CONSOLE_MODE(0x0008);
482
483 // SAFETY: Win32 console API is safe to call from any thread.
484 // Failures (console handle invalid, mode query fails) are silently
485 // ignored — this is a best-effort IME compatibility tweak.
486 unsafe {
487 let Ok(handle) = GetStdHandle(windows::Win32::System::Console::STD_INPUT_HANDLE) else {
488 return;
489 };
490 let mut mode = CONSOLE_MODE(0);
491 if GetConsoleMode(handle, &mut mode).is_err() {
492 return;
493 }
494 if mode.0 & ENABLE_WINDOW_INPUT.0 == 0 {
495 let _ = SetConsoleMode(handle, mode | ENABLE_WINDOW_INPUT);
496 }
497 }
498 }
499
500 /// Re-establish terminal mode flags. Idempotent and best-effort: each
501 /// underlying flag is silently discarded by terminals that don't support
502 /// it, and a single flag's failure doesn't prevent later flags from being
503 /// attempted.
504 ///
505 /// **Canonical location for terminal-mode setup.** If you add a new mode
506 /// flag at startup or in `resume_terminal`, add it here too — `FocusGained`
507 /// recovery calls this and will silently fall behind otherwise.
508 ///
509 /// There are three callers, and they must stay in step: `resume_terminal`
510 /// (after a child hands the terminal back, and after a job-control suspend),
511 /// and the `FocusGained` recovery path. A mode enabled in only one of them is a
512 /// mode that leaks into the shell on the other two paths (#6169).
513 ///
514 /// Excluded by design: raw mode and the alternate screen — those persist
515 /// across focus events and are only re-established by `resume_terminal`
516 /// after a suspension, which always runs a separate path.
517 ///
518 pub(crate) fn recover_terminal_modes<W: Write>(
519 writer: &mut W,
520 use_mouse_capture: bool,
521 use_bracketed_paste: bool,
522 ) {
523 #[cfg(target_os = "windows")]
524 enable_windows_ime_console_mode();
525
526 pop_keyboard_enhancement_flags(writer);
527 push_keyboard_enhancement_flags(writer);
528 // DECSET 1007 converts wheel input into arrow keys. While mouse capture
529 // is active, mouse reporting is the authoritative wheel channel and
530 // terminals disagree about precedence (iTerm2 converts — #5223), so keep
531 // 1007 off; #4026 already leaves it off without mouse capture.
532 disable_alternate_scroll_mode(writer);
533 if use_mouse_capture && let Err(err) = execute!(writer, EnableMouseCapture) {
534 tracing::debug!(?err, "EnableMouseCapture ignored");
535 }
536 if use_bracketed_paste {
537 try_enable_bracketed_paste_mode(writer);
538 }
539 if let Err(err) = execute!(writer, EnableFocusChange) {
540 tracing::debug!(?err, "EnableFocusChange ignored");
541 }
542 }
543
544 pub(crate) fn try_enable_bracketed_paste_mode<W: Write>(writer: &mut W) -> bool {
545 match execute!(writer, EnableBracketedPaste) {
546 Ok(()) => true,
547 Err(err) => {
548 tracing::debug!(?err, "EnableBracketedPaste ignored");
549 false
550 }
551 }
552 }
553
554 pub(crate) fn disable_bracketed_paste_mode<W: Write>(writer: &mut W) {
555 if let Err(err) = execute!(writer, DisableBracketedPaste) {
556 tracing::debug!(?err, "DisableBracketedPaste ignored");
557 }
558 }
559
560 pub(crate) fn terminal_event_needs_viewport_recapture(evt: &Event) -> bool {
561 matches!(evt, Event::FocusGained)
562 }
563
564 /// Next frame-emission gate from one terminal event (#6311).
565 ///
566 /// GTK3 pauses the frame clock on full occlusion while VTE keeps queuing
567 /// damage, so every frame emitted while covered becomes flicker backlog on
568 /// return. Focus loss therefore defers draws (state keeps ingesting;
569 /// `needs_redraw` stays set); focus gain re-arms with the existing
570 /// full-repaint recovery. Any key/mouse/paste input also re-arms: input
571 /// focus means a visible window, and it unsticks a lost `FocusGained`.
572 pub(crate) fn next_unfocused(unfocused: bool, evt: &Event) -> bool {
573 match evt {
574 Event::FocusLost => true,
575 Event::FocusGained | Event::Key(_) | Event::Mouse(_) | Event::Paste(_) => false,
576 _ => unfocused,
577 }
578 }
579
580 /// Whether focus loss may defer frame emission at all (#6311).
581 ///
582 /// Only GTK/VTE terminals (MATE, GNOME Terminal, Tilix, Terminator, ...)
583 /// queue damage while occluded and replay it on return; they all export
584 /// `VTE_VERSION`. Everywhere else an unfocused window is usually still
585 /// visible (side-by-side macOS/Windows windows, split panes), so freezing
586 /// frames on `FocusLost` made streaming output look stuck until the user
587 /// clicked, scrolled or typed back into the terminal.
588 ///
589 /// `VTE_VERSION` only proves VTE is the *immediate* terminal when no
590 /// multiplexer sits in between: tmux started from GNOME Terminal inherits it,
591 /// yet tmux reports `FocusLost` for a still-visible split pane. Inside tmux
592 /// (`TMUX` set) frames keep flowing.
593 pub(crate) fn focus_loss_defers_frames(vte_version: Option<&str>, tmux: Option<&str>) -> bool {
594 let inside_tmux = tmux.is_some_and(|v| !v.trim().is_empty());
595 !inside_tmux && vte_version.is_some_and(|v| !v.trim().is_empty())
596 }
597
598 pub(crate) fn terminal_pause_has_live_owner(app: &App) -> bool {
599 app.active_cell.as_ref().is_some_and(|active| {
600 active.entries().iter().any(|cell| {
601 matches!(
602 cell,
603 HistoryCell::Tool(ToolCell::Exec(exec)) if exec.status.is_active()
604 )
605 })
606 })
607 }
608
609 pub(crate) fn active_poll_ms(app: &App) -> u64 {
610 if app.low_motion {
611 96
612 } else {
613 UI_ACTIVE_POLL_MS
614 }
615 }
616
617 pub(crate) fn idle_poll_ms(app: &App) -> u64 {
618 if app.low_motion { 120 } else { UI_IDLE_POLL_MS }
619 }
620
621 /// How long the screen must have been unchanged, with no input and no engine
622 /// event, before the idle loop relaxes to [`UI_QUIESCENT_POLL_MS`] (#6728).
623 pub(crate) const UI_QUIESCENT_AFTER: Duration = Duration::from_secs(5);
624
625 /// Idle poll once the UI is quiescent. Input, resize and mouse events do not
626 /// wait for it: they arrive over the input pump's channel and return the loop
627 /// at once. It only bounds how late a source the loop merely *polls* (an
628 /// engine event, a background-task cell, the control socket, a remote
629 /// control event) is noticed while nothing else is happening: at most this
630 /// interval, instead of [`UI_IDLE_POLL_MS`].
631 ///
632 /// Known limits: the loop is still polled, not woken. Nothing wakes it from an
633 /// engine event, a remote-control event, a background-task cell (prompt
634 /// suggestion, fleet or constitution draft, workspace context) or the control
635 /// socket, so each of those can land up to this long late once the UI has been
636 /// quiet for [`UI_QUIESCENT_AFTER`]. Waking from those writers would remove the
637 /// bound and is not done here.
638 pub(crate) const UI_QUIESCENT_POLL_MS: u64 = 250;
639
640 /// What the loop knows about itself that [`App`] alone does not say.
641 #[derive(Debug, Clone, Copy, Default)]
642 pub(crate) struct IdleFacts {
643 /// Live sub-agents (`running_agent_count(app) > 0`).
644 pub(crate) has_running_agents: bool,
645 /// A spinner, the underwater scene, or a launch animation wants frames
646 /// faster than [`UI_QUIESCENT_POLL_MS`]; slower motion is woken by its
647 /// own frame deadline.
648 pub(crate) animation_active: bool,
649 /// A terminal event is already buffered for this iteration.
650 pub(crate) input_pending: bool,
651 /// A sub-agent list refresh is waiting for room in the engine mailbox.
652 pub(crate) pending_engine_op: bool,
653 }
654
655 pub(crate) fn has_live_durable_tasks(app: &App) -> bool {
656 app.task_panel.iter().any(|task| {
657 task.kind == crate::tui::app::TaskPanelEntryKind::Background
658 && matches!(task.status.as_str(), "queued" | "running" | "waiting")
659 })
660 }
661
662 /// Whether the UI has nothing to do *right now*: no turn, no live work, no
663 /// animation, no pending redraw, no toast about to expire, no modal ticking.
664 /// Pure on purpose. A state that is not listed here keeps the 48 ms poll, so
665 /// the list errs towards "busy".
666 pub(crate) fn ui_state_is_quiescent(app: &App, facts: &IdleFacts, now: Instant) -> bool {
667 let toast_live = |toast: &StatusToast| toast.ttl_ms.is_some() && !toast.is_expired(now);
668 let deciding = decision_prompt_waiting(app);
669 !((app.is_loading && !deciding)
670 || app.is_compacting
671 || app.is_purging
672 || (app.turn_started_at.is_some() && !deciding)
673 || (matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) && !deciding)
674 || facts.has_running_agents
675 || facts.animation_active
676 || facts.input_pending
677 || facts.pending_engine_op
678 || app.needs_redraw
679 || (!app.view_stack.is_empty() && !deciding)
680 || app.onboarding != OnboardingState::None
681 || app.redaction_gate
682 || !app.queued_messages.is_empty()
683 || app.queued_draft.is_some()
684 || app.mcp_login.is_some()
685 || !app.mcp_retries.is_empty()
686 || app.quit_armed_until.is_some()
687 || app.receipt_started_at.is_some()
688 || app.viewport.selection_autoscroll.is_some()
689 || app.status_toasts.iter().any(toast_live)
690 || app.sticky_status.as_ref().is_some_and(toast_live))
691 }
692
693 pub(crate) fn decision_prompt_waiting(app: &App) -> bool {
694 matches!(
695 app.view_stack.top_kind(),
696 Some(ModalKind::Approval | ModalKind::Elevation | ModalKind::UserInput)
697 )
698 }
699
700 /// The idle poll for this iteration: [`idle_poll_ms`] normally, relaxed to
701 /// [`UI_QUIESCENT_POLL_MS`] once the UI has been quiescent (see
702 /// [`ui_state_is_quiescent`]) and quiet for [`UI_QUIESCENT_AFTER`]. `quiet_for`
703 /// is measured by the loop from the last terminal event, engine event or busy
704 /// state, so any of those restores the short poll on the next iteration.
705 pub(crate) fn idle_poll_duration(
706 app: &App,
707 facts: &IdleFacts,
708 now: Instant,
709 quiet_for: Duration,
710 ) -> Duration {
711 if quiet_for >= UI_QUIESCENT_AFTER && ui_state_is_quiescent(app, facts, now) {
712 Duration::from_millis(UI_QUIESCENT_POLL_MS.max(idle_poll_ms(app)))
713 } else {
714 Duration::from_millis(idle_poll_ms(app))
715 }
716 }
717
718 /// The event loop's idle clocks (#6728). `last_ui_activity` is the last
719 /// moment anything happened that wanted a prompt reaction: a terminal event,
720 /// an engine event, or any non-quiescent UI state. The idle poll and the
721 /// automation scan back off from it. The git probe backs off from
722 /// `last_input_or_engine_event` instead, which a ticking label or an open
723 /// card does not move.
724 #[derive(Debug, Clone, Copy)]
725 pub(crate) struct IdleClock {
726 last_ui_activity: Instant,
727 last_input_or_engine_event: Instant,
728 elapsed_redraw_pending: bool,
729 ui_quiet: bool,
730 }
731
732 impl IdleClock {
733 pub(crate) fn new(now: Instant) -> Self {
734 Self {
735 last_ui_activity: now,
736 last_input_or_engine_event: now,
737 elapsed_redraw_pending: false,
738 ui_quiet: false,
739 }
740 }
741
742 pub(crate) fn ui_quiet(&self) -> bool {
743 self.ui_quiet
744 }
745
746 pub(crate) fn note_input(&mut self, now: Instant) {
747 self.last_ui_activity = now;
748 self.last_input_or_engine_event = now;
749 }
750
751 pub(crate) fn note_elapsed_only_change(&mut self) {
752 self.elapsed_redraw_pending = true;
753 }
754
755 pub(crate) fn settle(
756 &mut self,
757 app: &mut App,
758 facts: &IdleFacts,
759 now: Instant,
760 engine_event_seen: bool,
761 status_tick_repaints: bool,
762 ) {
763 if engine_event_seen {
764 self.last_input_or_engine_event = now;
765 }
766 let quiescent = ui_state_is_quiescent(app, facts, now);
767 if engine_event_seen || !quiescent {
768 self.last_ui_activity = now;
769 }
770 self.ui_quiet = quiescent && self.ui_quiet_for(now) >= UI_QUIESCENT_AFTER;
771 if std::mem::take(&mut self.elapsed_redraw_pending) && !status_tick_repaints {
772 app.needs_redraw = true;
773 }
774 }
775
776 pub(crate) fn ui_quiet_for(&self, now: Instant) -> Duration {
777 now.saturating_duration_since(self.last_ui_activity)
778 }
779
780 pub(crate) fn input_quiet_for(&self, now: Instant) -> Duration {
781 now.saturating_duration_since(self.last_input_or_engine_event)
782 }
783
784 pub(crate) fn poll(&self, app: &App, facts: &IdleFacts, now: Instant) -> Duration {
785 idle_poll_duration(app, facts, now, self.ui_quiet_for(now))
786 }
787 }
788
789 #[cfg(test)]
790 mod idle_poll_tests {
791 use super::*;
792
793 fn quiet_app() -> App {
794 let mut app =
795 crate::tui::test_support::test_app_with_options(crate::tui::app::TuiOptions {
796 skip_onboarding: true,
797 start_in_agent_mode: true,
798 ..crate::tui::test_support::test_tui_options(std::path::PathBuf::from("."))
799 });
800 app.needs_redraw = false;
801 app.low_motion = false;
802 app
803 }
804
805 fn at(app: &App, facts: &IdleFacts, quiet_secs: u64) -> Duration {
806 idle_poll_duration(app, facts, Instant::now(), Duration::from_secs(quiet_secs))
807 }
808
809 const FAST: Duration = Duration::from_millis(UI_IDLE_POLL_MS);
810 const SLOW: Duration = Duration::from_millis(UI_QUIESCENT_POLL_MS);
811
812 #[test]
813 fn a_running_background_shell_job_does_not_hold_the_ambient_scene_awake() {
814 let mut app = quiet_app();
815 let shell = crate::tui::app::TaskPanelEntry {
816 exit_code: None,
817 id: "shell-live".to_string(),
818 status: "running".to_string(),
819 prompt_summary: "shell: sleep 900".to_string(),
820 duration_ms: Some(60_000),
821 kind: crate::tui::app::TaskPanelEntryKind::Shell,
822 stale: false,
823 elapsed_since_output_ms: None,
824 owner_agent_id: None,
825 owner_agent_name: None,
826 current_tool: None,
827 role: None,
828 files_touched: 0,
829 };
830 app.task_panel.push(shell.clone());
831 assert!(!has_live_durable_tasks(&app));
832
833 app.task_panel.push(crate::tui::app::TaskPanelEntry {
834 kind: crate::tui::app::TaskPanelEntryKind::Background,
835 ..shell
836 });
837 assert!(has_live_durable_tasks(&app));
838 }
839
840 #[test]
841 fn a_settled_ui_relaxes_only_after_the_quiet_period() {
842 let app = quiet_app();
843 let facts = IdleFacts::default();
844 assert!(ui_state_is_quiescent(&app, &facts, Instant::now()));
845 assert_eq!(
846 at(&app, &facts, 0),
847 FAST,
848 "fresh activity keeps the fast poll"
849 );
850 assert_eq!(at(&app, &facts, 4), FAST, "inside the quiet period");
851 assert_eq!(at(&app, &facts, UI_QUIESCENT_AFTER.as_secs()), SLOW);
852 assert_eq!(at(&app, &facts, 600), SLOW);
853 }
854
855 #[test]
856 fn the_relaxed_poll_is_never_shorter_than_the_reduced_motion_poll() {
857 let mut app = quiet_app();
858 app.low_motion = true;
859 let facts = IdleFacts::default();
860 assert_eq!(at(&app, &facts, 1), Duration::from_millis(120));
861 assert_eq!(at(&app, &facts, 60), SLOW);
862 assert!(SLOW >= Duration::from_millis(120));
863 }
864
865 #[test]
866 fn any_live_state_keeps_the_fast_poll_however_long_it_has_been_quiet() {
867 let now = Instant::now();
868 let long = Duration::from_secs(3_600);
869 let busy = |app: &App, facts: &IdleFacts, why: &str| {
870 assert!(!ui_state_is_quiescent(app, facts, now), "{why}");
871 assert_eq!(idle_poll_duration(app, facts, now, long), FAST, "{why}");
872 };
873
874 let facts = IdleFacts::default();
875 let mut app = quiet_app();
876 app.is_loading = true;
877 busy(&app, &facts, "a turn is loading");
878
879 let mut app = quiet_app();
880 app.is_compacting = true;
881 busy(&app, &facts, "compacting");
882
883 let mut app = quiet_app();
884 app.is_purging = true;
885 busy(&app, &facts, "purging");
886
887 let mut app = quiet_app();
888 app.turn_started_at = Some(now);
889 busy(&app, &facts, "a turn has started");
890
891 let mut app = quiet_app();
892 app.runtime_turn_status = Some("in_progress".to_string());
893 busy(&app, &facts, "the runtime reports a turn in progress");
894
895 let mut app = quiet_app();
896 app.needs_redraw = true;
897 busy(&app, &facts, "a redraw is owed");
898
899 let mut app = quiet_app();
900 app.quit_armed_until = Some(now + Duration::from_secs(2));
901 busy(&app, &facts, "the quit prompt is armed");
902
903 let mut app = quiet_app();
904 app.receipt_started_at = Some(now);
905 busy(&app, &facts, "a receipt is on screen and expires on a tick");
906
907 let mut app = quiet_app();
908 app.push_status_toast("saved", StatusToastLevel::Info, Some(4_000));
909 app.needs_redraw = false;
910 busy(&app, &facts, "a timed toast is showing");
911
912 let app = quiet_app();
913 for (facts, why) in [
914 (
915 IdleFacts {
916 has_running_agents: true,
917 ..IdleFacts::default()
918 },
919 "a sub-agent is running",
920 ),
921 (
922 IdleFacts {
923 animation_active: true,
924 ..IdleFacts::default()
925 },
926 "something is animating",
927 ),
928 (
929 IdleFacts {
930 input_pending: true,
931 ..IdleFacts::default()
932 },
933 "input is already buffered",
934 ),
935 (
936 IdleFacts {
937 pending_engine_op: true,
938 ..IdleFacts::default()
939 },
940 "an engine op is waiting for mailbox room",
941 ),
942 ] {
943 busy(&app, &facts, why);
944 }
945 }
946
947 #[test]
948 fn an_expired_toast_and_a_standing_error_do_not_hold_the_fast_poll() {
949 let mut app = quiet_app();
950 let facts = IdleFacts::default();
951 let mut expired = StatusToast::new("old", StatusToastLevel::Info, Some(1));
952 expired.created_at = Instant::now() - Duration::from_secs(60);
953 app.status_toasts.push_back(expired);
954 // A sticky error without a lifetime ("no model connected") is a
955 // static line, not something that ticks.
956 app.sticky_status = Some(StatusToast::new("no model", StatusToastLevel::Error, None));
957 assert!(ui_state_is_quiescent(&app, &facts, Instant::now()));
958 assert_eq!(at(&app, &facts, 30), SLOW);
959 }
960
961 #[test]
962 fn a_queued_message_or_open_modal_is_not_quiescent() {
963 let facts = IdleFacts::default();
964 let mut app = quiet_app();
965 app.queued_draft = Some(QueuedMessage::new("later".to_string(), None));
966 assert!(!ui_state_is_quiescent(&app, &facts, Instant::now()));
967
968 let mut app = quiet_app();
969 app.onboarding = OnboardingState::Welcome;
970 assert!(!ui_state_is_quiescent(&app, &facts, Instant::now()));
971 }
972 }
973
974 #[cfg(test)]
975 mod screen_mode_tests {
976 use super::*;
977
978 /// The live-screen record only moves on an escape that went out.
979 #[cfg(not(windows))]
980 #[test]
981 fn live_screen_record_ignores_an_escape_that_failed_to_write() {
982 struct Closed;
983 impl Write for Closed {
984 fn write(&mut self, _: &[u8]) -> io::Result<usize> {
985 Err(io::Error::other("stdout closed"))
986 }
987 fn flush(&mut self) -> io::Result<()> {
988 Err(io::Error::other("stdout closed"))
989 }
990 }
991 let mut sink: Vec<u8> = Vec::new();
992 enter_alt_screen(&mut sink).expect("a writable sink takes the escape");
993 assert!(live_alt_screen());
994 assert!(leave_alt_screen(&mut Closed).is_err());
995 assert!(
996 live_alt_screen(),
997 "a leave that never reached the terminal must not be recorded"
998 );
999 leave_alt_screen(&mut sink).expect("a writable sink takes the escape");
1000 assert!(!live_alt_screen());
1001 }
1002
1003 #[test]
1004 fn caught_panic_rearms_terminal_once_foreground_and_unpaused() {
1005 let _lock = crate::test_support::lock_test_env();
1006 let _ = take_terminal_restored_by_panic();
1007
1008 let mut foreground_checks = 0usize;
1009 let mut rearms = 0usize;
1010 assert!(
1011 !rearm_terminal_if_restored_by_panic(
1012 false,
1013 || {
1014 foreground_checks += 1;
1015 true
1016 },
1017 || {
1018 rearms += 1;
1019 Ok(())
1020 },
1021 )
1022 .expect("no-op when no panic restore occurred")
1023 );
1024 assert_eq!(foreground_checks, 0);
1025 assert_eq!(rearms, 0);
1026
1027 let caught = std::panic::catch_unwind(|| {
1028 mark_terminal_restored_by_panic();
1029 panic!("simulated caught panic");
1030 });
1031 assert!(caught.is_err());
1032
1033 assert!(
1034 !rearm_terminal_if_restored_by_panic(
1035 true,
1036 || true,
1037 || {
1038 rearms += 1;
1039 Ok(())
1040 },
1041 )
1042 .expect("paused terminal defers re-arm")
1043 );
1044 assert_eq!(rearms, 0);
1045
1046 assert!(
1047 !rearm_terminal_if_restored_by_panic(
1048 false,
1049 || false,
1050 || {
1051 rearms += 1;
1052 Ok(())
1053 },
1054 )
1055 .expect("background process group defers re-arm")
1056 );
1057 assert_eq!(rearms, 0);
1058
1059 assert!(
1060 rearm_terminal_if_restored_by_panic(
1061 false,
1062 || true,
1063 || {
1064 rearms += 1;
1065 Ok(())
1066 },
1067 )
1068 .expect("foreground unpaused loop re-arms once")
1069 );
1070 assert_eq!(rearms, 1);
1071
1072 assert!(
1073 !rearm_terminal_if_restored_by_panic(
1074 false,
1075 || true,
1076 || {
1077 rearms += 1;
1078 Ok(())
1079 },
1080 )
1081 .expect("re-arm flag stays cleared after recovery")
1082 );
1083 assert_eq!(rearms, 1);
1084 }
1085 }
1086
1087 /// The terminal UI's implementation of the runtime's one terminal port
1088 /// (`codewhale_runtime::host_terminal`). The composition root installs it for every host
1089 /// this binary launches, so runtime code (the shell tools, the dispatcher)
1090 /// reaches raw mode only through it and never links crossterm.
1091 struct TuiHostTerminal;
1092
1093 impl codewhale_runtime::host_terminal::HostTerminal for TuiHostTerminal {
1094 fn suspend_raw_mode(&self) -> bool {
1095 let was_enabled = crossterm::terminal::is_raw_mode_enabled().unwrap_or(false);
1096 if was_enabled {
1097 let _ = disable_raw_mode();
1098 }
1099 was_enabled
1100 }
1101
1102 fn resume_raw_mode(&self) {
1103 let _ = enable_raw_mode();
1104 }
1105
1106 fn notify_model(&self, title: &str, body: Option<&str>) -> &'static str {
1107 crate::tui::notifications::notify_model(title, body)
1108 }
1109
1110 fn set_terminal_focused(&self, focused: bool) {
1111 crate::tui::notifications::set_terminal_focused(focused);
1112 }
1113
1114 fn apply_notification_settings(
1115 &self,
1116 config: &codewhale_config::notifications::NotificationsConfig,
1117 ) {
1118 let _ = crate::tui::notifications::apply_settings(config);
1119 }
1120
1121 fn begin_turn_chrome(&self) {
1122 crate::tui::notifications::set_taskbar_progress_busy();
1123 crate::tui::notifications::start_title_animation("codewhale");
1124 }
1125 }
1126
1127 /// Install the TUI as the process's terminal host. Idempotent: the first
1128 /// install wins.
1129 pub(crate) fn install_host_terminal() {
1130 let _ = codewhale_runtime::host_terminal::install(Box::new(TuiHostTerminal));
1131 }
1132
1133 #[cfg(test)]
1134 mod host_terminal_tests {
1135 use super::TuiHostTerminal;
1136 use crate::tui::notifications::{configured_method, install_configured_method};
1137 use codewhale_notify::DeliveryOutcome;
1138 use codewhale_runtime::host_terminal::HostTerminal;
1139
1140 /// The `notify` tool reaches delivery only through the installed host:
1141 /// the TUI's host must hand the model's text to the delivery path that
1142 /// honors the installed method, so `method = "off"` stays silent.
1143 #[test]
1144 fn tui_host_routes_the_notify_tool_through_the_installed_method() {
1145 let _lock = crate::test_support::lock_test_env();
1146 let previous_method = configured_method();
1147 let config = |text: &str| -> codewhale_runtime::config::Config {
1148 toml::from_str(text).expect("notifications config should parse")
1149 };
1150 // Settings reach the host the way the composition root sends them;
1151 // `condition = "always"` so the attention policy (checked first)
1152 // lets the call reach the method check whatever the runner's focus.
1153 TuiHostTerminal.apply_notification_settings(
1154 &config("[notifications]\nmethod = \"off\"\ncondition = \"always\"\n")
1155 .notifications_config(),
1156 );
1157
1158 let receipt = TuiHostTerminal.notify_model("done", None);
1159
1160 TuiHostTerminal
1161 .apply_notification_settings(&config("[notifications]\n").notifications_config());
1162 install_configured_method(previous_method);
1163 assert_eq!(receipt, DeliveryOutcome::SuppressedByMethod.receipt());
1164 }
1165 }
1166
1166 lines RUST