Skip to main content

agent_tui/tui/
mod.rs

1//! Chat TUI binary — event loop, terminal setup, module wiring.
2mod transcript;
3
4
5mod app;
6mod clock;
7mod commands;
8mod dispatch;
9mod draw;
10mod view_model;
11mod focus;
12pub(crate) mod text_metrics;
13mod gamba;
14mod help_find;
15mod helpers;
16mod highlight;
17mod input;
18mod lifecycle;
19mod lightbox;
20mod loop_arms;
21mod markdown;
22mod models;
23mod plugins;
24mod render;
25mod render_model;
26mod render_thread;
27mod run_setup;
28mod settings;
29mod sidecar;
30mod signals;
31mod stream_handler;
32/// P16.1: terminal capability facts (env-only detection; inert seam).
33mod termcaps;
34/// Headless test harness — see [`testing::TestHarness`]. Compiled only for
35/// in-crate tests or downstream consumers of the `testing` feature.
36#[cfg(any(test, feature = "testing"))]
37pub mod testing;
38mod theme;
39mod toast;
40mod viewport;
41
42/// Single process-global lock for ALL tests that mutate config-env vars
43/// (`SYNAPS_BASE_DIR`, `HOME`).  Both `migration_tests` (this file) and the
44/// `BASE_DIR_TEST_LOCK` tests in `plugins/actions.rs` must hold this lock for
45/// the duration of any test that sets or reads those vars, so the two groups
46/// can never interleave even when `cargo test` runs them on parallel threads.
47#[cfg(test)]
48pub(crate) static CONFIG_ENV_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
49
50use app::{App, ChatMessage, THINKING_PLACEHOLDER};
51use commands::CommandAction;
52use draw::{boot_effect, build_render_model, quit_effect};
53use helpers::{apply_setting, fetch_usage, rebuild_display_messages, should_draw};
54use input::InputAction;
55use lifecycle::setup_terminal;
56use render_thread::spawn_render_thread;
57
58use crossterm::event::EventStream;
59use futures::StreamExt;
60use serde_json::json;
61use std::sync::atomic::Ordering;
62use std::time::Instant;
63use synaps_cli::core::session_index::SessionIndexRecord;
64use synaps_cli::runtime::compaction::compact_conversation;
65use synaps_cli::{CancellationToken, Result, Runtime, Session};
66
67pub async fn run(
68    continue_session: Option<Option<String>>,
69    system: Option<String>,
70    profile: Option<String>,
71    no_extensions: bool,
72) -> Result<()> {
73    // ── Boot prologue (P12.1: extracted to run_setup.rs) ──
74    // run_setup performs engine-boot unpack, App construction (incl. the
75    // resumed-session branch), channel/handle setup, render-thread spawn,
76    // and tick-throttle init. Behavior byte-identical; the loop below owns
77    // every field by value exactly as it did when they were locals.
78    let run_setup::RunContext {
79        mut app,
80        mut runtime,
81        mut config,
82        registry,
83        keybind_registry,
84        system_prompt_path,
85        render_handle,
86        boot_done,
87        exit_done,
88        term_caps,
89        event_reader,
90        mut shutdown_signal_rx,
91        shutdown_signal_task,
92        mut stream,
93        secret_prompt_handle,
94        secret_prompt_rx,
95        mut cancel_token,
96        mut steer_tx,
97        background,
98        ext_mgr_shared,
99        mut boot_fx_sent,
100        mut exit_fx_sent,
101        mut last_draw,
102    } = run_setup::run_setup(continue_session, system, profile, no_extensions).await?;
103    // P16.1+P16.2: terminal capabilities — env detection merged with the
104    // DA1-fenced query burst run inside run_setup() (after raw-mode enable,
105    // BEFORE the EventStream above was created; see run_setup.rs). Still
106    // inert: nothing gates on this until P16.3. The only wiring is this
107    // `--verbose` (debug-level) boot line dumping the negotiated caps.
108    tracing::debug!(caps = %term_caps.summary(), "negotiated terminal capabilities (env + DA1-fenced burst)");
109    // P12.2: Option-wrapped so dispatch::handle_input_action can drop the
110    // reader early (gamba terminal handoff) through a `&mut` without moving
111    // it out of the loop. Always Some outside the dispatch call.
112    let mut event_reader = Some(event_reader);
113    loop {
114        // Only draw when something actually changed. During streaming, coalesce
115        // redraws to the configured frame budget (`max_fps`, default 60fps =
116        // ~16ms) — deltas and the spinner arrive faster than the eye reads, and
117        // building/publishing the RenderModel per frame is main-thread work
118        // (it re-renders the streaming message's markdown each frame). User
119        // input bypasses the cap via `force_redraw` so scroll/typing stays
120        // instant, and the `!app.streaming` short-circuit renders the final/idle
121        // frame immediately so end-of-turn state never lags. Tune via
122        // `max_fps = 60|144|240|…` in ~/.synaps-cli/config. (Was a hardcoded
123        // 100ms/10fps #131 throttle; 0.3.6 made publish O(viewport) so the cap
124        // could be raised to a real frame rate without burning a core.)
125        let throttle = std::time::Duration::from_millis(1000 / config.max_fps.max(1) as u64);
126        if should_draw(app.needs_redraw, app.force_redraw, app.streaming, last_draw.elapsed(), throttle) {
127            // Terminal lives on the render thread — get size via the crossterm
128            // TTY syscall directly (doesn't need the Terminal object).
129            // Skip the frame entirely if the reported size is 0×0 (terminal not
130            // yet ready, or a transient resize event) — publishing a 0×0 model
131            // would produce layout artifacts.
132            let term_size = match crossterm::terminal::size() {
133                Ok((w, h)) if w > 0 && h > 0 => ratatui::layout::Size { width: w, height: h },
134                _ => {
135                    // Terminal not yet ready or transient resize — clear redraw
136                    // flags and back off so we don't busy-spin when the size is
137                    // 0×0 or the syscall fails (#tui-safety fix 1).
138                    app.needs_redraw = false;
139                    app.force_redraw = false;
140                    last_draw = Instant::now();
141                    continue;
142                }
143            };
144            app.needs_redraw = false;
145            app.force_redraw = false;
146            last_draw = Instant::now();
147            let built = build_render_model(
148                &mut view_model::ViewInputs::from_app(&mut app),
149                &runtime,
150                &registry,
151                term_size,
152            );
153            if let Some((model, patch)) = built {
154                patch.apply(&mut app);
155                render_handle.publish(model);
156            }
157        }
158
159        tokio::select! {
160
161            // ── OS shutdown signals: Ctrl-C from terminal, SIGTERM from systemd/tmux/SSH ──
162            signal = shutdown_signal_rx.recv() => {
163                if let Some(signal) = signal {
164                    tracing::info!(signal = signals::signal_label(signal), "chat UI shutdown signal received");
165                    // All OS signals map to ImmediateExit (see signals.rs).
166                    // The /quit command sends SpawnExitFx to the render thread
167                    // and does NOT go through this path, so removing AnimatedExit
168                    // from signals does not affect interactive quit.
169                    let signals::ShutdownAction::ImmediateExit = signals::shutdown_action(signal);
170                    tracing::info!("immediate exit on {:?}", signal);
171                    // Cancel any in-flight stream so the tool/subagent is not
172                    // orphaned for the full watchdog window.
173                    if let Some(ref ct) = cancel_token { ct.cancel(); }
174                    // Abort any in-flight compaction so it doesn't hold state
175                    // open past the teardown budget.
176                    if let Some(ref h) = app.compact_task { h.abort(); }
177                    // Fall through to unified bounded-teardown below the loop.
178                    break;
179                }
180            }
181
182            // ── Ping results — fires when a model ping completes ──
183            result = app.ping_rx.recv() => {
184                loop_arms::handle_ping_arm(&mut app, result);
185            }
186
187            // ── Expanded model-list results ──
188            result = app.model_list_rx.recv() => {
189                loop_arms::handle_model_list_arm(&mut app, result);
190            }
191
192            // ── Async extension loader progress ──
193            event = app.extension_loader_rx.recv(), if app.extension_loader_running => {
194                loop_arms::handle_extension_loader_arm(&mut app, &runtime, event, &ext_mgr_shared).await;
195            }
196
197            // ── Widget events from background extension notification watchers ──
198            Some(widget_event) = app.widget_rx.recv() => {
199                loop_arms::handle_widget_arm(&mut app, widget_event);
200            }
201
202            // ── Sidecar events — multiplexed across all hosted sidecars (Phase 8 8B) ──
203            sidecar_event = async {
204                if app.sidecars.is_empty() {
205                    let _: () = std::future::pending().await;
206                    unreachable!()
207                } else {
208                    // Collect (plugin_id, &mut manager) and race them.
209                    let mut futures = Vec::with_capacity(app.sidecars.len());
210                    for (pid, v) in app.sidecars.iter_mut() {
211                        let pid = pid.clone();
212                        futures.push(Box::pin(async move {
213                            let ev = v.manager.next_event().await;
214                            (pid, ev)
215                        }));
216                    }
217                    let ((pid, ev), _, _) = futures::future::select_all(futures).await;
218                    (pid, ev)
219                }
220            } => {
221                let (pid, sidecar_event) = sidecar_event;
222                if let Some(event) = sidecar_event {
223                    self::sidecar::handle_event(&mut app, &pid, event);
224                    app.request_redraw();
225                }
226            }
227
228            // ── Event bus wake — fires instantly when an event is pushed to the queue.
229            // P12.4: arm body moved verbatim to stream_handler::handle_event_queue_arm.
230            _ = runtime.event_queue().notified() => {
231                stream_handler::handle_event_queue_arm(
232                    &mut app, &runtime, &secret_prompt_handle,
233                    &mut stream, &mut cancel_token, &mut steer_tx,
234                ).await;
235            }
236
237            // ── Tick: animations + spinner (~60fps when active) ──
238            _ = tokio::time::sleep(std::time::Duration::from_millis(16)), if boot_fx_sent || exit_fx_sent || app.streaming || app.compact_task.is_some() || 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()) => {
239                if loop_arms::handle_animation_tick(
240                    &mut app, &runtime, &config, &registry, &render_handle,
241                    &secret_prompt_rx, &boot_done, &exit_done,
242                    &mut boot_fx_sent, exit_fx_sent,
243                )
244                .await
245                {
246                    break;
247                }
248            }
249
250            // ── Input: keyboard, mouse, paste ──
251            maybe_event = event_reader.as_mut().expect("event_reader is always Some outside dispatch").next(), if app.gamba_child.is_none() => {
252                match maybe_event {
253                    Some(Ok(event)) => {
254                        // P7.8: the secret-prompt interception is gone — SecretPrompt
255                        // is a stack-routed pane (`route_secret_prompt`), dispatched
256                        // below by `input::handle_event` on `modal_stack.top()`.
257                        let is_streaming = app.streaming;
258                        // Scope the registry read guard to this block so it is
259                        // provably released before any later `.await`
260                        // (clippy::await_holding_lock) — the guard never spans a
261                        // yield point.
262                        let action = {
263                            let kb_guard = keybind_registry.read().expect("keybind registry poisoned");
264                            input::handle_event(event, &mut app, &runtime, is_streaming, &registry, &kb_guard, config.scroll_lines.unwrap_or(3))
265                        };
266                        // Input events (keys, mouse, paste, resize) almost always
267                        // change visible state (cursor, input buffer, scroll) and
268                        // must feel instant — bypass the streaming redraw throttle.
269                        app.request_immediate_redraw();
270                        // P12.2: the ~1,300-line InputAction dispatch match moved
271                        // verbatim to dispatch::handle_input_action (dispatch.rs).
272                        // LoopState lends exactly the loop-locals the match
273                        // touched; Break maps to the outer `break` (unused today,
274                        // honored anyway), Continue to the old fall-through.
275                        let state = dispatch::LoopState {
276                            app: &mut app,
277                            runtime: &mut runtime,
278                            config: &mut config,
279                            registry: &registry,
280                            keybind_registry: &keybind_registry,
281                            system_prompt_path: &system_prompt_path,
282                            render_handle: &render_handle,
283                            event_reader: &mut event_reader,
284                            stream: &mut stream,
285                            secret_prompt_handle: &secret_prompt_handle,
286                            cancel_token: &mut cancel_token,
287                            steer_tx: &mut steer_tx,
288                            ext_mgr_shared: &ext_mgr_shared,
289                            exit_fx_sent: &mut exit_fx_sent,
290                        };
291                        if dispatch::handle_input_action(action, state).await.is_break() {
292                            break;
293                        }
294                    }
295                    // FIX C (defense in depth): EventStream yields Err or None when
296                    // crossterm detects the PTY is gone. Break cleanly here.
297                    // NOTE: on some kernels crossterm's EPOLL loop can spin without ever
298                    // yielding Err/None on a dead PTY (the confirmed busy-loop bug). The
299                    // render thread's I/O error path is the backstop: it logs the error
300                    // and keeps rendering until the main loop tears down (does NOT break
301                    // the render loop on a single I/O error).
302                    Some(Err(_)) | None => break,
303                }
304            }
305
306            // ── Stream events from runtime. P12.4: the polling future stays
307            // inline (it borrows `stream`); the arm body moved verbatim to
308            // stream_handler::handle_stream_arm — delta/tool_use/done/abort
309            // lifecycle is preserved exactly (hot path).
310            maybe_event = async {
311                if let Some(ref mut s) = stream {
312                    s.next().await
313                } else {
314                    std::future::pending().await
315                }
316            } => {
317                stream_handler::handle_stream_arm(
318                    maybe_event, &mut app, &runtime, &registry, &render_handle,
319                    &secret_prompt_handle, &mut stream, &mut cancel_token, &mut steer_tx,
320                ).await;
321            }
322        }
323    }
324
325    // ── PART 2: Bounded teardown — two sequential budgets.
326    //
327    // All timing constants are defined in signals.rs (single source of truth):
328    //   SAVE_TIMEOUT_SECS  — session save + index record (data safety first)
329    //   HOOKS_TIMEOUT_SECS — on_session_end hook emit (concurrent, fail-open)
330    //   TEARDOWN_TIMEOUT_SECS = SAVE_TIMEOUT_SECS + HOOKS_TIMEOUT_SECS
331    //
332    // Session save ALWAYS runs first in its own timeout so slow extension
333    // handlers cannot starve it.  Even if the hook budget is exhausted, the
334    // session data on disk is already safe before hooks are attempted.
335    {
336        let session_id = app.session.id.clone();
337        let api_messages = app.api_messages.clone();
338
339        // ── STEP 1: Save session data — own bounded timeout, highest priority ──
340        let save_fut = async {
341            app.save_session().await;
342
343            let mut index_record = SessionIndexRecord::end(&session_id);
344            index_record.turns = Some(api_messages.len());
345            if let Err(err) = synaps_cli::core::session_index::append_record(&index_record) {
346                tracing::warn!("failed to append session end index record: {}", err);
347            }
348        };
349
350        match tokio::time::timeout(
351            std::time::Duration::from_secs(signals::SAVE_TIMEOUT_SECS),
352            save_fut,
353        )
354        .await
355        {
356            Ok(()) => tracing::debug!("session save completed"),
357            Err(_elapsed) => {
358                tracing::warn!(
359                    budget_secs = signals::SAVE_TIMEOUT_SECS,
360                    "session save timed out — data may be incomplete"
361                );
362                lifecycle::emergency_teardown_terminal();
363                std::process::exit(1);
364            }
365        }
366
367        // ── STEP 2: Fire on_session_end hook — own bounded timeout, after save ──
368        //
369        // emit_concurrent() dispatches all on_session_end handlers simultaneously
370        // under one shared timeout window instead of N×5 s serial.  This is safe
371        // because on_session_end only allows `Continue` results — handlers are
372        // independent fire-and-forget notification calls (deck, d20, jawz-widget,
373        // synaps-tasks each write to their own stores; no ordering dependency).
374        //
375        // Ordering-safety evidence: HookKind::OnSessionEnd::allowed_action_names()
376        // returns &["continue"] exclusively; allows_result() permits only Continue;
377        // emit_concurrent() merges injections (N/A here) and treats timeouts as
378        // continue (fail-open).  Serial ordering cannot matter when the return
379        // value is always Continue and handlers touch disjoint state.
380        let transcript = Some(api_messages);
381        let hook_event = synaps_cli::extensions::hooks::events::HookEvent::on_session_end(
382            &session_id,
383            transcript,
384        );
385        match tokio::time::timeout(
386            std::time::Duration::from_secs(signals::HOOKS_TIMEOUT_SECS),
387            runtime.hook_bus().emit_concurrent(&hook_event),
388        )
389        .await
390        {
391            Ok(_) => tracing::debug!("on_session_end hooks completed"),
392            Err(_elapsed) => {
393                tracing::warn!(
394                    budget_secs = signals::HOOKS_TIMEOUT_SECS,
395                    "on_session_end hooks timed out — extensions may not have flushed"
396                );
397                // Session is already saved above — no data loss here.
398                // Fall through to normal teardown.
399            }
400        }
401
402        tracing::debug!("clean teardown completed");
403    }
404
405    // Let extension shutdown continue in the background; exit should not hang on
406    // extension post/session-end cleanup or slow child-process teardown.
407    let _extension_shutdown =
408        synaps_cli::extensions::manager::ExtensionManager::shutdown_all_detached(
409            std::sync::Arc::clone(&ext_mgr_shared),
410        );
411    // Stop the signal-listener thread (signal-hook handle, not a JoinHandle).
412    shutdown_signal_task.close();
413
414    // Shut down background tasks (inbox watcher, socket, session registry)
415    background.shutdown();
416
417    // ── Render-thread teardown ───────────────────────────────────────────────
418    //
419    // The render thread owns the Terminal.  We send it a Teardown command and
420    // wait for the ack within the combined SAVE + HOOKS budget already spent
421    // above.  If the ack doesn't arrive the thread is wedged (dead PTY); we
422    // skip the join and let process exit reap it — see RenderHandle::teardown.
423    // This self-bounding teardown replaced the old signal watchdog (#116).
424    //
425    // The render thread's do_teardown() calls emergency_teardown_terminal()
426    // (disable_raw_mode + LeaveAlternateScreen + etc.) and show_cursor(), then
427    // sends the ack and exits its loop.  The Terminal is dropped when the
428    // thread exits — that's safe because crossterm teardown was already done.
429    let teardown_budget = std::time::Duration::from_secs(
430        signals::TEARDOWN_TIMEOUT_SECS.saturating_sub(signals::SAVE_TIMEOUT_SECS),
431    )
432    .max(std::time::Duration::from_secs(2));
433    let acked = render_handle.teardown(teardown_budget);
434    if !acked {
435        tracing::warn!("render thread did not ack teardown within budget — watchdog is backstop");
436        // emergency_teardown_terminal is a no-op if the terminal is already
437        // restored, so calling it here is safe even if the render thread did
438        // eventually finish teardown after the timeout.
439        lifecycle::emergency_teardown_terminal();
440    }
441
442    Ok(())
443}