Skip to main content

hyprstream_tui/
chat_app.rs

1//! ChatApp — LLM chat terminal application.
2//!
3//! On native, implements [`waxterm::app::TerminalApp`] so it can be spawned via
4//! `spawn_app_process` inside the TuiService frame loop.  The inference
5//! background thread is injected as a [`StreamSpawner`] closure.
6//!
7//! On WASM, works as a push-based state machine: the host calls `on_token()`,
8//! `on_stream_complete()`, etc. directly, and `submit_message_payload()` returns
9//! the serialized JSON request for the host to forward.
10
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::collections::VecDeque;
14use uuid::Uuid;
15use waxterm::input::KeyPress;
16
17#[cfg(not(target_os = "wasi"))]
18use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
19#[cfg(not(target_os = "wasi"))]
20use ratatui_textarea::TextArea;
21#[cfg(not(target_os = "wasi"))]
22use std::sync::mpsc;
23#[cfg(not(target_os = "wasi"))]
24use std::sync::Arc;
25#[cfg(not(target_os = "wasi"))]
26use std::time::Instant;
27#[cfg(not(target_os = "wasi"))]
28use waxterm::app::TerminalApp;
29
30#[cfg(not(target_os = "wasi"))]
31fn keypress_to_crossterm(key: KeyPress) -> Option<KeyEvent> {
32    let (code, mods) = match key {
33        KeyPress::Char(b) if b.is_ascii_graphic() || b == b' ' => {
34            (KeyCode::Char(b as char), KeyModifiers::NONE)
35        }
36        KeyPress::Char(0x0A) => (KeyCode::Enter, KeyModifiers::NONE), // Ctrl-J
37        KeyPress::Enter => (KeyCode::Enter, KeyModifiers::NONE),
38        KeyPress::Backspace => (KeyCode::Backspace, KeyModifiers::NONE),
39        KeyPress::ArrowLeft => (KeyCode::Left, KeyModifiers::NONE),
40        KeyPress::ArrowRight => (KeyCode::Right, KeyModifiers::NONE),
41        KeyPress::ArrowUp => (KeyCode::Up, KeyModifiers::NONE),
42        KeyPress::ArrowDown => (KeyCode::Down, KeyModifiers::NONE),
43        KeyPress::Tab => (KeyCode::Tab, KeyModifiers::NONE),
44        // Ctrl-letter keys (0x01–0x1A, excluding already handled)
45        KeyPress::Char(b) if b < 0x20 => {
46            let ch = (b + b'a' - 1) as char;
47            (KeyCode::Char(ch), KeyModifiers::CONTROL)
48        }
49        _ => return None,
50    };
51    Some(KeyEvent {
52        code,
53        modifiers: mods,
54        kind: KeyEventKind::Press,
55        state: KeyEventState::NONE,
56    })
57}
58
59// ============================================================================
60// Public types
61// ============================================================================
62
63/// Per-session inference configuration, adjustable via the Settings modal.
64#[derive(Clone)]
65pub struct ChatGenConfig {
66    pub max_tokens: usize,
67    pub temperature: f32,
68    pub top_p: f32,
69    pub top_k: Option<usize>,
70    /// None = use model default; Some(n) = override context window on next load.
71    pub context_window: Option<usize>,
72}
73
74impl Default for ChatGenConfig {
75    fn default() -> Self {
76        Self {
77            max_tokens: 2048,
78            temperature: 0.7,
79            top_p: 0.9,
80            top_k: Some(40),
81            context_window: None,
82        }
83    }
84}
85
86/// Tool-call output format used by a model family.
87///
88/// Determines which markers to scan for in the streaming token output.
89/// Defined here (rather than importing from `hyprstream`) to keep this crate
90/// free of the main binary's dependency graph.
91#[derive(Clone, Copy, PartialEq, Eq, Default)]
92pub enum ToolCallFormat {
93    /// Qwen3 XML: `<tool_call>{"name":…,"arguments":…}</tool_call>`
94    Qwen3Xml,
95    /// Qwen3.5 XML parameter format:
96    /// `<tool_call><function=NAME><parameter=KEY>value</parameter>…</function></tool_call>`
97    Qwen35XmlParam,
98    /// Llama 3.1+: `<|python_tag|>` prefix + JSON
99    LlamaJson,
100    /// Mistral: `[TOOL_CALLS]` prefix + JSON array
101    MistralJson,
102    /// Model does not support tool calling (default).
103    #[default]
104    None,
105}
106
107/// Events sent from the inference background thread to `ChatApp::tick`.
108#[cfg(not(target_os = "wasi"))]
109pub enum ChatEvent {
110    Token(String),
111    StreamComplete,
112    /// Inference was cancelled by the user — partial content was already written.
113    StreamCancelled,
114    StreamError(String),
115    TemplateError(String),
116    /// A complete tool call block was parsed from the model output.
117    ToolCallDetected {
118        /// Per-invocation correlation ID.
119        id: String,
120        uuid: String,
121        description: String,
122        arguments: String,
123    },
124    /// Result from executing a tool call.
125    ToolCallResult {
126        /// Per-invocation correlation ID (matches `ToolCallDetected::id`).
127        id: String,
128        uuid: String,
129        result: String,
130    },
131}
132
133/// Role of a chat history entry.
134#[derive(Serialize, Deserialize, Clone)]
135pub enum ChatRole {
136    User,
137    Assistant,
138    /// Tool result injected back into the conversation.
139    Tool,
140}
141
142/// A recorded tool call and its result (or in-flight state).
143#[derive(Serialize, Deserialize, Clone)]
144pub struct ToolCallRecord {
145    /// Per-invocation correlation ID (UUID v4).  Used to match `ToolCallResult`
146    /// events back to this record.  Two calls to the same tool have different IDs.
147    #[serde(default)]
148    pub id: String,
149    /// The UUID name used on the wire (what the model outputs as `name`).
150    pub uuid: String,
151    /// Human-readable label fetched from `list_tools()`.
152    pub description: String,
153    /// JSON-encoded arguments string.
154    pub arguments: String,
155    /// Execution result. `None` while the call is in-flight.
156    pub result: Option<String>,
157}
158
159/// A single message in the conversation history.
160#[derive(Serialize, Deserialize, Clone)]
161pub struct ChatHistoryEntry {
162    pub role: ChatRole,
163    /// Visible response content (what gets sent back to the model as context).
164    pub content: String,
165    /// Reasoning / thinking tokens, hidden by default (not sent to model).
166    #[serde(default)]
167    pub thinking: String,
168    /// Tool calls made by this assistant turn.  Non-empty only on Assistant messages.
169    #[serde(default)]
170    pub tool_calls: Vec<ToolCallRecord>,
171    /// For Tool messages: the UUID of the corresponding assistant tool call.
172    #[serde(default)]
173    pub tool_call_id: Option<String>,
174}
175
176/// One-shot cancellation handle returned by `StreamSpawner`.
177/// Calling it signals the background thread to abort the current stream.
178#[cfg(not(target_os = "wasi"))]
179pub type CancelHandle = Box<dyn FnOnce() + Send + 'static>;
180
181/// Injected by `service.rs` — captures signing_key + model_ref.
182///
183/// Called with the current history and event channel every time the user
184/// submits a message or a tool result re-triggers generation.
185/// Returns a [`CancelHandle`] that aborts the stream.
186/// Must be `Send + 'static` because it is moved into the background thread
187/// spawned by `spawn_app_process`.
188#[cfg(not(target_os = "wasi"))]
189pub type StreamSpawner = Box<
190    dyn Fn(Vec<ChatHistoryEntry>, mpsc::SyncSender<ChatEvent>) -> CancelHandle + Send + 'static,
191>;
192
193/// Tool executor injected at construction time.
194///
195/// Called with `(id, uuid, arguments_json, event_tx)` where `id` is the
196/// per-invocation correlation ID to echo back in `ChatEvent::ToolCallResult`.
197/// Spawns a background thread internally and sends `ChatEvent::ToolCallResult`
198/// when done.
199#[cfg(not(target_os = "wasi"))]
200pub type ToolCaller =
201    Arc<dyn Fn(String, String, String, mpsc::SyncSender<ChatEvent>) + Send + Sync + 'static>;
202
203/// Called after `StreamComplete` to persist the current history.
204pub type SaveHook = Box<dyn Fn(&[ChatHistoryEntry]) + Send + 'static>;
205
206/// Called once at construction to restore prior history (returns `None` if no
207/// history exists yet).
208pub type LoadHook = Box<dyn FnOnce() -> Option<Vec<ChatHistoryEntry>> + Send + 'static>;
209
210// ============================================================================
211// App mode
212// ============================================================================
213
214pub enum ChatMode {
215    Input,
216    Streaming,
217    #[cfg(not(target_os = "wasi"))]
218    Editor,
219    /// Settings modal: ↑/↓ select field, ←/→ adjust, Enter save, Esc discard.
220    #[cfg(not(target_os = "wasi"))]
221    Settings {
222        selected_field: usize,
223    },
224}
225
226// ============================================================================
227// ChatApp
228// ============================================================================
229
230/// Double-Esc close window: two Esc presses within this interval close the app.
231#[cfg(not(target_os = "wasi"))]
232const DOUBLE_ESC_MS: u128 = 1500;
233
234pub struct ChatApp {
235    pub model_name: String,
236    pub history: Vec<ChatHistoryEntry>,
237    #[cfg(not(target_os = "wasi"))]
238    pub textarea: TextArea<'static>,
239    /// Simple input buffer for WASM (no TextArea available).
240    #[cfg(target_os = "wasi")]
241    pub input_buf: String,
242    pub mode: ChatMode,
243    /// Current text content held by the editor (set on Ctrl-E, read on Ctrl-S).
244    #[cfg(not(target_os = "wasi"))]
245    pub editor_text: String,
246    /// Number of lines from the tail to scroll back (0 = show tail).
247    pub scroll_offset: usize,
248    pub status: Option<String>,
249    #[cfg(not(target_os = "wasi"))]
250    event_rx: mpsc::Receiver<ChatEvent>,
251    #[cfg(not(target_os = "wasi"))]
252    event_tx: mpsc::SyncSender<ChatEvent>,
253    #[cfg(not(target_os = "wasi"))]
254    spawner: StreamSpawner,
255    pub cols: u16,
256    pub rows: u16,
257    pub quit: bool,
258    /// UUID for this private session (used as the storage filename key).
259    pub session_id: Option<Uuid>,
260    /// Fired after `StreamComplete` to persist `history`.
261    save_hook: Option<SaveHook>,
262    /// True while currently inside a `<think>…</think>` block in the stream.
263    in_thinking: bool,
264    /// Whether to display thinking blocks expanded (Ctrl-O to toggle).
265    pub show_thinking: bool,
266    /// Error messages queued for the outer compositor to surface as toasts.
267    /// Drained by the event loop each tick (see shell_handlers.rs).
268    pub pending_toasts: Vec<String>,
269    /// Cancel handle for the current in-flight stream. `None` when idle.
270    #[cfg(not(target_os = "wasi"))]
271    cancel_handle: Option<CancelHandle>,
272    /// Prompts queued while an inference is in flight.
273    pub pending_prompts: VecDeque<String>,
274    /// Timestamp of the last Esc press (for double-Esc-to-close detection).
275    #[cfg(not(target_os = "wasi"))]
276    last_esc: Option<Instant>,
277
278    // ── Generation config + settings modal ───────────────────────────────────
279    /// Shared generation config (read by spawner each invocation).
280    #[cfg(not(target_os = "wasi"))]
281    pub gen_config: Arc<parking_lot::RwLock<ChatGenConfig>>,
282    /// In-progress edits to generation config (committed on Enter, discarded on Esc).
283    #[cfg(not(target_os = "wasi"))]
284    pub settings_draft: ChatGenConfig,
285    /// Set when user saves a new context_window; polled by shell_handlers to
286    /// trigger model reload.  0 = use model default.
287    #[cfg(not(target_os = "wasi"))]
288    pub requested_context_window: Option<usize>,
289    /// True when this ChatApp is hosted inside TuiService (server-spawned).
290    /// In that mode, context window changes are surfaced as a toast rather than
291    /// triggering an automatic model reload.
292    #[cfg(not(target_os = "wasi"))]
293    pub is_server_spawned: bool,
294
295    // ── Tool calling ─────────────────────────────────────────────────────────
296    /// Optional tool executor (None when MCP service is unavailable).
297    #[cfg(not(target_os = "wasi"))]
298    tool_caller: Option<ToolCaller>,
299    /// UUID → human-readable description map built once from `list_tools()`.
300    pub tool_descriptions: HashMap<String, String>,
301    /// Format-specific markers to detect in the token stream.
302    pub tool_call_format: ToolCallFormat,
303    /// True while buffering inside a tool call block.
304    in_tool_call: bool,
305    /// Accumulated bytes inside the current tool call block.
306    tool_call_buf: String,
307    /// Number of tool calls dispatched but not yet resolved.
308    #[cfg(not(target_os = "wasi"))]
309    pub pending_tool_calls: usize,
310    /// Spinner frame index — incremented each tick while tool calls are in flight.
311    pub spinner_tick: u32,
312
313    // ── VFS namespace for / command routing ──────────────────────────────────
314    /// VFS namespace for / path commands. None on WASM.
315    vfs: Option<std::sync::Arc<hyprstream_vfs::Namespace>>,
316    /// Caller identity for VFS operations.
317    vfs_subject: hyprstream_vfs::Subject,
318    /// Tcl shell owner for `/` command evaluation. Created lazily on first use
319    /// (see [`ensure_tcl_shell`](Self::ensure_tcl_shell)) because `TclShell` is
320    /// `!Send` (molt `Value` uses `Rc`) and ChatApp is moved across threads in
321    /// `spawn_app_process` — so the shell cannot be constructed until ChatApp has
322    /// settled on its final thread. The init data (subject + namespace) IS Send
323    /// and crosses the thread boundary fine; only the live shell cannot.
324    ///
325    /// The `TclShell` is never touched outside the dedicated owner thread that
326    /// [`shell_driver::ShellOwner`] spawns for it — there is no unsafe Send bypass
327    /// because the shell never crosses a thread boundary at all.
328    #[cfg(not(target_os = "wasi"))]
329    tcl_owner: Option<crate::shell_driver::ShellOwner>,
330    /// Deferred init data for the Tcl shell owner (Send-safe). Consumed on first
331    /// access by [`ensure_tcl_shell`](Self::ensure_tcl_shell).
332    tcl_shell_init: Option<(
333        hyprstream_vfs::Subject,
334        std::sync::Arc<hyprstream_vfs::Namespace>,
335    )>,
336    /// Dedicated-thread driver for direct `Namespace` access (`cat`/`ls`), used
337    /// by bare-path slash commands that don't need a Tcl interpreter at all. See
338    /// [`ensure_ns_driver`](Self::ensure_ns_driver) and the routing split in
339    /// [`handle_vfs_command`](Self::handle_vfs_command).
340    #[cfg(not(target_os = "wasi"))]
341    ns_driver: Option<crate::shell_driver::NamespaceDriver>,
342}
343
344// ============================================================================
345// Slash-command routing: decouple simple VFS access from Tcl
346// ============================================================================
347
348/// Classification of a `/`-prefixed command, used to decide whether it can be
349/// served directly from the `Namespace` (no Tcl interpreter involved) or needs
350/// genuine Tcl script evaluation.
351///
352/// This is the decoupling #611 asks for: slash-command routing no longer
353/// assumes Tcl is the only way to reach the VFS. Only commands that are
354/// literally "read a file" or "list a directory" — the two cases the old
355/// bare-path heuristic already special-cased — bypass Tcl; anything with
356/// Tcl-shaped syntax (multiple words, braces, `$vars`, `[brackets]`, other
357/// builtins like `write`/`ctl`/`mount`/`help`, or unrecognized commands) still
358/// goes through the interpreter exactly as before.
359#[cfg(not(target_os = "wasi"))]
360#[derive(Debug)]
361enum VfsCommandClass {
362    /// Bare path (`/srv/model/status`) or explicit `cat <path>` with exactly one
363    /// argument and no Tcl metacharacters in it.
364    Cat(String),
365    /// `ls` or `ls <path>` with at most one argument and no Tcl metacharacters.
366    Ls(Option<String>),
367    /// Anything else — evaluate as Tcl.
368    Eval(String),
369}
370
371/// True if `s` contains characters that would change meaning under Tcl
372/// evaluation (substitution, grouping, command nesting) or any whitespace.
373///
374/// Direct-path arguments containing any of these fall through to `eval` so they
375/// get exactly the semantics they had before this routing split. The Tcl
376/// metacharacters (`$ [ ] { } " ; \`) cover substitution/grouping/command-
377/// nesting. The whitespace check keeps a bare-path fast-path argument
378/// byte-faithful to "literally `cat <this exact string>`": the old bare-path
379/// heuristic built `cat {input}` and let the molt tokenizer split it, so a path
380/// containing e.g. a newline would have been command-split by the interpreter
381/// rather than read as one opaque filename — routing such inputs through Tcl
382/// preserves that. (The VFS resolver returns `NotFound` for whitespace-bearing
383/// paths regardless; all path-safety/authorization lives inside
384/// `Namespace::cat`/`ls`, which the Tcl `cmd_cat`/`cmd_ls` builtins call
385/// unchanged — so this is a faithfulness guard, not a security fix.)
386#[cfg(not(target_os = "wasi"))]
387fn has_tcl_metachars(s: &str) -> bool {
388    s.contains(['$', '[', ']', '{', '}', '"', ';', '\\']) || s.contains(char::is_whitespace)
389}
390
391/// Classify a stripped (no leading `/`) slash-command body for direct-VFS vs.
392/// Tcl-eval routing. `leading_slash_path` mirrors the original bare-path
393/// heuristic in `handle_vfs_command`: a single word containing `/` with no
394/// space (e.g. `srv/model/status`, from input `/srv/model/status`).
395#[cfg(not(target_os = "wasi"))]
396fn classify_vfs_command(stripped: &str, leading_slash_path: bool) -> VfsCommandClass {
397    if leading_slash_path {
398        return if has_tcl_metachars(stripped) {
399            VfsCommandClass::Eval(stripped.to_owned())
400        } else {
401            VfsCommandClass::Cat(format!("/{stripped}"))
402        };
403    }
404
405    let mut parts = stripped.split_whitespace();
406    let Some(cmd) = parts.next() else {
407        return VfsCommandClass::Eval(stripped.to_owned());
408    };
409    let rest: Vec<&str> = parts.collect();
410
411    match cmd {
412        "cat" if rest.len() == 1 && !has_tcl_metachars(rest[0]) => {
413            VfsCommandClass::Cat(rest[0].to_owned())
414        }
415        "ls" if rest.is_empty() => VfsCommandClass::Ls(None),
416        "ls" if rest.len() == 1 && !has_tcl_metachars(rest[0]) => {
417            VfsCommandClass::Ls(Some(rest[0].to_owned()))
418        }
419        _ => VfsCommandClass::Eval(stripped.to_owned()),
420    }
421}
422
423impl ChatApp {
424    #[cfg(not(target_os = "wasi"))]
425    pub fn new(model_name: String, cols: u16, rows: u16, spawner: StreamSpawner) -> Self {
426        let (event_tx, event_rx) = mpsc::sync_channel::<ChatEvent>(256);
427        Self {
428            model_name,
429            history: Vec::new(),
430            textarea: Self::make_textarea(),
431            mode: ChatMode::Input,
432            editor_text: String::new(),
433            scroll_offset: 0,
434            status: None,
435            event_rx,
436            event_tx,
437            spawner,
438            cols,
439            rows,
440            quit: false,
441            session_id: None,
442            save_hook: None,
443            in_thinking: false,
444            show_thinking: false,
445            pending_toasts: Vec::new(),
446            cancel_handle: None,
447            pending_prompts: VecDeque::new(),
448            last_esc: None,
449            gen_config: Arc::new(parking_lot::RwLock::new(ChatGenConfig::default())),
450            settings_draft: ChatGenConfig::default(),
451            requested_context_window: None,
452            is_server_spawned: false,
453            tool_caller: None,
454            tool_descriptions: HashMap::new(),
455            tool_call_format: ToolCallFormat::None,
456            in_tool_call: false,
457            tool_call_buf: String::new(),
458            pending_tool_calls: 0,
459            spinner_tick: 0,
460            vfs: None,
461            vfs_subject: hyprstream_vfs::Subject::anonymous(),
462            tcl_owner: None,
463            tcl_shell_init: None,
464            ns_driver: None,
465        }
466    }
467
468    /// Create a WASM-compatible ChatApp (no StreamSpawner, push-based events).
469    #[cfg(target_os = "wasi")]
470    pub fn new_wasm(model_name: String, cols: u16, rows: u16) -> Self {
471        Self {
472            model_name,
473            history: Vec::new(),
474            input_buf: String::new(),
475            mode: ChatMode::Input,
476            scroll_offset: 0,
477            status: None,
478            cols,
479            rows,
480            quit: false,
481            session_id: None,
482            save_hook: None,
483            in_thinking: false,
484            show_thinking: false,
485            pending_toasts: Vec::new(),
486            pending_prompts: VecDeque::new(),
487            tool_descriptions: HashMap::new(),
488            tool_call_format: ToolCallFormat::None,
489            in_tool_call: false,
490            tool_call_buf: String::new(),
491            spinner_tick: 0,
492            vfs: None,
493            vfs_subject: hyprstream_vfs::Subject::anonymous(),
494            tcl_shell_init: None,
495        }
496    }
497
498    #[cfg(not(target_os = "wasi"))]
499    fn make_textarea() -> TextArea<'static> {
500        use ratatui::style::{Color, Style};
501        let mut ta = TextArea::default();
502        ta.set_block(hyprstream_compositor::theme::input_block());
503        ta.set_line_number_style(hyprstream_compositor::theme::gutter_style());
504        ta.set_cursor_line_style(
505            Style::default()
506                .bg(hyprstream_compositor::theme::BG)
507                .fg(Color::White),
508        );
509        ta.set_style(
510            Style::default()
511                .bg(hyprstream_compositor::theme::BG)
512                .fg(Color::White),
513        );
514        ta.set_placeholder_text("Type a message…");
515        ta
516    }
517
518    /// Create a private chat app with encrypted history persistence.
519    ///
520    /// `load_hook` is called immediately to restore any prior conversation.
521    /// `save_hook` is called after each `StreamComplete` to persist history.
522    #[cfg(not(target_os = "wasi"))]
523    pub fn new_private(
524        model_name: String,
525        cols: u16,
526        rows: u16,
527        spawner: StreamSpawner,
528        session_id: Uuid,
529        load_hook: LoadHook,
530        save_hook: SaveHook,
531    ) -> Self {
532        let (event_tx, event_rx) = mpsc::sync_channel::<ChatEvent>(256);
533        let mut history = load_hook().unwrap_or_default();
534        // Clean up tool call records whose result is None — these survive
535        // serialization when the session crashes mid-execution.
536        for entry in history.iter_mut() {
537            for tc in entry.tool_calls.iter_mut() {
538                if tc.result.is_none() {
539                    tc.result = Some("[interrupted]".to_owned());
540                }
541            }
542        }
543        Self {
544            model_name,
545            history,
546            textarea: Self::make_textarea(),
547            mode: ChatMode::Input,
548            editor_text: String::new(),
549            scroll_offset: 0,
550            status: None,
551            event_rx,
552            event_tx,
553            spawner,
554            cols,
555            rows,
556            quit: false,
557            session_id: Some(session_id),
558            save_hook: Some(save_hook),
559            in_thinking: false,
560            show_thinking: false,
561            pending_toasts: Vec::new(),
562            cancel_handle: None,
563            pending_prompts: VecDeque::new(),
564            last_esc: None,
565            gen_config: Arc::new(parking_lot::RwLock::new(ChatGenConfig::default())),
566            settings_draft: ChatGenConfig::default(),
567            requested_context_window: None,
568            is_server_spawned: false,
569            tool_caller: None,
570            tool_descriptions: HashMap::new(),
571            tool_call_format: ToolCallFormat::None,
572            in_tool_call: false,
573            tool_call_buf: String::new(),
574            pending_tool_calls: 0,
575            spinner_tick: 0,
576            vfs: None,
577            vfs_subject: hyprstream_vfs::Subject::anonymous(),
578            tcl_owner: None,
579            tcl_shell_init: None,
580            ns_driver: None,
581        }
582    }
583
584    /// Replace the default gen_config with a pre-created Arc (to share with the spawner).
585    #[cfg(not(target_os = "wasi"))]
586    pub fn with_gen_config(mut self, gen_config: Arc<parking_lot::RwLock<ChatGenConfig>>) -> Self {
587        self.gen_config = gen_config;
588        self
589    }
590
591    /// Mark this ChatApp as server-spawned (hosted inside TuiService).
592    ///
593    /// When true, context window changes from the Settings modal push a toast
594    /// with CLI instructions rather than triggering an automatic model reload.
595    #[cfg(not(target_os = "wasi"))]
596    pub fn with_server_spawned(mut self) -> Self {
597        self.is_server_spawned = true;
598        self
599    }
600
601    /// Attach a VFS namespace for `/path` command routing.
602    ///
603    /// The Tcl shell owner thread and the direct-`Namespace` driver thread (see
604    /// `crate::shell_driver`) are both created lazily on first use, because
605    /// `TclShell` is `!Send` and ChatApp must cross a thread boundary in
606    /// `spawn_app_process` before it can settle on the thread its owner will
607    /// spawn from.
608    pub fn with_vfs(
609        mut self,
610        ns: std::sync::Arc<hyprstream_vfs::Namespace>,
611        subject: hyprstream_vfs::Subject,
612    ) -> Self {
613        self.tcl_shell_init = Some((subject.clone(), std::sync::Arc::clone(&ns)));
614        self.vfs = Some(ns);
615        self.vfs_subject = subject;
616        self
617    }
618
619    /// Attach VFS namespace for `/path` command routing (compat shim).
620    ///
621    /// The `_vfs_tx` parameter is ignored — TclShell now awaits namespace
622    /// operations directly. This method exists for call-site compatibility;
623    /// prefer `with_vfs` for new code.
624    pub fn with_vfs_proxy(
625        mut self,
626        ns: std::sync::Arc<hyprstream_vfs::Namespace>,
627        subject: hyprstream_vfs::Subject,
628        _vfs_tx: tokio::sync::mpsc::Sender<hyprstream_vfs::proxy::VfsRequest>,
629    ) -> Self {
630        self.tcl_shell_init = Some((subject.clone(), std::sync::Arc::clone(&ns)));
631        self.vfs = Some(ns);
632        self.vfs_subject = subject;
633        self
634    }
635
636    /// Configure tool calling.  Call after construction if the MCP service is available.
637    ///
638    /// `tool_caller` executes a tool by UUID and sends `ToolCallResult` back.
639    /// `tool_descriptions` maps UUID → human label for display purposes.
640    /// `format` selects the model-specific tool call syntax.
641    #[cfg(not(target_os = "wasi"))]
642    pub fn with_tool_caller(
643        mut self,
644        tool_caller: ToolCaller,
645        tool_descriptions: HashMap<String, String>,
646        tool_call_format: ToolCallFormat,
647    ) -> Self {
648        self.tool_caller = Some(tool_caller);
649        self.tool_descriptions = tool_descriptions;
650        self.tool_call_format = tool_call_format;
651        self
652    }
653
654    // ── Settings helpers ──────────────────────────────────────────────────────
655
656    /// Adjust a single settings field in `settings_draft` by `delta` steps.
657    ///
658    /// Field indices:
659    /// 0 = max_tokens  (step 64, range 64–32768)
660    /// 1 = temperature (step 0.05, range 0.0–2.0)
661    /// 2 = top_p       (step 0.05, range 0.05–1.0)
662    /// 3 = top_k       (step 1, range None/off or 1–200)
663    /// 4 = context_window (step 512, range None/"model default" or 512–131072)
664    #[cfg(not(target_os = "wasi"))]
665    fn apply_settings_field_delta(&mut self, field: usize, delta: i32) {
666        match field {
667            0 => {
668                let v = self.settings_draft.max_tokens as i32 + delta * 64;
669                self.settings_draft.max_tokens = v.clamp(64, 32768) as usize;
670            }
671            1 => {
672                let v = self.settings_draft.temperature + delta as f32 * 0.05;
673                let rounded = (v.clamp(0.0, 2.0) * 100.0).round() / 100.0;
674                self.settings_draft.temperature = rounded;
675            }
676            2 => {
677                let v = self.settings_draft.top_p + delta as f32 * 0.05;
678                let rounded = (v.clamp(0.05, 1.0) * 100.0).round() / 100.0;
679                self.settings_draft.top_p = rounded;
680            }
681            3 => match self.settings_draft.top_k {
682                None if delta > 0 => self.settings_draft.top_k = Some(1),
683                Some(1) if delta < 0 => self.settings_draft.top_k = None,
684                Some(v) => {
685                    self.settings_draft.top_k = Some((v as i32 + delta).clamp(1, 200) as usize);
686                }
687                _ => {}
688            },
689            4 => match self.settings_draft.context_window {
690                None if delta > 0 => self.settings_draft.context_window = Some(512),
691                Some(512) if delta < 0 => self.settings_draft.context_window = None,
692                Some(v) => {
693                    self.settings_draft.context_window =
694                        Some((v as i32 + delta * 512).clamp(512, 131072) as usize);
695                }
696                _ => {}
697            },
698            _ => {}
699        }
700    }
701
702    // ── Tool call state machine helpers ──────────────────────────────────────
703
704    /// Parse the buffered tool call content and return `(function_name, arguments_json)`.
705    ///
706    /// Tries JSON first (Hermes/nous format), then falls back to the Qwen3.5
707    /// XML parameter format (`<function=NAME><parameter=KEY>value</parameter></function>`).
708    fn parse_tool_call_buf(buf: &str) -> Option<(String, String)> {
709        let trimmed = buf.trim();
710
711        // Try JSON format first (Qwen3/Hermes: {"name": ..., "arguments": ...})
712        if let Ok(call_data) = serde_json::from_str::<serde_json::Value>(trimmed) {
713            let name = call_data["name"].as_str()?.to_owned();
714            let arguments = serde_json::to_string(&call_data["arguments"]).ok()?;
715            return Some((name, arguments));
716        }
717
718        // Fall back to Qwen3.5 XML parameter format:
719        //   <function=get_weather>
720        //   <parameter=location>NYC</parameter>
721        //   </function>
722        if trimmed.contains("<function=") {
723            return Self::parse_xml_param_tool_call(trimmed);
724        }
725
726        None
727    }
728
729    /// Parse a single Qwen3.5 XML parameter-format tool call block.
730    fn parse_xml_param_tool_call(buf: &str) -> Option<(String, String)> {
731        // Extract function name from <function=NAME>
732        let func_start = buf.find("<function=")?;
733        let name_start = func_start + "<function=".len();
734        let name_end = buf[name_start..].find('>')? + name_start;
735        let name = buf[name_start..name_end].trim().to_owned();
736        if name.is_empty() {
737            return None;
738        }
739
740        // Extract the body between <function=NAME> and </function>
741        let body_start = name_end + 1;
742        let body_end = buf.find("</function>").unwrap_or(buf.len());
743        let body = &buf[body_start..body_end];
744
745        // Extract <parameter=KEY>VALUE</parameter> pairs
746        let mut args = serde_json::Map::new();
747        let mut search_from = 0;
748        while let Some(param_start) = body[search_from..].find("<parameter=") {
749            let abs_start = search_from + param_start;
750            let key_start = abs_start + "<parameter=".len();
751            let key_end = match body[key_start..].find('>') {
752                Some(p) => key_start + p,
753                None => break,
754            };
755            let key = body[key_start..key_end].trim().to_owned();
756
757            let value_start = key_end + 1;
758            let value_end = match body[value_start..].find("</parameter>") {
759                Some(p) => value_start + p,
760                None => break,
761            };
762            let value = body[value_start..value_end].trim();
763
764            if !key.is_empty() {
765                // Try JSON parse for numbers/bools/objects, fall back to string
766                let json_val = serde_json::from_str::<serde_json::Value>(value)
767                    .unwrap_or_else(|_| serde_json::Value::String(value.to_owned()));
768                args.insert(key, json_val);
769            }
770
771            search_from = value_end + "</parameter>".len();
772        }
773
774        let arguments = serde_json::to_string(&serde_json::Value::Object(args)).ok()?;
775        Some((name, arguments))
776    }
777
778    // ── ingest_token ─────────────────────────────────────────────────────────
779
780    /// Route a streamed token into the correct buffer.
781    ///
782    /// Handles `<think>`/`</think>` and (when configured) tool-call markers.
783    /// Returns a list of `(uuid, arguments_json)` for any complete tool call
784    /// blocks that were just closed.  Callers are responsible for emitting
785    /// `ChatEvent::ToolCallDetected` and firing the cancel handle.
786    fn ingest_token(&mut self, token: &str) -> Vec<(String, String)> {
787        let mut detected: Vec<(String, String)> = Vec::new();
788
789        // Cache format-derived markers before mutably borrowing history.
790        let open_marker: Option<(&'static str, &'static str)> = match self.tool_call_format {
791            ToolCallFormat::Qwen3Xml => Some(("<tool_call>", "</tool_call>")),
792            ToolCallFormat::Qwen35XmlParam => Some(("<tool_call>", "</tool_call>")),
793            ToolCallFormat::LlamaJson => Some(("<|python_tag|>", "")),
794            ToolCallFormat::MistralJson => Some(("[TOOL_CALLS]", "")),
795            ToolCallFormat::None => None,
796        };
797
798        let Some(last) = self.history.last_mut() else {
799            return detected;
800        };
801        let mut remaining = token;
802
803        while !remaining.is_empty() {
804            if self.in_thinking {
805                if let Some(end) = remaining.find("</think>") {
806                    last.thinking.push_str(&remaining[..end]);
807                    self.in_thinking = false;
808                    remaining = &remaining[end + "</think>".len()..];
809                } else {
810                    last.thinking.push_str(remaining);
811                    break;
812                }
813            } else if self.in_tool_call {
814                let close = open_marker.map(|(_, c)| c).unwrap_or("");
815                if close.is_empty() {
816                    // Llama/Mistral: no closing tag — buffer everything.
817                    self.tool_call_buf.push_str(remaining);
818                    break;
819                }
820                if let Some(end) = remaining.find(close) {
821                    self.tool_call_buf.push_str(&remaining[..end]);
822                    remaining = &remaining[end + close.len()..];
823                    self.in_tool_call = false;
824                    let buf = std::mem::take(&mut self.tool_call_buf);
825                    if let Some(pair) = Self::parse_tool_call_buf(&buf) {
826                        detected.push(pair);
827                    }
828                } else {
829                    self.tool_call_buf.push_str(remaining);
830                    break;
831                }
832            } else if let Some((open, _)) = open_marker {
833                if let Some(start) = remaining.find(open) {
834                    last.content.push_str(&remaining[..start]);
835                    self.in_tool_call = true;
836                    self.tool_call_buf.clear();
837                    remaining = &remaining[start + open.len()..];
838                } else if let Some(start) = remaining.find("<think>") {
839                    last.content.push_str(&remaining[..start]);
840                    self.in_thinking = true;
841                    remaining = &remaining[start + "<think>".len()..];
842                } else {
843                    last.content.push_str(remaining);
844                    break;
845                }
846            } else if let Some(start) = remaining.find("<think>") {
847                last.content.push_str(&remaining[..start]);
848                self.in_thinking = true;
849                remaining = &remaining[start + "<think>".len()..];
850            } else {
851                last.content.push_str(remaining);
852                break;
853            }
854        }
855
856        detected
857    }
858
859    // ── VFS helpers ──────────────────────────────────────────────────────────
860
861    /// Display a system-level message in the chat history (VFS output, errors).
862    fn push_system_message(&mut self, msg: &str) {
863        self.history.push(ChatHistoryEntry {
864            role: ChatRole::Assistant,
865            content: msg.to_owned(),
866            thinking: String::new(),
867            tool_calls: Vec::new(),
868            tool_call_id: None,
869        });
870        self.scroll_offset = 0;
871    }
872
873    /// Lazily spawn the Tcl shell owner thread. Must be called from the app
874    /// thread (after the ChatApp has been moved into `spawn_app_process`) so
875    /// `tcl_shell_init`'s `Subject`/`Arc<Namespace>` (both `Send`) can cross into
876    /// the dedicated owner thread that [`shell_driver::ShellOwner::spawn`]
877    /// creates — the live `TclShell` itself never crosses any thread boundary.
878    ///
879    /// The owner services the synchronous slash-command `eval()` path only;
880    /// `/lang/tcl` VFS traffic is served by the self-contained `TclMount` in the
881    /// namespace, not by ChatApp.
882    #[cfg(not(target_os = "wasi"))]
883    fn ensure_tcl_shell(&mut self) {
884        if self.tcl_owner.is_none() {
885            if let Some((subject, namespace)) = self.tcl_shell_init.take() {
886                self.tcl_owner = Some(crate::shell_driver::ShellOwner::spawn(subject, namespace));
887            }
888        }
889    }
890
891    /// No-op on WASI: there is no dedicated-thread shell owner there (no VFS,
892    /// no `/`-command routing — see `new_wasm`, which never calls `with_vfs`).
893    #[cfg(target_os = "wasi")]
894    fn ensure_tcl_shell(&mut self) {}
895
896    /// Lazily spawn the direct-`Namespace` driver thread used for bare
897    /// cat/ls-shaped `/`-commands that don't need a Tcl interpreter at all.
898    #[cfg(not(target_os = "wasi"))]
899    fn ensure_ns_driver(&mut self) {
900        if self.ns_driver.is_none() {
901            if let Some(ns) = &self.vfs {
902                self.ns_driver = Some(crate::shell_driver::NamespaceDriver::spawn(
903                    self.vfs_subject.clone(),
904                    std::sync::Arc::clone(ns),
905                ));
906            }
907        }
908    }
909
910    /// Handle a `/`-prefixed command.
911    ///
912    /// Bare paths (e.g. `/srv/model/status`) and simple `cat`/`ls` invocations
913    /// are served directly from the `Namespace` via
914    /// [`NamespaceDriver`](crate::shell_driver::NamespaceDriver) — no Tcl
915    /// interpreter is constructed or consulted for these. Anything else (e.g.
916    /// `/write`, `/ctl`, `/mount`, `/help`, or genuine Tcl syntax with
917    /// `$vars`/`[brackets]`/etc.) still evaluates through `TclShell` via
918    /// [`ShellOwner`](crate::shell_driver::ShellOwner), exactly as before — this
919    /// is a routing refactor, not a behavior change for those paths.
920    #[cfg(not(target_os = "wasi"))]
921    fn handle_vfs_command(&mut self, input: &str) {
922        if self.vfs.is_none() {
923            self.push_system_message("VFS not available");
924            return;
925        }
926
927        // Show the command in history.
928        self.history.push(ChatHistoryEntry {
929            role: ChatRole::User,
930            content: input.to_owned(),
931            thinking: String::new(),
932            tool_calls: Vec::new(),
933            tool_call_id: None,
934        });
935
936        // Strip leading '/' and decide: bare path vs command, mirroring the
937        // original heuristic exactly (single word containing '/' with no space
938        // = bare path), before sub-classifying for direct-vs-Tcl routing.
939        let stripped = input.trim_start_matches('/');
940        let leading_slash_path = !stripped.contains(' ') && stripped.contains('/');
941
942        let class = classify_vfs_command(stripped, leading_slash_path);
943
944        let result = match class {
945            VfsCommandClass::Cat(path) => {
946                self.ensure_ns_driver();
947                match &self.ns_driver {
948                    Some(driver) => driver.cat(&path),
949                    None => Err("VFS not available".to_owned()),
950                }
951            }
952            VfsCommandClass::Ls(path) => {
953                self.ensure_ns_driver();
954                match &self.ns_driver {
955                    Some(driver) => driver.ls(path.as_deref().unwrap_or("/")),
956                    None => Err("VFS not available".to_owned()),
957                }
958            }
959            VfsCommandClass::Eval(script) => {
960                self.ensure_tcl_shell();
961                match &self.tcl_owner {
962                    Some(owner) => owner.eval(&script),
963                    None => Err("VFS not available".to_owned()),
964                }
965            }
966        };
967
968        match result {
969            Ok(output) if !output.is_empty() => {
970                self.push_system_message(&output);
971            }
972            Ok(_) => {} // Empty output — nothing to display.
973            Err(e) => {
974                self.push_system_message(&format!("error: {e}"));
975            }
976        }
977    }
978
979    /// No-op on WASI: `/`-command routing requires a VFS namespace, which is
980    /// never attached there (see `new_wasm`).
981    #[cfg(target_os = "wasi")]
982    fn handle_vfs_command(&mut self, _input: &str) {
983        self.push_system_message("VFS not available");
984    }
985
986    // ── Submit helpers ────────────────────────────────────────────────────────
987
988    /// Build history pairs (role, content) for the model, appending a new user
989    /// message, and fire the spawner.  Stores the returned `CancelHandle`.
990    #[cfg(not(target_os = "wasi"))]
991    fn submit_message(&mut self, user_text: String) {
992        self.history.push(ChatHistoryEntry {
993            role: ChatRole::User,
994            content: user_text,
995            thinking: String::new(),
996            tool_calls: Vec::new(),
997            tool_call_id: None,
998        });
999        self.start_generation();
1000    }
1001
1002    /// Push an empty assistant placeholder and start the spawner.
1003    ///
1004    /// Used by both `submit_message` (first turn) and `restart_generation`
1005    /// (agentic re-invoke after tool results).
1006    #[cfg(not(target_os = "wasi"))]
1007    fn start_generation(&mut self) {
1008        self.history.push(ChatHistoryEntry {
1009            role: ChatRole::Assistant,
1010            content: String::new(),
1011            thinking: String::new(),
1012            tool_calls: Vec::new(),
1013            tool_call_id: None,
1014        });
1015
1016        let handle = (self.spawner)(self.history.clone(), self.event_tx.clone());
1017        self.cancel_handle = Some(handle);
1018        self.mode = ChatMode::Streaming;
1019        self.status = Some("Generating\u{2026}".to_owned());
1020        self.scroll_offset = 0;
1021        self.in_thinking = false;
1022        self.in_tool_call = false;
1023        self.tool_call_buf.clear();
1024    }
1025
1026    /// Signal the current stream to cancel.
1027    #[cfg(not(target_os = "wasi"))]
1028    fn cancel_stream(&mut self) {
1029        if let Some(cancel) = self.cancel_handle.take() {
1030            cancel();
1031        }
1032        self.status = Some("Cancelling\u{2026}".to_owned());
1033    }
1034
1035    /// Called on StreamComplete / StreamCancelled from user action (not tool
1036    /// cancellation): persist, then drain the pending queue if any prompts
1037    /// were typed while we were streaming.
1038    fn on_stream_done(&mut self) {
1039        #[cfg(not(target_os = "wasi"))]
1040        {
1041            self.cancel_handle = None;
1042        }
1043        self.in_thinking = false;
1044        self.in_tool_call = false;
1045        self.tool_call_buf.clear();
1046        if let Some(_next_text) = self.pending_prompts.pop_front() {
1047            #[cfg(not(target_os = "wasi"))]
1048            self.submit_message(_next_text);
1049        } else {
1050            self.mode = ChatMode::Input;
1051            self.status = None;
1052        }
1053    }
1054
1055    // ====================================================================
1056    // Push-based event methods (for WASM and direct callers)
1057    // ====================================================================
1058
1059    /// Ingest a streamed token from an external event source.
1060    pub fn on_token(&mut self, token: &str) {
1061        let detected = self.ingest_token(token);
1062        #[cfg(not(target_os = "wasi"))]
1063        for (uuid, arguments) in detected {
1064            let description = self
1065                .tool_descriptions
1066                .get(&uuid)
1067                .cloned()
1068                .unwrap_or_else(|| uuid.clone());
1069            // Generate a unique correlation ID per invocation so two calls to the
1070            // same tool function can be distinguished in ToolCallResult matching.
1071            let id = Uuid::new_v4().to_string();
1072            // Enqueue the event BEFORE cancelling.  The cancel handle is fired
1073            // in tick() when ToolCallDetected is dequeued, which guarantees that
1074            // StreamCancelled (sent by the spawner thread after it sees the cancel
1075            // signal) cannot arrive before ToolCallDetected in the event channel.
1076            let _ = self.event_tx.send(ChatEvent::ToolCallDetected {
1077                id,
1078                uuid,
1079                description,
1080                arguments,
1081            });
1082        }
1083    }
1084
1085    /// Signal that the inference stream completed successfully.
1086    pub fn on_stream_complete(&mut self) {
1087        #[cfg(not(target_os = "wasi"))]
1088        {
1089            // Always persist — Tool messages are already in history at this point.
1090            if let Some(ref hook) = self.save_hook {
1091                hook(&self.history);
1092            }
1093            if self.pending_tool_calls > 0 {
1094                // Mid-agentic loop: generation ended (naturally or before the cancel
1095                // signal arrived).  Don't drain the prompt queue or transition to Input
1096                // mode — ToolCallResult will re-invoke the spawner when all results arrive.
1097                self.cancel_handle = None;
1098                self.in_thinking = false;
1099                self.in_tool_call = false;
1100                self.tool_call_buf.clear();
1101                return;
1102            }
1103        }
1104        #[cfg(target_os = "wasi")]
1105        {
1106            if let Some(ref hook) = self.save_hook {
1107                hook(&self.history);
1108            }
1109        }
1110        self.on_stream_done();
1111    }
1112
1113    /// Signal that the inference stream was cancelled.
1114    pub fn on_stream_cancelled(&mut self) {
1115        #[cfg(not(target_os = "wasi"))]
1116        {
1117            // If we cancelled because of a tool call, don't reset mode — the
1118            // agentic dispatch in tick() will re-invoke the spawner.
1119            if self.pending_tool_calls > 0 {
1120                self.cancel_handle = None;
1121                self.in_thinking = false;
1122                self.in_tool_call = false;
1123                self.tool_call_buf.clear();
1124                return;
1125            }
1126        }
1127        self.on_stream_done();
1128    }
1129
1130    /// Signal an inference error.
1131    pub fn on_stream_error(&mut self, msg: String) {
1132        self.pending_toasts.push(format!("Inference error: {msg}"));
1133        if let Some(last) = self.history.last_mut() {
1134            last.content = format!("[Error: {msg}]");
1135        }
1136        #[cfg(not(target_os = "wasi"))]
1137        {
1138            self.cancel_handle = None;
1139        }
1140        self.in_thinking = false;
1141        self.in_tool_call = false;
1142        self.tool_call_buf.clear();
1143        #[cfg(not(target_os = "wasi"))]
1144        {
1145            if self.pending_tool_calls > 0 {
1146                // Tool executor threads may still be running; discard queued prompts
1147                // to avoid starting a new generation against a corrupt history state.
1148                self.pending_prompts.clear();
1149            }
1150            self.pending_tool_calls = 0;
1151        }
1152        self.on_stream_done();
1153    }
1154
1155    /// Signal a template application error.
1156    pub fn on_template_error(&mut self, msg: String) {
1157        // The last entry is always the empty assistant placeholder pushed by
1158        // start_generation().  Pop only that entry to preserve any Tool messages
1159        // from a preceding agentic round (so context is intact on retry).
1160        // Fall back to popping until User if the history shape is unexpected.
1161        let tail_is_empty_assistant = self
1162            .history
1163            .last()
1164            .map(|e| {
1165                matches!(e.role, ChatRole::Assistant)
1166                    && e.content.is_empty()
1167                    && e.tool_calls.is_empty()
1168            })
1169            .unwrap_or(false);
1170        if tail_is_empty_assistant {
1171            self.history.pop();
1172        } else {
1173            while let Some(entry) = self.history.pop() {
1174                if matches!(entry.role, ChatRole::User) {
1175                    // Put the user message back — we only want to remove
1176                    // assistant/tool entries, not the user's input.
1177                    self.history.push(entry);
1178                    break;
1179                }
1180            }
1181        }
1182        self.pending_toasts.push(format!("Model error: {msg}"));
1183        #[cfg(not(target_os = "wasi"))]
1184        {
1185            self.cancel_handle = None;
1186            self.pending_tool_calls = 0;
1187        }
1188        self.in_thinking = false;
1189        self.in_tool_call = false;
1190        self.tool_call_buf.clear();
1191        self.mode = ChatMode::Input;
1192        self.status = Some(msg);
1193    }
1194
1195    /// Build the inference request payload as a JSON string (for WASM OSC output).
1196    pub fn submit_message_payload(&mut self, user_text: String) -> String {
1197        self.history.push(ChatHistoryEntry {
1198            role: ChatRole::User,
1199            content: user_text,
1200            thinking: String::new(),
1201            tool_calls: Vec::new(),
1202            tool_call_id: None,
1203        });
1204        self.history.push(ChatHistoryEntry {
1205            role: ChatRole::Assistant,
1206            content: String::new(),
1207            thinking: String::new(),
1208            tool_calls: Vec::new(),
1209            tool_call_id: None,
1210        });
1211        self.mode = ChatMode::Streaming;
1212        self.status = Some("Generating\u{2026}".to_owned());
1213        self.scroll_offset = 0;
1214        self.in_thinking = false;
1215
1216        let messages: Vec<serde_json::Value> = self
1217            .history
1218            .iter()
1219            .filter(|e| !e.content.is_empty())
1220            .map(|e| {
1221                let role = match e.role {
1222                    ChatRole::User => "user",
1223                    ChatRole::Assistant => "assistant",
1224                    ChatRole::Tool => "tool",
1225                };
1226                serde_json::json!({ "role": role, "content": e.content })
1227            })
1228            .collect();
1229
1230        serde_json::json!({
1231            "model": self.model_name,
1232            "messages": messages,
1233            "stream": true,
1234        })
1235        .to_string()
1236    }
1237
1238    /// Handle a keyboard key in WASM mode.
1239    #[cfg(target_os = "wasi")]
1240    pub fn handle_key(&mut self, key: KeyPress) -> Option<String> {
1241        if matches!(self.mode, ChatMode::Streaming) {
1242            match key {
1243                KeyPress::Escape | KeyPress::F(10) => {
1244                    self.quit = true;
1245                }
1246                _ => {}
1247            }
1248            return None;
1249        }
1250
1251        match key {
1252            KeyPress::Escape | KeyPress::F(10) => {
1253                self.quit = true;
1254                None
1255            }
1256            KeyPress::Enter => {
1257                if self.input_buf.is_empty() {
1258                    return None;
1259                }
1260                let user_msg = std::mem::take(&mut self.input_buf);
1261                Some(self.submit_message_payload(user_msg))
1262            }
1263            KeyPress::Backspace => {
1264                self.input_buf.pop();
1265                None
1266            }
1267            KeyPress::Char(b) if b.is_ascii_graphic() || b == b' ' => {
1268                self.input_buf.push(b as char);
1269                None
1270            }
1271            KeyPress::ArrowUp => {
1272                self.scroll_offset = self.scroll_offset.saturating_add(1);
1273                None
1274            }
1275            KeyPress::ArrowDown => {
1276                self.scroll_offset = self.scroll_offset.saturating_sub(1);
1277                None
1278            }
1279            _ => None,
1280        }
1281    }
1282}
1283
1284// ============================================================================
1285// TerminalApp impl (native only)
1286// ============================================================================
1287
1288#[cfg(not(target_os = "wasi"))]
1289impl TerminalApp for ChatApp {
1290    type Command = KeyPress;
1291
1292    fn render(&self, frame: &mut ratatui::Frame) {
1293        crate::chat_ui::draw(frame, self);
1294    }
1295
1296    fn handle_input(&mut self, key: KeyPress) -> bool {
1297        // Ctrl-O toggles thinking visibility in all modes.
1298        if matches!(key, KeyPress::Char(0x0F)) {
1299            self.show_thinking = !self.show_thinking;
1300            return true;
1301        }
1302
1303        match self.mode {
1304            // ── Input mode ──────────────────────────────────────────────────
1305            ChatMode::Input => match key {
1306                KeyPress::Escape => {
1307                    // No-op. Use Ctrl+Space → Q to close via compositor menu.
1308                    false
1309                }
1310                KeyPress::Char(0x05) => {
1311                    self.editor_text = self.textarea.lines().join("\n");
1312                    self.mode = ChatMode::Editor;
1313                    true
1314                }
1315                KeyPress::Enter => {
1316                    let user_content = self.textarea.lines().join("\n");
1317                    let user_content = user_content.trim().to_owned();
1318                    if user_content.is_empty() {
1319                        return false;
1320                    }
1321                    self.textarea = Self::make_textarea();
1322                    self.last_esc = None;
1323
1324                    // VFS path routing: /path → cat from namespace.
1325                    if user_content.starts_with('/') && !user_content.starts_with("//") {
1326                        self.handle_vfs_command(&user_content);
1327                        return true;
1328                    }
1329
1330                    // Escape: // → / (send to model with leading slash).
1331                    let content = if let Some(stripped) = user_content.strip_prefix("//") {
1332                        format!("/{stripped}")
1333                    } else {
1334                        user_content
1335                    };
1336
1337                    self.submit_message(content);
1338                    true
1339                }
1340                KeyPress::Backspace => {
1341                    self.textarea.delete_char();
1342                    true
1343                }
1344                KeyPress::Char(b) => {
1345                    if b.is_ascii_graphic() || b == b' ' {
1346                        self.textarea.insert_char(b as char);
1347                        true
1348                    } else if b == 0x0A {
1349                        self.textarea.insert_newline();
1350                        true
1351                    } else {
1352                        false
1353                    }
1354                }
1355                KeyPress::ArrowLeft => {
1356                    self.textarea
1357                        .move_cursor(ratatui_textarea::CursorMove::Back);
1358                    true
1359                }
1360                KeyPress::ArrowRight => {
1361                    self.textarea
1362                        .move_cursor(ratatui_textarea::CursorMove::Forward);
1363                    true
1364                }
1365                KeyPress::ArrowUp | KeyPress::ScrollUp => {
1366                    self.scroll_offset =
1367                        self.scroll_offset
1368                            .saturating_add(if matches!(key, KeyPress::ScrollUp) {
1369                                3
1370                            } else {
1371                                1
1372                            });
1373                    true
1374                }
1375                KeyPress::ArrowDown | KeyPress::ScrollDown => {
1376                    self.scroll_offset =
1377                        self.scroll_offset
1378                            .saturating_sub(if matches!(key, KeyPress::ScrollDown) {
1379                                3
1380                            } else {
1381                                1
1382                            });
1383                    true
1384                }
1385                _ => false,
1386            },
1387
1388            // ── Streaming mode — allow typing + queueing ─────────────────────
1389            ChatMode::Streaming => match key {
1390                KeyPress::Escape => {
1391                    // Don't attempt to cancel when tool executor threads are running —
1392                    // cancel_handle is already consumed and there's no way to abort them.
1393                    // The Esc hint is hidden from the fkey bar in this state.
1394                    if self.pending_tool_calls == 0 {
1395                        self.cancel_stream();
1396                    }
1397                    true
1398                }
1399                KeyPress::F(10) => {
1400                    self.quit = true;
1401                    true
1402                }
1403                KeyPress::Enter => {
1404                    let user_content = self.textarea.lines().join("\n");
1405                    let user_content = user_content.trim().to_owned();
1406                    if user_content.is_empty() {
1407                        return false;
1408                    }
1409                    self.textarea = Self::make_textarea();
1410                    self.pending_prompts.push_back(user_content);
1411                    true
1412                }
1413                KeyPress::Backspace => {
1414                    self.textarea.delete_char();
1415                    true
1416                }
1417                KeyPress::Char(b) => {
1418                    if b.is_ascii_graphic() || b == b' ' {
1419                        self.textarea.insert_char(b as char);
1420                        true
1421                    } else if b == 0x0A {
1422                        self.textarea.insert_newline();
1423                        true
1424                    } else {
1425                        false
1426                    }
1427                }
1428                KeyPress::ArrowLeft => {
1429                    self.textarea
1430                        .move_cursor(ratatui_textarea::CursorMove::Back);
1431                    true
1432                }
1433                KeyPress::ArrowRight => {
1434                    self.textarea
1435                        .move_cursor(ratatui_textarea::CursorMove::Forward);
1436                    true
1437                }
1438                KeyPress::ArrowUp | KeyPress::ScrollUp => {
1439                    self.scroll_offset =
1440                        self.scroll_offset
1441                            .saturating_add(if matches!(key, KeyPress::ScrollUp) {
1442                                3
1443                            } else {
1444                                1
1445                            });
1446                    true
1447                }
1448                KeyPress::ArrowDown | KeyPress::ScrollDown => {
1449                    self.scroll_offset =
1450                        self.scroll_offset
1451                            .saturating_sub(if matches!(key, KeyPress::ScrollDown) {
1452                                3
1453                            } else {
1454                                1
1455                            });
1456                    true
1457                }
1458                _ => false,
1459            },
1460
1461            // ── Settings mode ─────────────────────────────────────────────────
1462            ChatMode::Settings { selected_field } => match key {
1463                KeyPress::Escape => {
1464                    self.mode = ChatMode::Input;
1465                    true
1466                }
1467                KeyPress::Enter => {
1468                    let draft = self.settings_draft.clone();
1469                    let old_context = self.gen_config.read().context_window;
1470                    *self.gen_config.write() = draft.clone();
1471                    if draft.context_window != old_context {
1472                        if self.is_server_spawned {
1473                            let ctx_str = draft
1474                                .context_window
1475                                .map_or("default".to_owned(), |n| n.to_string());
1476                            self.pending_toasts.push(format!(
1477                                "Context window set to {ctx_str}. Reload model to apply: \
1478                                 hyprstream quick load {} --max-context {ctx_str}",
1479                                self.model_name,
1480                            ));
1481                        } else {
1482                            // Shell_handlers will reload the model on the next bg_tick.
1483                            self.requested_context_window = Some(draft.context_window.unwrap_or(0));
1484                        }
1485                    }
1486                    self.mode = ChatMode::Input;
1487                    true
1488                }
1489                KeyPress::ArrowUp => {
1490                    if selected_field > 0 {
1491                        self.mode = ChatMode::Settings {
1492                            selected_field: selected_field - 1,
1493                        };
1494                    }
1495                    true
1496                }
1497                KeyPress::ArrowDown => {
1498                    if selected_field < 4 {
1499                        self.mode = ChatMode::Settings {
1500                            selected_field: selected_field + 1,
1501                        };
1502                    }
1503                    true
1504                }
1505                KeyPress::ArrowLeft => {
1506                    self.apply_settings_field_delta(selected_field, -1);
1507                    true
1508                }
1509                KeyPress::ArrowRight => {
1510                    self.apply_settings_field_delta(selected_field, 1);
1511                    true
1512                }
1513                _ => false,
1514            },
1515
1516            // ── Editor mode ──────────────────────────────────────────────────
1517            ChatMode::Editor => match key {
1518                KeyPress::Escape => {
1519                    self.editor_text = String::new();
1520                    self.mode = ChatMode::Input;
1521                    true
1522                }
1523                KeyPress::Char(0x13) => {
1524                    let content = crate::chat_ui::take_editor_text();
1525                    self.textarea = Self::make_textarea();
1526                    for (i, line) in content.lines().enumerate() {
1527                        if i > 0 {
1528                            self.textarea.insert_newline();
1529                        }
1530                        for ch in line.chars() {
1531                            self.textarea.insert_char(ch);
1532                        }
1533                    }
1534                    self.editor_text = String::new();
1535                    self.mode = ChatMode::Input;
1536                    true
1537                }
1538                _ => {
1539                    if let Some(crossterm_key) = keypress_to_crossterm(key) {
1540                        crate::chat_ui::EDITOR_STATE.with(|cell| {
1541                            if let Some(ref mut state) = *cell.borrow_mut() {
1542                                edtui::EditorEventHandler::default()
1543                                    .on_key_event(crossterm_key, state);
1544                            }
1545                        });
1546                        true
1547                    } else {
1548                        false
1549                    }
1550                }
1551            },
1552        }
1553    }
1554
1555    fn tick(&mut self, _delta_ms: u64) -> bool {
1556        // Clear the single-Esc hint if it's been sitting long enough.
1557        if let Some(prev) = self.last_esc {
1558            if prev.elapsed().as_millis() >= DOUBLE_ESC_MS {
1559                self.last_esc = None;
1560                if self.status.as_deref() == Some("Press Esc again to close") {
1561                    self.status = None;
1562                }
1563            }
1564        }
1565
1566        let mut redraw = false;
1567
1568        // Advance spinner while tool calls are in flight.
1569        if self.pending_tool_calls > 0 {
1570            self.spinner_tick = self.spinner_tick.wrapping_add(1);
1571            redraw = true;
1572        }
1573
1574        loop {
1575            match self.event_rx.try_recv() {
1576                Ok(ChatEvent::Token(s)) => {
1577                    self.on_token(&s);
1578                    redraw = true;
1579                }
1580                Ok(ChatEvent::StreamComplete) => {
1581                    self.on_stream_complete();
1582                    redraw = true;
1583                }
1584                Ok(ChatEvent::StreamCancelled) => {
1585                    self.on_stream_cancelled();
1586                    redraw = true;
1587                }
1588                Ok(ChatEvent::StreamError(s)) => {
1589                    self.on_stream_error(s);
1590                    redraw = true;
1591                }
1592                Ok(ChatEvent::TemplateError(s)) => {
1593                    self.on_template_error(s);
1594                    redraw = true;
1595                }
1596                Ok(ChatEvent::ToolCallDetected {
1597                    id,
1598                    uuid,
1599                    description,
1600                    arguments,
1601                }) => {
1602                    // Security: only dispatch tools present in the allowlist fetched
1603                    // from list_tools().  Models cannot invoke arbitrary endpoints.
1604                    let allowed =
1605                        self.tool_caller.is_none() || self.tool_descriptions.contains_key(&uuid);
1606
1607                    // Record the tool call on the last assistant entry.
1608                    if let Some(last) = self.history.last_mut() {
1609                        last.tool_calls.push(ToolCallRecord {
1610                            id: id.clone(),
1611                            uuid: uuid.clone(),
1612                            description: description.clone(),
1613                            arguments: arguments.clone(),
1614                            result: if allowed {
1615                                None
1616                            } else {
1617                                Some(format!("[Tool not found: {uuid}]"))
1618                            },
1619                        });
1620                    }
1621                    self.pending_tool_calls += 1;
1622
1623                    // Cancel the stream NOW — after ToolCallDetected is already
1624                    // dequeued from the channel.  This guarantees that StreamCancelled
1625                    // (sent by the spawner on the other side of the oneshot) arrives
1626                    // AFTER this event, never before it.
1627                    if let Some(cancel) = self.cancel_handle.take() {
1628                        cancel();
1629                    }
1630
1631                    if !allowed {
1632                        // Unknown UUID — send error result immediately so the loop completes.
1633                        let _ = self.event_tx.send(ChatEvent::ToolCallResult {
1634                            id,
1635                            uuid,
1636                            result: "[Tool not found]".to_string(),
1637                        });
1638                    } else if let Some(ref caller) = self.tool_caller {
1639                        // Dispatch to the tool executor.
1640                        let caller_arc = Arc::clone(caller);
1641                        let tx = self.event_tx.clone();
1642                        let id_c = id.clone();
1643                        let uuid_c = uuid.clone();
1644                        let args_c = arguments.clone();
1645                        std::thread::spawn(move || {
1646                            caller_arc(id_c, uuid_c, args_c, tx);
1647                        });
1648                    } else {
1649                        // No MCP client — emit error result immediately.
1650                        let _ = self.event_tx.send(ChatEvent::ToolCallResult {
1651                            id,
1652                            uuid,
1653                            result: "[Tool calling not available]".to_owned(),
1654                        });
1655                    }
1656                    redraw = true;
1657                }
1658                Ok(ChatEvent::ToolCallResult {
1659                    id,
1660                    uuid: _,
1661                    result,
1662                }) => {
1663                    // Guard: ignore stale/duplicate results (e.g. after on_stream_error
1664                    // reset pending_tool_calls to 0, or a duplicate delivery).
1665                    if self.pending_tool_calls == 0 {
1666                        redraw = true;
1667                        continue;
1668                    }
1669
1670                    // Fill in the result on the matching ToolCallRecord by correlation ID.
1671                    for entry in self.history.iter_mut() {
1672                        for tc in entry.tool_calls.iter_mut() {
1673                            if tc.id == id {
1674                                tc.result = Some(result.clone());
1675                                break;
1676                            }
1677                        }
1678                    }
1679
1680                    // Sanitize tool result: strip tool-call markers so a compromised
1681                    // MCP service cannot inject fake tool calls into the next turn.
1682                    let sanitized_result = result
1683                        .replace("<tool_call>", "")
1684                        .replace("</tool_call>", "")
1685                        .replace("<|python_tag|>", "")
1686                        .replace("[TOOL_CALLS]", "");
1687
1688                    // Inject a Tool message into history.  `tool_call_id` must match
1689                    // `ToolCall.id` in the preceding assistant message — both use the
1690                    // per-invocation correlation ID, not the tool-name UUID.
1691                    self.history.push(ChatHistoryEntry {
1692                        role: ChatRole::Tool,
1693                        content: sanitized_result,
1694                        thinking: String::new(),
1695                        tool_calls: Vec::new(),
1696                        tool_call_id: Some(id),
1697                    });
1698
1699                    // Snap scroll to bottom so the newly-arrived result is visible.
1700                    self.scroll_offset = 0;
1701
1702                    self.pending_tool_calls -= 1;
1703
1704                    // When all pending tool calls are resolved, re-invoke the spawner.
1705                    if self.pending_tool_calls == 0 {
1706                        self.start_generation();
1707                    }
1708                    redraw = true;
1709                }
1710                Err(mpsc::TryRecvError::Empty) => break,
1711                Err(mpsc::TryRecvError::Disconnected) => {
1712                    if matches!(self.mode, ChatMode::Streaming) {
1713                        self.cancel_handle = None;
1714                        self.in_thinking = false;
1715                        self.in_tool_call = false;
1716                        self.tool_call_buf.clear();
1717                        self.pending_tool_calls = 0;
1718                        self.on_stream_done();
1719                        redraw = true;
1720                    }
1721                    break;
1722                }
1723            }
1724        }
1725        redraw
1726    }
1727
1728    fn should_quit(&self) -> bool {
1729        self.quit
1730    }
1731}
1732
1733#[cfg(all(test, not(target_os = "wasi")))]
1734mod tests {
1735    use super::{classify_vfs_command, has_tcl_metachars, VfsCommandClass};
1736
1737    /// A bare path (single word containing `/`) with no metacharacters routes to
1738    /// a direct `Namespace::cat` of the leading-`/`-prefixed path — matching the
1739    /// old `format!("cat {input}")` behavior exactly.
1740    #[test]
1741    fn bare_path_routes_to_direct_cat() {
1742        let class = classify_vfs_command("srv/model/status", true);
1743        assert!(matches!(class, VfsCommandClass::Cat(p) if p == "/srv/model/status"));
1744    }
1745
1746    /// A bare path containing any Tcl metacharacter falls through to Tcl `eval`
1747    /// so the interpreter's substitution/grouping semantics are preserved.
1748    #[test]
1749    fn bare_path_with_metachar_routes_to_eval() {
1750        for bad in [
1751            "srv/$x",
1752            "srv/[a]",
1753            "srv/{b}",
1754            "srv/\"q\"",
1755            "srv;c",
1756            "srv\\d",
1757        ] {
1758            let class = classify_vfs_command(bad, true);
1759            assert!(
1760                matches!(class, VfsCommandClass::Eval(ref s) if s == bad),
1761                "bare path {bad:?} should fall through to Eval, got {class:?}"
1762            );
1763        }
1764    }
1765
1766    /// A bare path containing whitespace (space/tab/newline) also falls through
1767    /// to Tcl: the old heuristic built `cat {input}` and let molt tokenize it, so
1768    /// e.g. a newline would have been command-split. See `has_tcl_metachars`.
1769    #[test]
1770    fn bare_path_with_whitespace_routes_to_eval() {
1771        for bad in ["srv/x\t", "srv\ny/z", "srv\r/z"] {
1772            // `leading_slash_path` is computed by the caller from "no space AND
1773            // contains '/'"; a tab/newline is not a space so the caller would
1774            // still set it true — the classifier must then reject via the
1775            // whitespace arm of has_tcl_metachars.
1776            let class = classify_vfs_command(bad, true);
1777            assert!(
1778                matches!(class, VfsCommandClass::Eval(ref s) if s == bad),
1779                "bare path {bad:?} should fall through to Eval, got {class:?}"
1780            );
1781        }
1782    }
1783
1784    /// `cat <path>` with exactly one metachar-free argument routes to direct cat.
1785    #[test]
1786    fn explicit_cat_routes_to_direct_cat() {
1787        let class = classify_vfs_command("cat /srv/model/status", false);
1788        assert!(matches!(class, VfsCommandClass::Cat(p) if p == "/srv/model/status"));
1789    }
1790
1791    /// `cat` with zero, two, or metachar-bearing arguments falls through to Tcl.
1792    #[test]
1793    fn cat_wrong_arity_or_meta_routes_to_eval() {
1794        assert!(matches!(
1795            classify_vfs_command("cat", false),
1796            VfsCommandClass::Eval(_)
1797        ));
1798        assert!(matches!(
1799            classify_vfs_command("cat a b", false),
1800            VfsCommandClass::Eval(_)
1801        ));
1802        assert!(matches!(
1803            classify_vfs_command("cat $x", false),
1804            VfsCommandClass::Eval(_)
1805        ));
1806    }
1807
1808    /// `ls` and `ls <path>` route to direct ls.
1809    #[test]
1810    fn ls_routes_to_direct_ls() {
1811        assert!(matches!(
1812            classify_vfs_command("ls", false),
1813            VfsCommandClass::Ls(None)
1814        ));
1815        assert!(matches!(
1816            classify_vfs_command("ls /srv", false),
1817            VfsCommandClass::Ls(Some(p)) if p == "/srv"
1818        ));
1819    }
1820
1821    /// Everything that isn't a bare path or simple cat/ls — write/ctl/mount/help,
1822    /// unknown commands, empty input — falls through to Tcl `eval` unchanged.
1823    #[test]
1824    fn non_direct_commands_route_to_eval() {
1825        for input in [
1826            "write /x y",
1827            "ctl /svc start",
1828            "mount foo",
1829            "help",
1830            "frobnicate",
1831            "",
1832        ] {
1833            assert!(
1834                matches!(classify_vfs_command(input, false), VfsCommandClass::Eval(s) if s == input),
1835                "input {input:?} should Eval unchanged"
1836            );
1837        }
1838    }
1839
1840    /// `has_tcl_metachars` is the security-relevant gate: it must reject every
1841    /// character that would change meaning under Tcl evaluation, plus whitespace.
1842    #[test]
1843    fn metachar_detection_is_complete() {
1844        // Each Tcl-significant character, in an otherwise-inert string.
1845        for c in [
1846            '$', '[', ']', '{', '}', '"', ';', '\\', ' ', '\t', '\n', '\r',
1847        ] {
1848            assert!(has_tcl_metachars(&format!("x{c}y")), "failed to flag {c:?}");
1849        }
1850        // A plain path is clean.
1851        assert!(!has_tcl_metachars("/srv/model/status"));
1852        assert!(!has_tcl_metachars("bin/foo-bar_2.txt"));
1853    }
1854}