agent_tui/tui/mod.rs
1//! Chat TUI binary — event loop, terminal setup, module wiring.
2mod transcript;
3
4mod app;
5/// A4: the TUI over `SocketTransport` (`synaps --attach`).
6pub mod attach;
7pub mod client_diet;
8mod clock;
9mod commands;
10mod dispatch;
11mod draw;
12mod driver_client;
13mod effort;
14mod focus;
15mod gamba;
16mod help_find;
17mod helpers;
18mod highlight;
19mod input;
20mod lifecycle;
21mod lightbox;
22mod loop_arms;
23mod markdown;
24mod modal_kit;
25mod models;
26mod neon_prompt;
27mod plugins;
28pub mod quit_guard;
29mod render;
30mod render_model;
31mod render_thread;
32mod run_setup;
33mod session_link;
34mod settings;
35mod sidecar;
36mod signals;
37mod stream_handler;
38mod subagent_tray;
39/// P16.1: terminal capability facts (env-only detection; inert seam).
40mod termcaps;
41/// Headless test harness — see [`testing::TestHarness`]. Compiled only for
42/// in-crate tests or downstream consumers of the `testing` feature.
43#[cfg(any(test, feature = "testing"))]
44pub mod testing;
45pub(crate) mod text_metrics;
46mod theme;
47mod toast;
48mod view_model;
49mod viewport;
50
51/// Single process-global lock for ALL tests that mutate config-env vars
52/// (`SYNAPS_BASE_DIR`, `HOME`). Both `migration_tests` (this file) and the
53/// `BASE_DIR_TEST_LOCK` tests in `plugins/actions.rs` must hold this lock for
54/// the duration of any test that sets or reads those vars, so the two groups
55/// can never interleave even when `cargo test` runs them on parallel threads.
56#[cfg(test)]
57pub(crate) static CONFIG_ENV_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
58
59pub use run_setup::push_boot_notice;
60
61use app::{App, ChatMessage};
62use commands::CommandAction;
63use draw::{boot_effect, build_render_model, quit_effect};
64use helpers::{apply_setting, fetch_usage, rebuild_display_messages, should_draw};
65use input::InputAction;
66use lifecycle::setup_terminal;
67use render_thread::spawn_render_thread;
68
69use crossterm::event::EventStream;
70use futures::StreamExt;
71use serde_json::json;
72use std::sync::atomic::Ordering;
73use std::time::Instant;
74use synaps_cli::Result;
75
76use agent_engine::session::{EndReason, SessionCommand};
77
78pub async fn run(
79 continue_session: Option<Option<String>>,
80 system: Option<String>,
81 prompt_manifest: Option<std::path::PathBuf>,
82 profile: Option<String>,
83 no_extensions: bool,
84) -> Result<()> {
85 // ── Boot prologue (P12.1: extracted to run_setup.rs) ──
86 // run_setup performs engine-boot unpack, App construction (incl. the
87 // resumed-session branch), channel/handle setup, render-thread spawn,
88 // and tick-throttle init. Behavior byte-identical; the loop below owns
89 // every field by value exactly as it did when they were locals.
90 let ctx = run_setup::run_setup(
91 continue_session,
92 system,
93 prompt_manifest,
94 profile,
95 no_extensions,
96 )
97 .await?;
98 run_loop(ctx).await
99}
100
101/// The event loop + teardown, shared by the in-process boot and the socket
102/// attach (`run_attached`).
103pub(crate) async fn run_loop(ctx: run_setup::RunContext) -> Result<()> {
104 let run_setup::RunContext {
105 mut app,
106 mut link,
107 http,
108 mut prompt_bridge,
109 mode,
110 mut config,
111 registry,
112 keybind_registry,
113 system_prompt_path,
114 render_handle,
115 boot_done,
116 exit_done,
117 term_caps,
118 event_reader,
119 mut shutdown_signal_rx,
120 shutdown_signal_task,
121 secret_prompt_rx,
122 ext_mgr_shared,
123 mut boot_fx_sent,
124 mut exit_fx_sent,
125 mut last_draw,
126 } = ctx;
127 // P16.1+P16.2: terminal capabilities — env detection merged with the
128 // DA1-fenced query burst run inside run_setup() (after raw-mode enable,
129 // BEFORE the EventStream above was created; see run_setup.rs). Still
130 // inert: nothing gates on this until P16.3. The only wiring is this
131 // `--verbose` (debug-level) boot line dumping the negotiated caps.
132 tracing::debug!(caps = %term_caps.summary(), "negotiated terminal capabilities (env + DA1-fenced burst)");
133 // P12.2: Option-wrapped so dispatch::handle_input_action can drop the
134 // reader early (gamba terminal handoff) through a `&mut` without moving
135 // it out of the loop. Always Some outside the dispatch call.
136 let mut event_reader = Some(event_reader);
137 // Live-MXC layer (myx theme): boot the subscriber when configured.
138 loop_arms::boot_myx_live(&mut app);
139 // Throttle state for idle subagent reconcile (~1s cadence in the tick arm).
140 let mut last_subagent_reconcile: Option<std::time::Instant> = None;
141 let mut first_frame_done = false;
142 let mut idle_purge = client_diet::IdlePurge::new(matches!(mode, run_setup::TransportMode::Socket));
143 loop {
144 // Only draw when something actually changed. During streaming, coalesce
145 // redraws to the configured frame budget (`max_fps`, default 60fps =
146 // ~16ms) — deltas and the spinner arrive faster than the eye reads, and
147 // building/publishing the RenderModel per frame is main-thread work
148 // (it re-renders the streaming message's markdown each frame). User
149 // input bypasses the cap via `force_redraw` so scroll/typing stays
150 // instant, and the `!app.streaming` short-circuit renders the final/idle
151 // frame immediately so end-of-turn state never lags. Tune via
152 // `max_fps = 60|144|240|…` in ~/.synaps-cli/config. (Was a hardcoded
153 // 100ms/10fps #131 throttle; 0.3.6 made publish O(viewport) so the cap
154 // could be raised to a real frame rate without burning a core.)
155 let throttle = std::time::Duration::from_millis(1000 / config.max_fps.max(1) as u64);
156 if should_draw(
157 app.needs_redraw,
158 app.force_redraw,
159 app.streaming,
160 last_draw.elapsed(),
161 throttle,
162 ) {
163 // Terminal lives on the render thread — get size via the crossterm
164 // TTY syscall directly (doesn't need the Terminal object).
165 // Skip the frame entirely if the reported size is 0×0 (terminal not
166 // yet ready, or a transient resize event) — publishing a 0×0 model
167 // would produce layout artifacts.
168 let term_size = match crossterm::terminal::size() {
169 Ok((w, h)) if w > 0 && h > 0 => ratatui::layout::Size {
170 width: w,
171 height: h,
172 },
173 _ => {
174 // Terminal not yet ready or transient resize — clear redraw
175 // flags and back off so we don't busy-spin when the size is
176 // 0×0 or the syscall fails (#tui-safety fix 1).
177 app.needs_redraw = false;
178 app.force_redraw = false;
179 last_draw = Instant::now();
180 continue;
181 }
182 };
183 app.needs_redraw = false;
184 app.force_redraw = false;
185 last_draw = Instant::now();
186 let built = build_render_model(
187 &mut view_model::ViewInputs::from_app(&mut app),
188 &**link.view(),
189 ®istry,
190 term_size,
191 );
192 if let Some((model, patch)) = built {
193 patch.apply(&mut app);
194 render_handle.publish(model);
195 if !first_frame_done {
196 first_frame_done = true;
197 agent_core::core::memstat::ladder("first_frame", &"");
198 }
199 }
200 }
201 idle_purge.observe(app.streaming || app.compacting);
202
203 tokio::select! {
204
205 // ── OS shutdown signals: Ctrl-C from terminal, SIGTERM from systemd/tmux/SSH ──
206 signal = shutdown_signal_rx.recv() => {
207 if let Some(signal) = signal {
208 tracing::info!(signal = signals::signal_label(signal), "chat UI shutdown signal received");
209 // All OS signals map to ImmediateExit (see signals.rs).
210 // The /quit command sends SpawnExitFx to the render thread
211 // and does NOT go through this path, so removing AnimatedExit
212 // from signals does not affect interactive quit.
213 let signals::ShutdownAction::ImmediateExit = signals::shutdown_action(signal);
214 tracing::info!("immediate exit on {:?}", signal);
215 // The actor cancels the in-flight turn/compaction on End.
216 // Fall through to unified bounded-teardown below the loop.
217 break;
218 }
219 }
220
221 // ── Client diet: idle purge (socket client only; §4.4) ──
222 _ = idle_purge.wait() => {
223 idle_purge.fire();
224 }
225
226 // ── Ping results — fires when a model ping completes ──
227 result = app.ping_rx.recv() => {
228 loop_arms::handle_ping_arm(&mut app, result);
229 }
230
231 // ── Expanded model-list results ──
232 result = app.model_list_rx.recv() => {
233 loop_arms::handle_model_list_arm(&mut app, result);
234 }
235
236 // ── Async extension loader progress ──
237 event = app.extension_loader_rx.recv(), if app.extension_loader_running => {
238 loop_arms::handle_extension_loader_arm(&mut app, link.view(), event, ext_mgr_shared.as_ref()).await;
239 }
240
241 // ── Widget events from background extension notification watchers ──
242 Some(widget_event) = app.widget_rx.recv() => {
243 loop_arms::handle_widget_arm(&mut app, widget_event);
244 }
245
246 // ── Live MXC palettes (myx theme) — UI-thread apply, same path as /theme ──
247 Some(myx_theme) = app.myx_theme_rx.recv() => {
248 loop_arms::handle_myx_theme_arm(&mut app, myx_theme);
249 }
250
251 // ── Sidecar events — multiplexed across all hosted sidecars (Phase 8 8B) ──
252 sidecar_event = self::sidecar::next_event(&mut app.sidecars) => {
253 let (pid, event) = sidecar_event;
254 self::sidecar::handle_event(&mut app, &pid, event);
255 app.request_redraw();
256 }
257
258 // ── Sidecar non-blocking startup completion (G3, in-process only) ──
259 // Socket path: the TUI does not own a SidecarManager (G Q1);
260 // sidecar_starts is always empty under Socket, so this arm pends.
261 (pid, result) = self::sidecar::next_startup(&mut app.sidecar_starts) => {
262 self::sidecar::finish_startup(&mut app, ®istry, pid, result);
263 app.request_redraw();
264 }
265
266 // ── Secret-prompt answers from the pane (PromptBridge) → Answer ──
267 Some((prompt_id, value)) = prompt_bridge.answers_rx.recv() => {
268 prompt_bridge.on_local_answer(prompt_id);
269 let _ = link.send(SessionCommand::Answer { prompt_id, value }).await;
270 }
271
272 // ── Tick: animations + spinner (~60fps when active) ──
273 _ = tokio::time::sleep(std::time::Duration::from_millis(16)), if boot_fx_sent || exit_fx_sent || app.streaming || app.compacting || app.transcript.is_empty() || app.logo_dismiss_t.is_some() || app.logo_build_t.is_some() || app.gamba_child.is_some() || app.secret_prompts.is_active() || !app.toasts.is_empty() || app.plugins.as_ref().is_some_and(|p| p.is_install_active()) || !app.subagents.is_empty() || app.theme_transition.is_some() || app.prompt_clock.animating(app.clock.now(), app.streaming) => {
274 if loop_arms::handle_animation_tick(
275 &mut app, &config, ®istry, &render_handle,
276 &secret_prompt_rx, &boot_done, &exit_done,
277 &mut boot_fx_sent, exit_fx_sent,
278 &mut last_subagent_reconcile,
279 )
280 .await
281 {
282 break;
283 }
284 }
285
286 // ── Input: keyboard, mouse, paste ──
287 maybe_event = event_reader.as_mut().expect("event_reader is always Some outside dispatch").next(), if app.gamba_child.is_none() => {
288 match maybe_event {
289 Some(Ok(event)) => {
290 // P7.8: the secret-prompt interception is gone — SecretPrompt
291 // is a stack-routed pane (`route_secret_prompt`), dispatched
292 // below by `input::handle_event` on `modal_stack.top()`.
293 let is_streaming = app.streaming;
294 // Scope the registry read guard to this block so it is
295 // provably released before any later `.await`
296 // (clippy::await_holding_lock) — the guard never spans a
297 // yield point.
298 let action = {
299 let kb_guard = keybind_registry.read().expect("keybind registry poisoned");
300 input::handle_event(event, &mut app, &**link.view(), is_streaming, ®istry, &kb_guard, config.scroll_lines.unwrap_or(3))
301 };
302 // Input events (keys, mouse, paste, resize) almost always
303 // change visible state (cursor, input buffer, scroll) and
304 // must feel instant — bypass the streaming redraw throttle.
305 app.request_immediate_redraw();
306 // P12.2: the ~1,300-line InputAction dispatch match moved
307 // verbatim to dispatch::handle_input_action (dispatch.rs).
308 // LoopState lends exactly the loop-locals the match
309 // touched; Break maps to the outer `break` (unused today,
310 // honored anyway), Continue to the old fall-through.
311 let state = dispatch::LoopState {
312 app: &mut app,
313 link: &mut link,
314 http: &http,
315 config: &mut config,
316 registry: ®istry,
317 keybind_registry: &keybind_registry,
318 system_prompt_path: &system_prompt_path,
319 render_handle: &render_handle,
320 event_reader: &mut event_reader,
321 ext_mgr_shared: ext_mgr_shared.as_ref(),
322 exit_fx_sent: &mut exit_fx_sent,
323 is_socket: matches!(mode, run_setup::TransportMode::Socket),
324 };
325 if dispatch::handle_input_action(action, state).await.is_break() {
326 break;
327 }
328 }
329 // FIX C (defense in depth): EventStream yields Err or None when
330 // crossterm detects the PTY is gone. Break cleanly here.
331 // NOTE: on some kernels crossterm's EPOLL loop can spin without ever
332 // yielding Err/None on a dead PTY (the confirmed busy-loop bug). The
333 // render thread's I/O error path is the backstop: it logs the error
334 // and keeps rendering until the main loop tears down (does NOT break
335 // the render loop on a single I/O error).
336 Some(Err(_)) | None => break,
337 }
338 }
339
340 // ── Session envelopes: stream events + every actor notification
341 // (PLAN-phase3 §2.4). `None` = the actor is gone (in-process) or
342 // the socket closed (reconnect flow, A4).
343 maybe_env = link.next_event() => {
344 match maybe_env {
345 Some(env) => {
346 if let stream_handler::ArmFlow::Ended = stream_handler::handle_session_event_arm(
347 env, &mut app, &mut link, ®istry, &render_handle,
348 &mut prompt_bridge, ext_mgr_shared.as_ref(),
349 ).await {
350 break;
351 }
352 }
353 None => {
354 if !run_setup::try_reconnect(&mut app, &mut link, &mode, &render_handle, ®istry).await {
355 break;
356 }
357 }
358 }
359 }
360 }
361 }
362
363 // Stop the live-MXC subscriber FIRST — no background task writes past here.
364 loop_arms::abort_myx_live(&mut app);
365
366 // ── PART 2: Bounded teardown — the actor saves, fires on_session_end
367 // and flushes observability under its own budgets (`SessionActor::
368 // finish`); we ask for it and wait for `Ended` within the sum of those
369 // budgets plus margin (`SESSION_END_TIMEOUT_SECS`). The channel closing
370 // cleanly before `Ended` is observed is a clean exit too (exit 0); only
371 // an actor still running past its whole budget is an emergency exit.
372 // Over the socket the session lives on: Detach.
373 let teardown = std::time::Duration::from_secs(signals::SESSION_END_TIMEOUT_SECS);
374 if !link.is_closed() {
375 let cmd = match mode {
376 run_setup::TransportMode::Local { .. } => SessionCommand::End {
377 reason: EndReason::ClientQuit,
378 },
379 run_setup::TransportMode::Socket => SessionCommand::Detach {
380 client: link.client_id(),
381 },
382 };
383 let _ = link.send(cmd).await;
384 agent_core::core::memstat::ladder("detach", &"");
385 if let run_setup::TransportMode::Local { .. } = mode {
386 match tokio::time::timeout(teardown, link.wait_ended()).await {
387 Ok(true) => tracing::debug!("clean teardown completed"),
388 Ok(false) => {
389 tracing::debug!("session channel closed before Ended — clean exit")
390 }
391 Err(_elapsed) => {
392 tracing::warn!(
393 budget_secs = signals::SESSION_END_TIMEOUT_SECS,
394 "session end timed out — data may be incomplete"
395 );
396 lifecycle::emergency_exit();
397 }
398 }
399 }
400 }
401
402 // Let extension shutdown continue in the background; exit should not hang on
403 // extension post/session-end cleanup or slow child-process teardown.
404 let _extension_shutdown = ext_mgr_shared.as_ref().map(|m| {
405 synaps_cli::extensions::manager::ExtensionManager::shutdown_all_detached(
406 std::sync::Arc::clone(m),
407 )
408 });
409 // Stop the signal-listener thread (signal-hook handle, not a JoinHandle).
410 shutdown_signal_task.close();
411
412 // ── Render-thread teardown ───────────────────────────────────────────────
413 //
414 // The render thread owns the Terminal. We send it a Teardown command and
415 // wait for the ack within the combined SAVE + HOOKS budget already spent
416 // above. If the ack doesn't arrive the thread is wedged (dead PTY); we
417 // skip the join and let process exit reap it — see RenderHandle::teardown.
418 // This self-bounding teardown replaced the old signal watchdog (#116).
419 //
420 // The render thread's do_teardown() calls emergency_teardown_terminal()
421 // (disable_raw_mode + LeaveAlternateScreen + etc.) and show_cursor(), then
422 // sends the ack and exits its loop. The Terminal is dropped when the
423 // thread exits — that's safe because crossterm teardown was already done.
424 let teardown_budget = std::time::Duration::from_secs(
425 signals::TEARDOWN_TIMEOUT_SECS.saturating_sub(signals::SAVE_TIMEOUT_SECS),
426 )
427 .max(std::time::Duration::from_secs(2));
428 let acked = render_handle.teardown(teardown_budget);
429 if !acked {
430 tracing::warn!("render thread did not ack teardown within budget — watchdog is backstop");
431 // emergency_teardown_terminal is a no-op if the terminal is already
432 // restored, so calling it here is safe even if the render thread did
433 // eventually finish teardown after the timeout.
434 lifecycle::emergency_teardown_terminal();
435 }
436
437 // ── F9: daemon-lost exit — stderr message + non-zero code ──
438 if let Some(lost) = app.daemon_lost {
439 eprintln!(
440 "synaps: lost the daemon (pid {}) and could not reconnect within {} s \
441 — session {}; resume with synaps --attach {} / --continue {}",
442 lost.pid, lost.budget_secs, lost.session_id, lost.session_id, lost.session_id,
443 );
444 std::process::exit(agent_engine::daemon::EXIT_DAEMON_LOST);
445 }
446
447 Ok(())
448}