Skip to main content

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