1use 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), 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 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#[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 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#[derive(Clone, Copy, PartialEq, Eq, Default)]
92pub enum ToolCallFormat {
93 Qwen3Xml,
95 Qwen35XmlParam,
98 LlamaJson,
100 MistralJson,
102 #[default]
104 None,
105}
106
107#[cfg(not(target_os = "wasi"))]
109pub enum ChatEvent {
110 Token(String),
111 StreamComplete,
112 StreamCancelled,
114 StreamError(String),
115 TemplateError(String),
116 ToolCallDetected {
118 id: String,
120 uuid: String,
121 description: String,
122 arguments: String,
123 },
124 ToolCallResult {
126 id: String,
128 uuid: String,
129 result: String,
130 },
131}
132
133#[derive(Serialize, Deserialize, Clone)]
135pub enum ChatRole {
136 User,
137 Assistant,
138 Tool,
140}
141
142#[derive(Serialize, Deserialize, Clone)]
144pub struct ToolCallRecord {
145 #[serde(default)]
148 pub id: String,
149 pub uuid: String,
151 pub description: String,
153 pub arguments: String,
155 pub result: Option<String>,
157}
158
159#[derive(Serialize, Deserialize, Clone)]
161pub struct ChatHistoryEntry {
162 pub role: ChatRole,
163 pub content: String,
165 #[serde(default)]
167 pub thinking: String,
168 #[serde(default)]
170 pub tool_calls: Vec<ToolCallRecord>,
171 #[serde(default)]
173 pub tool_call_id: Option<String>,
174}
175
176#[cfg(not(target_os = "wasi"))]
179pub type CancelHandle = Box<dyn FnOnce() + Send + 'static>;
180
181#[cfg(not(target_os = "wasi"))]
189pub type StreamSpawner = Box<
190 dyn Fn(Vec<ChatHistoryEntry>, mpsc::SyncSender<ChatEvent>) -> CancelHandle + Send + 'static,
191>;
192
193#[cfg(not(target_os = "wasi"))]
200pub type ToolCaller =
201 Arc<dyn Fn(String, String, String, mpsc::SyncSender<ChatEvent>) + Send + Sync + 'static>;
202
203pub type SaveHook = Box<dyn Fn(&[ChatHistoryEntry]) + Send + 'static>;
205
206pub type LoadHook = Box<dyn FnOnce() -> Option<Vec<ChatHistoryEntry>> + Send + 'static>;
209
210pub enum ChatMode {
215 Input,
216 Streaming,
217 #[cfg(not(target_os = "wasi"))]
218 Editor,
219 #[cfg(not(target_os = "wasi"))]
221 Settings {
222 selected_field: usize,
223 },
224}
225
226#[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 #[cfg(target_os = "wasi")]
241 pub input_buf: String,
242 pub mode: ChatMode,
243 #[cfg(not(target_os = "wasi"))]
245 pub editor_text: String,
246 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 pub session_id: Option<Uuid>,
260 save_hook: Option<SaveHook>,
262 in_thinking: bool,
264 pub show_thinking: bool,
266 pub pending_toasts: Vec<String>,
269 #[cfg(not(target_os = "wasi"))]
271 cancel_handle: Option<CancelHandle>,
272 pub pending_prompts: VecDeque<String>,
274 #[cfg(not(target_os = "wasi"))]
276 last_esc: Option<Instant>,
277
278 #[cfg(not(target_os = "wasi"))]
281 pub gen_config: Arc<parking_lot::RwLock<ChatGenConfig>>,
282 #[cfg(not(target_os = "wasi"))]
284 pub settings_draft: ChatGenConfig,
285 #[cfg(not(target_os = "wasi"))]
288 pub requested_context_window: Option<usize>,
289 #[cfg(not(target_os = "wasi"))]
293 pub is_server_spawned: bool,
294
295 #[cfg(not(target_os = "wasi"))]
298 tool_caller: Option<ToolCaller>,
299 pub tool_descriptions: HashMap<String, String>,
301 pub tool_call_format: ToolCallFormat,
303 in_tool_call: bool,
305 tool_call_buf: String,
307 #[cfg(not(target_os = "wasi"))]
309 pub pending_tool_calls: usize,
310 pub spinner_tick: u32,
312
313 vfs: Option<std::sync::Arc<hyprstream_vfs::Namespace>>,
316 vfs_subject: hyprstream_vfs::Subject,
318 #[cfg(not(target_os = "wasi"))]
329 tcl_owner: Option<crate::shell_driver::ShellOwner>,
330 tcl_shell_init: Option<(
333 hyprstream_vfs::Subject,
334 std::sync::Arc<hyprstream_vfs::Namespace>,
335 )>,
336 #[cfg(not(target_os = "wasi"))]
341 ns_driver: Option<crate::shell_driver::NamespaceDriver>,
342}
343
344#[cfg(not(target_os = "wasi"))]
360#[derive(Debug)]
361enum VfsCommandClass {
362 Cat(String),
365 Ls(Option<String>),
367 Eval(String),
369}
370
371#[cfg(not(target_os = "wasi"))]
387fn has_tcl_metachars(s: &str) -> bool {
388 s.contains(['$', '[', ']', '{', '}', '"', ';', '\\']) || s.contains(char::is_whitespace)
389}
390
391#[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 #[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 #[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 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 #[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 #[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 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 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 #[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 #[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 fn parse_tool_call_buf(buf: &str) -> Option<(String, String)> {
709 let trimmed = buf.trim();
710
711 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 if trimmed.contains("<function=") {
723 return Self::parse_xml_param_tool_call(trimmed);
724 }
725
726 None
727 }
728
729 fn parse_xml_param_tool_call(buf: &str) -> Option<(String, String)> {
731 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 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 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 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 fn ingest_token(&mut self, token: &str) -> Vec<(String, String)> {
787 let mut detected: Vec<(String, String)> = Vec::new();
788
789 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 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 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 #[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 #[cfg(target_os = "wasi")]
894 fn ensure_tcl_shell(&mut self) {}
895
896 #[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 #[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 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 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(_) => {} Err(e) => {
974 self.push_system_message(&format!("error: {e}"));
975 }
976 }
977 }
978
979 #[cfg(target_os = "wasi")]
982 fn handle_vfs_command(&mut self, _input: &str) {
983 self.push_system_message("VFS not available");
984 }
985
986 #[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 #[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 #[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 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 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 let id = Uuid::new_v4().to_string();
1072 let _ = self.event_tx.send(ChatEvent::ToolCallDetected {
1077 id,
1078 uuid,
1079 description,
1080 arguments,
1081 });
1082 }
1083 }
1084
1085 pub fn on_stream_complete(&mut self) {
1087 #[cfg(not(target_os = "wasi"))]
1088 {
1089 if let Some(ref hook) = self.save_hook {
1091 hook(&self.history);
1092 }
1093 if self.pending_tool_calls > 0 {
1094 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 pub fn on_stream_cancelled(&mut self) {
1115 #[cfg(not(target_os = "wasi"))]
1116 {
1117 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 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 self.pending_prompts.clear();
1149 }
1150 self.pending_tool_calls = 0;
1151 }
1152 self.on_stream_done();
1153 }
1154
1155 pub fn on_template_error(&mut self, msg: String) {
1157 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 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 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 #[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#[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 if matches!(key, KeyPress::Char(0x0F)) {
1299 self.show_thinking = !self.show_thinking;
1300 return true;
1301 }
1302
1303 match self.mode {
1304 ChatMode::Input => match key {
1306 KeyPress::Escape => {
1307 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 if user_content.starts_with('/') && !user_content.starts_with("//") {
1326 self.handle_vfs_command(&user_content);
1327 return true;
1328 }
1329
1330 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 ChatMode::Streaming => match key {
1390 KeyPress::Escape => {
1391 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 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 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 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 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 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 let allowed =
1605 self.tool_caller.is_none() || self.tool_descriptions.contains_key(&uuid);
1606
1607 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 if let Some(cancel) = self.cancel_handle.take() {
1628 cancel();
1629 }
1630
1631 if !allowed {
1632 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 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 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 if self.pending_tool_calls == 0 {
1666 redraw = true;
1667 continue;
1668 }
1669
1670 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 let sanitized_result = result
1683 .replace("<tool_call>", "")
1684 .replace("</tool_call>", "")
1685 .replace("<|python_tag|>", "")
1686 .replace("[TOOL_CALLS]", "");
1687
1688 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 self.scroll_offset = 0;
1701
1702 self.pending_tool_calls -= 1;
1703
1704 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 #[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 #[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 #[test]
1770 fn bare_path_with_whitespace_routes_to_eval() {
1771 for bad in ["srv/x\t", "srv\ny/z", "srv\r/z"] {
1772 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 #[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 #[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 #[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 #[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 #[test]
1843 fn metachar_detection_is_complete() {
1844 for c in [
1846 '$', '[', ']', '{', '}', '"', ';', '\\', ' ', '\t', '\n', '\r',
1847 ] {
1848 assert!(has_tcl_metachars(&format!("x{c}y")), "failed to flag {c:?}");
1849 }
1850 assert!(!has_tcl_metachars("/srv/model/status"));
1852 assert!(!has_tcl_metachars("bin/foo-bar_2.txt"));
1853 }
1854}