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 sidecar;
38mod signals;
39mod stream_handler;
40mod subagent_tray;
41/// P16.1: terminal capability facts (env-only detection; inert seam).
42mod termcaps;
43/// Headless test harness — see [`testing::TestHarness`]. Compiled only for
44/// in-crate tests or downstream consumers of the `testing` feature.
45#[cfg(any(test, feature = "testing"))]
46pub mod testing;
47pub(crate) mod text_metrics;
48mod theme;
49mod threads;
50mod toast;
51mod view_model;
52mod viewport;
53mod watch;
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        let throttle = std::time::Duration::from_millis(1000 / config.max_fps.max(1) as u64);
160        if should_draw(
161            app.needs_redraw,
162            app.force_redraw,
163            app.streaming,
164            last_draw.elapsed(),
165            throttle,
166        ) {
167            // Terminal lives on the render thread — get size via the crossterm
168            // TTY syscall directly (doesn't need the Terminal object).
169            // Skip the frame entirely if the reported size is 0×0 (terminal not
170            // yet ready, or a transient resize event) — publishing a 0×0 model
171            // would produce layout artifacts.
172            let term_size = match crossterm::terminal::size() {
173                Ok((w, h)) if w > 0 && h > 0 => ratatui::layout::Size {
174                    width: w,
175                    height: h,
176                },
177                _ => {
178                    // Terminal not yet ready or transient resize — clear redraw
179                    // flags and back off so we don't busy-spin when the size is
180                    // 0×0 or the syscall fails (#tui-safety fix 1).
181                    app.needs_redraw = false;
182                    app.force_redraw = false;
183                    last_draw = Instant::now();
184                    continue;
185                }
186            };
187            app.needs_redraw = false;
188            app.force_redraw = false;
189            last_draw = Instant::now();
190            let built = build_render_model(
191                &mut view_model::ViewInputs::from_app(&mut app),
192                &**link.view(),
193                &registry,
194                term_size,
195            );
196            if let Some((model, patch)) = built {
197                patch.apply(&mut app);
198                render_handle.publish(model);
199                if !first_frame_done {
200                    first_frame_done = true;
201                    agent_core::core::memstat::ladder("first_frame", &"");
202                }
203            }
204        }
205        idle_purge.observe(app.streaming || app.compacting);
206        // A fixed deadline, read before `select!` borrows `app`: a fresh
207        // `sleep` would restart every 16 ms animation tick and never fire.
208        let watch_due = watch::poll_due_at(&app);
209
210        tokio::select! {
211
212            // ── OS shutdown signals: Ctrl-C from terminal, SIGTERM from systemd/tmux/SSH ──
213            signal = shutdown_signal_rx.recv() => {
214                if let Some(signal) = signal {
215                    tracing::info!(signal = signals::signal_label(signal), "chat UI shutdown signal received");
216                    // All OS signals map to ImmediateExit (see signals.rs).
217                    // The /quit command sends SpawnExitFx to the render thread
218                    // and does NOT go through this path, so removing AnimatedExit
219                    // from signals does not affect interactive quit.
220                    let signals::ShutdownAction::ImmediateExit = signals::shutdown_action(signal);
221                    tracing::info!("immediate exit on {:?}", signal);
222                    // The actor cancels the in-flight turn/compaction on End.
223                    // Fall through to unified bounded-teardown below the loop.
224                    break;
225                }
226            }
227
228            // ── Client diet: idle purge (socket client only; §4.4) ──
229            _ = idle_purge.wait() => {
230                idle_purge.fire();
231            }
232
233            // ── Ping results — fires when a model ping completes ──
234            result = app.ping_rx.recv() => {
235                loop_arms::handle_ping_arm(&mut app, result);
236            }
237
238            // ── Expanded model-list results ──
239            result = app.model_list_rx.recv() => {
240                loop_arms::handle_model_list_arm(&mut app, result);
241            }
242
243            // ── /sessions modal: daemon list, past list, pin/close answers ──
244            Some(msg) = app.sessions_rx.recv() => {
245                loop_arms::handle_sessions_arm(&mut app, &link, msg);
246            }
247
248            // ── Async extension loader progress ──
249            event = app.extension_loader_rx.recv(), if app.extension_loader_running => {
250                loop_arms::handle_extension_loader_arm(&mut app, link.view(), event, ext_mgr_shared.as_ref()).await;
251            }
252
253            // ── Widget events from background extension notification watchers ──
254            Some(widget_event) = app.widget_rx.recv() => {
255                loop_arms::handle_widget_arm(&mut app, widget_event);
256            }
257
258            // ── Live MXC palettes (myx theme) — UI-thread apply, same path as /theme ──
259            Some(myx_theme) = app.myx_theme_rx.recv() => {
260                loop_arms::handle_myx_theme_arm(&mut app, myx_theme);
261            }
262
263            // ── Sidecar events — multiplexed across all hosted sidecars (Phase 8 8B) ──
264            sidecar_event = self::sidecar::next_event(&mut app.sidecars) => {
265                let (pid, event) = sidecar_event;
266                self::sidecar::handle_event(&mut app, &pid, event);
267                app.request_redraw();
268            }
269
270            // ── Sidecar non-blocking startup completion (G3, in-process only) ──
271            // Socket path: the TUI does not own a SidecarManager (G Q1);
272            // sidecar_starts is always empty under Socket, so this arm pends.
273            (pid, result) = self::sidecar::next_startup(&mut app.sidecar_starts) => {
274                self::sidecar::finish_startup(&mut app, &registry, pid, result);
275                app.request_redraw();
276            }
277
278            // ── Secret-prompt answers from the pane (PromptBridge) → Answer ──
279            Some((prompt_id, value)) = prompt_bridge.answers_rx.recv() => {
280                if prompt_bridge.on_local_answer(prompt_id) {
281                    let _ = link.send(SessionCommand::Answer { prompt_id, value }).await;
282                }
283            }
284
285            // ── Subagent watch: page the focused worker view's journal ──
286            _ = tokio::time::sleep_until(tokio::time::Instant::from_std(
287                watch_due.unwrap_or_else(Instant::now),
288            )), if watch_due.is_some() => {
289                watch::poll(&mut app, &mut link, Instant::now()).await;
290            }
291
292            // ── Tick: animations + spinner (~60fps when active) ──
293            _ = 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() || watch::focused(&app).is_some() || app.theme_transition.is_some() || app.prompt_clock.animating(app.clock.now(), app.streaming) => {
294                if loop_arms::handle_animation_tick(
295                    &mut app, &config, &registry, &render_handle,
296                    &secret_prompt_rx, &boot_done, &exit_done,
297                    &mut boot_fx_sent, exit_fx_sent,
298                    &mut last_subagent_reconcile,
299                )
300                .await
301                {
302                    break;
303                }
304            }
305
306            // ── Input: keyboard, mouse, paste ──
307            maybe_event = event_reader.as_mut().expect("event_reader is always Some outside dispatch").next(), if app.gamba_child.is_none() => {
308                match maybe_event {
309                    Some(Ok(event)) => {
310                        // P7.8: the secret-prompt interception is gone — SecretPrompt
311                        // is a stack-routed pane (`route_secret_prompt`), dispatched
312                        // below by `input::handle_event` on `modal_stack.top()`.
313                        let is_streaming = app.streaming;
314                        // Scope the registry read guard to this block so it is
315                        // provably released before any later `.await`
316                        // (clippy::await_holding_lock) — the guard never spans a
317                        // yield point.
318                        let action = {
319                            let kb_guard = keybind_registry.read().expect("keybind registry poisoned");
320                            input::handle_event(event, &mut app, &**link.view(), is_streaming, &registry, &kb_guard, config.scroll_lines.unwrap_or(3))
321                        };
322                        // Input events (keys, mouse, paste, resize) almost always
323                        // change visible state (cursor, input buffer, scroll) and
324                        // must feel instant — bypass the streaming redraw throttle.
325                        app.request_immediate_redraw();
326                        // P12.2: the ~1,300-line InputAction dispatch match moved
327                        // verbatim to dispatch::handle_input_action (dispatch.rs).
328                        // LoopState lends exactly the loop-locals the match
329                        // touched; Break maps to the outer `break` (unused today,
330                        // honored anyway), Continue to the old fall-through.
331                        let state = dispatch::LoopState {
332                            app: &mut app,
333                            link: &mut link,
334                            http: &http,
335                            config: &mut config,
336                            registry: &registry,
337                            keybind_registry: &keybind_registry,
338                            system_prompt_path: &system_prompt_path,
339                            render_handle: &render_handle,
340                            event_reader: &mut event_reader,
341                            ext_mgr_shared: ext_mgr_shared.as_ref(),
342                            exit_fx_sent: &mut exit_fx_sent,
343                            is_socket: matches!(mode, run_setup::TransportMode::Socket),
344                        };
345                        if dispatch::handle_input_action(action, state).await.is_break() {
346                            break;
347                        }
348                        loop_arms::drain_session_switch(&mut app, &mut link, &mut prompt_bridge, &registry, &render_handle).await;
349                    }
350                    // FIX C (defense in depth): EventStream yields Err or None when
351                    // crossterm detects the PTY is gone. Break cleanly here.
352                    // NOTE: on some kernels crossterm's EPOLL loop can spin without ever
353                    // yielding Err/None on a dead PTY (the confirmed busy-loop bug). The
354                    // render thread's I/O error path is the backstop: it logs the error
355                    // and keeps rendering until the main loop tears down (does NOT break
356                    // the render loop on a single I/O error).
357                    Some(Err(_)) | None => break,
358                }
359            }
360
361            // ── Session envelopes: stream events + every actor notification
362            // (PLAN-phase3 §2.4). `None` = the actor is gone (in-process) or
363            // the socket closed (reconnect flow, A4).
364            maybe_env = link.next_event() => {
365                match maybe_env {
366                    Some(env) => {
367                        if let stream_handler::ArmFlow::Ended = stream_handler::handle_session_event_arm(
368                            env, &mut app, &mut link, &registry, &render_handle,
369                            &mut prompt_bridge, ext_mgr_shared.as_ref(),
370                        ).await {
371                            break;
372                        }
373                    }
374                    None => {
375                        if !run_setup::try_reconnect(&mut app, &mut link, &mode, &render_handle, &registry).await {
376                            break;
377                        }
378                    }
379                }
380            }
381        }
382    }
383
384    // Stop the live-MXC subscriber FIRST — no background task writes past here.
385    loop_arms::abort_myx_live(&mut app);
386
387    // ── PART 2: Bounded teardown — the actor saves, fires on_session_end
388    // and flushes observability under its own budgets (`SessionActor::
389    // finish`); we ask for it and wait for `Ended` within the sum of those
390    // budgets plus margin (`SESSION_END_TIMEOUT_SECS`). The channel closing
391    // cleanly before `Ended` is observed is a clean exit too (exit 0); only
392    // an actor still running past its whole budget is an emergency exit.
393    // Over the socket the session lives on: Detach.
394    let teardown = std::time::Duration::from_secs(signals::SESSION_END_TIMEOUT_SECS);
395    if !link.is_closed() {
396        let cmd = match mode {
397            run_setup::TransportMode::Local { .. } => SessionCommand::End {
398                reason: EndReason::ClientQuit,
399            },
400            run_setup::TransportMode::Socket => SessionCommand::Detach {
401                client: link.client_id(),
402            },
403        };
404        let _ = link.send(cmd).await;
405        agent_core::core::memstat::ladder("detach", &"");
406        if let run_setup::TransportMode::Local { .. } = mode {
407            match tokio::time::timeout(teardown, link.wait_ended()).await {
408                Ok(true) => tracing::debug!("clean teardown completed"),
409                Ok(false) => {
410                    tracing::debug!("session channel closed before Ended — clean exit")
411                }
412                Err(_elapsed) => {
413                    tracing::warn!(
414                        budget_secs = signals::SESSION_END_TIMEOUT_SECS,
415                        "session end timed out — data may be incomplete"
416                    );
417                    lifecycle::emergency_exit();
418                }
419            }
420        }
421    }
422
423    // Let extension shutdown continue in the background; exit should not hang on
424    // extension post/session-end cleanup or slow child-process teardown.
425    let _extension_shutdown = ext_mgr_shared.as_ref().map(|m| {
426        synaps_cli::extensions::manager::ExtensionManager::shutdown_all_detached(
427            std::sync::Arc::clone(m),
428        )
429    });
430    // Stop the signal-listener thread (signal-hook handle, not a JoinHandle).
431    shutdown_signal_task.close();
432
433    // ── Render-thread teardown ───────────────────────────────────────────────
434    //
435    // The render thread owns the Terminal.  We send it a Teardown command and
436    // wait for the ack within the combined SAVE + HOOKS budget already spent
437    // above.  If the ack doesn't arrive the thread is wedged (dead PTY); we
438    // skip the join and let process exit reap it — see RenderHandle::teardown.
439    // This self-bounding teardown replaced the old signal watchdog (#116).
440    //
441    // The render thread's do_teardown() calls emergency_teardown_terminal()
442    // (disable_raw_mode + LeaveAlternateScreen + etc.) and show_cursor(), then
443    // sends the ack and exits its loop.  The Terminal is dropped when the
444    // thread exits — that's safe because crossterm teardown was already done.
445    let teardown_budget = std::time::Duration::from_secs(
446        signals::TEARDOWN_TIMEOUT_SECS.saturating_sub(signals::SAVE_TIMEOUT_SECS),
447    )
448    .max(std::time::Duration::from_secs(2));
449    let acked = render_handle.teardown(teardown_budget);
450    if !acked {
451        tracing::warn!("render thread did not ack teardown within budget — watchdog is backstop");
452        // emergency_teardown_terminal is a no-op if the terminal is already
453        // restored, so calling it here is safe even if the render thread did
454        // eventually finish teardown after the timeout.
455        lifecycle::emergency_teardown_terminal();
456    }
457
458    // ── F9: daemon-lost exit — stderr message + non-zero code ──
459    if let Some(lost) = app.daemon_lost {
460        eprintln!(
461            "synaps: lost the daemon (pid {}) and could not reconnect within {} s \
462             — session {}; resume with synaps --attach {} / --continue {}",
463            lost.pid, lost.budget_secs, lost.session_id, lost.session_id, lost.session_id,
464        );
465        std::process::exit(agent_engine::daemon::EXIT_DAEMON_LOST);
466    }
467    // A daemon session that ended under this client (`/close` here or on
468    // another client, `daemon stop`): which one, and how to bring it back.
469    // In-process, quitting always ends the session; nothing to say.
470    if let (run_setup::TransportMode::Socket, Some(reason)) = (&mode, app.session_ended) {
471        if let Some(line) = attach::session_ended_line(reason, &app.session.id, app.api_messages_len > 0) {
472            eprintln!("{line}");
473        }
474    }
475
476    Ok(())
477}