Skip to main content

stynx_code_tui/state/
app_state.rs

1use stynx_code_types::EngineEvent;
2use super::{ConversationState, DiffLine, DiffLineKind, DisplayMessage, DisplayToolUse, InputState, ModalState, ToastState, ToolUseStatus};
3
4#[derive(Clone)]
5pub struct SessionSummary {
6    pub id: String,
7    pub title: String,
8    pub updated_at: u64,
9    pub pinned: bool,
10}
11
12pub struct SidebarState {
13    pub visible: bool,
14    pub title: String,
15    pub session_id: String,
16    pub version: String,
17    pub sessions: Vec<SessionSummary>,
18}
19
20impl SidebarState {
21    pub fn new() -> Self {
22        Self {
23            visible: true,
24            title: "New session".to_string(),
25            session_id: String::new(),
26            version: env!("CARGO_PKG_VERSION").to_string(),
27            sessions: Vec::new(),
28        }
29    }
30}
31
32impl Default for SidebarState {
33    fn default() -> Self { Self::new() }
34}
35
36pub struct AppState {
37    pub input: InputState,
38    pub conversation: ConversationState,
39    pub modal: ModalState,
40    pub sidebar: SidebarState,
41    pub toasts: ToastState,
42    pub model_name: String,
43    pub permission_mode: String,
44    pub total_cost: f64,
45    pub git_branch: Option<String>,
46    pub cwd: String,
47    pub is_streaming: bool,
48    pub spinner_frame: usize,
49    pub spinner_tick: u8,
50    pub total_input: u64,
51    pub total_output: u64,
52    pub recent_models: Vec<String>,
53    pub tool_details: bool,
54    /// Live thinking text for the in-flight turn. Rendered in a dedicated
55    /// panel just above the input; archived into the last assistant message
56    /// once the turn completes.
57    pub live_thinking: String,
58}
59
60impl AppState {
61    pub fn push_recent_model(&mut self, id: &str) {
62        self.recent_models.retain(|m| m != id);
63        self.recent_models.insert(0, id.to_string());
64        if self.recent_models.len() > 8 {
65            self.recent_models.truncate(8);
66        }
67    }
68
69    pub fn cycle_recent_model(&mut self) -> Option<String> {
70        if self.recent_models.len() < 2 {
71            return None;
72        }
73        let next = self.recent_models.remove(1);
74        self.recent_models.insert(0, next.clone());
75        Some(next)
76    }
77}
78
79impl AppState {
80    pub fn new() -> Self {
81        Self {
82            input: InputState::new(),
83            conversation: ConversationState::new(),
84            modal: ModalState::new(),
85            sidebar: SidebarState::new(),
86            toasts: ToastState::new(),
87            model_name: String::from("claude-sonnet-4-20250514"),
88            permission_mode: String::from("Normal"),
89            total_cost: 0.0,
90            git_branch: None,
91            cwd: std::env::current_dir().ok()
92                .and_then(|p| p.to_str().map(|s| s.to_string()))
93                .unwrap_or_default(),
94            is_streaming: false,
95            spinner_frame: 0,
96            spinner_tick: 0,
97            total_input: 0,
98            total_output: 0,
99            recent_models: Vec::new(),
100            tool_details: true,
101            live_thinking: String::new(),
102        }
103    }
104
105    pub fn push_user_message(&mut self, text: impl Into<String>) {
106        self.conversation.messages.push(DisplayMessage {
107            role: "user".to_string(),
108            content: text.into(),
109            thinking: String::new(),
110            tool_uses: Vec::new(),
111            is_streaming: false,
112        });
113        self.conversation.auto_scroll = true;
114    }
115
116    pub fn push_system_message(&mut self, text: impl Into<String>) {
117        self.conversation.messages.push(DisplayMessage {
118            role: "system".to_string(),
119            content: text.into(),
120            thinking: String::new(),
121            tool_uses: Vec::new(),
122            is_streaming: false,
123        });
124        self.conversation.auto_scroll = true;
125    }
126
127    pub fn apply_engine_event(&mut self, event: EngineEvent) {
128        match event {
129            EngineEvent::TextDelta(text) => {
130                self.is_streaming = true;
131                match self.conversation.messages.last_mut() {
132                    Some(m) if m.role == "assistant" && m.is_streaming => m.content.push_str(&text),
133                    _ => self.conversation.messages.push(DisplayMessage {
134                        role: "assistant".to_string(), content: text,
135                        thinking: String::new(), tool_uses: Vec::new(), is_streaming: true,
136                    }),
137                }
138            }
139            EngineEvent::ThinkingDelta(text) => {
140                self.is_streaming = true;
141                self.live_thinking.push_str(&text);
142            }
143            EngineEvent::ToolStart { name, .. } => {
144                self.is_streaming = true;
145                let tool = DisplayToolUse {
146                    name,
147                    status: ToolUseStatus::Running,
148                    output_preview: String::new(),
149                    input_json: String::new(),
150                    input_summary: String::new(),
151                    output_excerpt: Vec::new(),
152                    diff: Vec::new(),
153                };
154                match self.conversation.messages.last_mut().filter(|m| m.role == "assistant") {
155                    Some(m) => m.tool_uses.push(tool),
156                    None => self.conversation.messages.push(DisplayMessage {
157                        role: "assistant".to_string(), content: String::new(),
158                        thinking: String::new(), tool_uses: vec![tool], is_streaming: true,
159                    }),
160                }
161            }
162            EngineEvent::ToolInput { json_chunk } => {
163                if let Some(m) = self.conversation.messages.last_mut() {
164                    if let Some(t) = m.tool_uses.iter_mut().rev()
165                        .find(|t| t.status == ToolUseStatus::Running)
166                    {
167                        t.input_json.push_str(&json_chunk);
168                        t.input_summary = summarize_tool_input(&t.name, &t.input_json);
169                    }
170                }
171            }
172            EngineEvent::ToolResult { name, output, is_error } => {
173                let clean_output = crate::util::strip_ansi(&output);
174                let preview_limit = if is_error { 400 } else { 80 };
175                if let Some(m) = self.conversation.messages.last_mut() {
176                    if let Some(t) = m.tool_uses.iter_mut().rev()
177                        .find(|t| t.name == name && t.status == ToolUseStatus::Running) {
178                        t.status = if is_error { ToolUseStatus::Error } else { ToolUseStatus::Completed };
179                        t.output_preview = clean_output.lines().next().unwrap_or("").chars().take(preview_limit).collect();
180                        if t.input_summary.is_empty() {
181                            t.input_summary = summarize_tool_input(&t.name, &t.input_json);
182                        }
183                        t.output_excerpt = excerpt_lines(&clean_output, 6, 200);
184                        if t.name == "file_edit" || t.name == "file_write" {
185                            t.diff = build_diff_for(&t.name, &t.input_json);
186                        }
187                        // Append line-count badge to read/grep/glob/bash summary
188                        // so the user can see how much came back without
189                        // dumping the body.
190                        if matches!(t.name.as_str(), "read" | "grep" | "glob") && !is_error {
191                            let n = clean_output.lines().filter(|l| !l.trim().is_empty()).count();
192                            if n > 0 && !t.input_summary.contains("(")  {
193                                t.input_summary = format!("{}  ({n} lines)", t.input_summary);
194                            }
195                        }
196                    }
197                }
198                if is_error {
199                    self.conversation.messages.push(DisplayMessage {
200                        role: "error".to_string(),
201                        content: format!("{name}: {clean_output}"),
202                        thinking: String::new(),
203                        tool_uses: Vec::new(),
204                        is_streaming: false,
205                    });
206                    tracing::error!(tool = %name, output = %clean_output, "tool returned error");
207                }
208            }
209            EngineEvent::TurnComplete => {
210                self.is_streaming = false;
211                let tool_summary = self.conversation.messages.last().and_then(|m| {
212                    if m.role != "assistant" { return None; }
213                    if m.tool_uses.is_empty() { return None; }
214                    let parts: Vec<String> = m.tool_uses.iter().map(|t| {
215                        let pretty = match t.name.as_str() {
216                            "bash" => "Bash".into(),
217                            "read" => "Read".into(),
218                            "file_write" => "Write".into(),
219                            "file_edit" => "Edit".into(),
220                            "glob" => "Glob".into(),
221                            "grep" => "Grep".into(),
222                            "web_fetch" => "WebFetch".into(),
223                            "web_search" => "WebSearch".into(),
224                            "todo_write" => "TodoWrite".into(),
225                            "todo_read" => "TodoRead".into(),
226                            "ask_user_question" => "AskUser".into(),
227                            "agent" => "Agent".into(),
228                            other => {
229                                let mut s = other.replace('_', " ");
230                                s = s.split_whitespace()
231                                    .map(|w| { let mut c = w.chars(); c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default() })
232                                    .collect::<Vec<_>>().join("");
233                                s
234                            }
235                        };
236                        if t.input_summary.is_empty() {
237                            pretty
238                        } else {
239                            format!("{}({})", pretty, t.input_summary)
240                        }
241                    }).collect();
242                    Some(parts.join(", "))
243                });
244                if let Some(m) = self.conversation.messages.last_mut() {
245                    m.is_streaming = false;
246                    if !self.live_thinking.is_empty() && m.role == "assistant" {
247                        if m.thinking.is_empty() {
248                            m.thinking = std::mem::take(&mut self.live_thinking);
249                        } else {
250                            m.thinking.push_str(&self.live_thinking);
251                            self.live_thinking.clear();
252                        }
253                    }
254                }
255                self.live_thinking.clear();
256                if let Some(summary) = tool_summary {
257                    self.conversation.messages.push(DisplayMessage {
258                        role: "done".to_string(),
259                        content: summary,
260                        thinking: String::new(),
261                        tool_uses: Vec::new(),
262                        is_streaming: false,
263                    });
264                    self.conversation.auto_scroll = true;
265                }
266            }
267            EngineEvent::Usage { input_tokens, output_tokens } => {
268                if input_tokens > 0 { self.total_input += input_tokens; }
269                if output_tokens > 0 { self.total_output += output_tokens; }
270                self.total_cost = (self.total_input as f64 * 3.0 + self.total_output as f64 * 15.0) / 1_000_000.0;
271            }
272            EngineEvent::Error(e) => {
273                self.is_streaming = false;
274                self.conversation.messages.push(DisplayMessage {
275                    role: "error".to_string(), content: e,
276                    thinking: String::new(), tool_uses: Vec::new(), is_streaming: false,
277                });
278            }
279            EngineEvent::ModeChanged { mode } => {
280                self.permission_mode = mode.label().to_string();
281            }
282            _ => {}
283        }
284    }
285}
286
287impl Default for AppState {
288    fn default() -> Self { Self::new() }
289}
290
291fn try_parse(json: &str) -> Option<serde_json::Value> {
292    if json.trim().is_empty() { return None; }
293    serde_json::from_str(json).ok()
294}
295
296fn shorten(s: &str, max: usize) -> String {
297    let trimmed = s.trim();
298    if trimmed.chars().count() <= max {
299        return trimmed.to_string();
300    }
301    let mut out: String = trimmed.chars().take(max.saturating_sub(1)).collect();
302    out.push('…');
303    out
304}
305
306fn first_line(s: &str) -> &str {
307    s.lines().next().unwrap_or("")
308}
309
310pub fn summarize_tool_input(tool: &str, json: &str) -> String {
311    let parsed = try_parse(json);
312    let get = |k: &str| -> String {
313        parsed
314            .as_ref()
315            .and_then(|v| v.get(k))
316            .and_then(|v| v.as_str())
317            .map(|s| s.to_string())
318            .unwrap_or_default()
319    };
320    match tool {
321        "bash" => {
322            if parsed.as_ref().and_then(|v| v.get("list")).and_then(|v| v.as_bool()).unwrap_or(false) {
323                return "list background processes".to_string();
324            }
325            if let Some(h) = parsed.as_ref().and_then(|v| v.get("kill")).and_then(|v| v.as_str()) {
326                return format!("kill {h}");
327            }
328            if let Some(h) = parsed.as_ref().and_then(|v| v.get("status")).and_then(|v| v.as_str()) {
329                return format!("status {h}");
330            }
331            let cmd = get("command");
332            if cmd.is_empty() { return String::new(); }
333            let bg = parsed.as_ref().and_then(|v| v.get("background")).and_then(|v| v.as_bool()).unwrap_or(false);
334            let suffix = if bg { "  &" } else { "" };
335            format!("$ {}{suffix}", shorten(first_line(&cmd), 140))
336        }
337        "read" => {
338            let path = get("file_path");
339            if path.is_empty() { return String::new(); }
340            let offset = parsed.as_ref().and_then(|v| v.get("offset")).and_then(|v| v.as_u64());
341            let limit = parsed.as_ref().and_then(|v| v.get("limit")).and_then(|v| v.as_u64());
342            match (offset, limit) {
343                (Some(o), Some(l)) => format!("{path}:{o}-{}", o + l),
344                (Some(o), None) => format!("{path}:{o}-"),
345                _ => path,
346            }
347        }
348        "file_write" => {
349            let path = get("file_path");
350            let content_len = parsed
351                .as_ref()
352                .and_then(|v| v.get("content"))
353                .and_then(|v| v.as_str())
354                .map(|s| s.lines().count())
355                .unwrap_or(0);
356            if path.is_empty() { return String::new(); }
357            if content_len > 0 { format!("{path}  ({content_len} lines)") } else { path }
358        }
359        "file_edit" => {
360            let path = get("file_path");
361            if path.is_empty() { return String::new(); }
362            path
363        }
364        "glob" => {
365            let pattern = get("pattern");
366            if pattern.is_empty() { return String::new(); }
367            shorten(&pattern, 140)
368        }
369        "grep" => {
370            let pattern = get("pattern");
371            let path = get("path");
372            let mut s = shorten(&pattern, 100);
373            if !path.is_empty() {
374                s.push_str(" in ");
375                s.push_str(&shorten(&path, 40));
376            }
377            s
378        }
379        "web_fetch" | "web_search" => {
380            let url = get("url");
381            let q = get("query");
382            if !url.is_empty() { shorten(&url, 140) } else { shorten(&q, 140) }
383        }
384        "delegate_to_intern" => {
385            let task = get("task");
386            shorten(first_line(&task), 140)
387        }
388        "agent" | "explore" => {
389            let task = get("task");
390            shorten(first_line(&task), 140)
391        }
392        "todo_write" | "todo_read" => String::new(),
393        _ => {
394            // Generic fallback: first string field
395            parsed
396                .as_ref()
397                .and_then(|v| v.as_object())
398                .and_then(|m| m.values().find_map(|v| v.as_str()))
399                .map(|s| shorten(first_line(s), 120))
400                .unwrap_or_default()
401        }
402    }
403}
404
405pub fn build_diff_for(tool: &str, input_json: &str) -> Vec<DiffLine> {
406    let Some(v) = try_parse(input_json) else { return Vec::new(); };
407    let max_lines = 14usize;
408    let context_lines = 2usize;
409
410    if tool == "file_write" {
411        let content = v.get("content").and_then(|c| c.as_str()).unwrap_or("");
412        return content
413            .lines()
414            .take(max_lines)
415            .map(|l| DiffLine {
416                kind: DiffLineKind::Added,
417                text: l.to_string(),
418            })
419            .collect();
420    }
421
422    let old_s = v.get("old_string").and_then(|s| s.as_str()).unwrap_or("");
423    let new_s = v.get("new_string").and_then(|s| s.as_str()).unwrap_or("");
424
425    let old_lines: Vec<&str> = old_s.split('\n').collect();
426    let new_lines: Vec<&str> = new_s.split('\n').collect();
427
428    // Trim common prefix
429    let mut p = 0;
430    while p < old_lines.len() && p < new_lines.len() && old_lines[p] == new_lines[p] {
431        p += 1;
432    }
433    // Trim common suffix
434    let mut s = 0;
435    while s < old_lines.len() - p && s < new_lines.len() - p
436        && old_lines[old_lines.len() - 1 - s] == new_lines[new_lines.len() - 1 - s]
437    {
438        s += 1;
439    }
440
441    let mut out: Vec<DiffLine> = Vec::new();
442
443    // Leading context
444    let ctx_start = p.saturating_sub(context_lines);
445    for line in &old_lines[ctx_start..p] {
446        out.push(DiffLine { kind: DiffLineKind::Context, text: line.to_string() });
447    }
448
449    // Removed
450    for line in &old_lines[p..old_lines.len() - s] {
451        out.push(DiffLine { kind: DiffLineKind::Removed, text: line.to_string() });
452        if out.len() >= max_lines { return out; }
453    }
454
455    // Added
456    for line in &new_lines[p..new_lines.len() - s] {
457        out.push(DiffLine { kind: DiffLineKind::Added, text: line.to_string() });
458        if out.len() >= max_lines { return out; }
459    }
460
461    // Trailing context
462    let ctx_end_start = old_lines.len() - s;
463    let ctx_end_stop = (ctx_end_start + context_lines).min(old_lines.len());
464    for line in &old_lines[ctx_end_start..ctx_end_stop] {
465        out.push(DiffLine { kind: DiffLineKind::Context, text: line.to_string() });
466        if out.len() >= max_lines { return out; }
467    }
468
469    out
470}
471
472pub fn excerpt_lines(text: &str, max_lines: usize, max_width: usize) -> Vec<String> {
473    let mut lines: Vec<String> = text
474        .lines()
475        .filter(|l| !l.trim().is_empty())
476        .take(max_lines + 1)
477        .map(|l| {
478            if l.chars().count() > max_width {
479                let mut s: String = l.chars().take(max_width.saturating_sub(1)).collect();
480                s.push('…');
481                s
482            } else {
483                l.to_string()
484            }
485        })
486        .collect();
487    let total = text.lines().filter(|l| !l.trim().is_empty()).count();
488    if total > max_lines {
489        lines.truncate(max_lines);
490        lines.push(format!("… +{} more lines", total - max_lines));
491    }
492    lines
493}