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/// USD price per million tokens `(input, output)` for a given model.
5///
6/// Matched on substrings so provider prefixes / date suffixes still resolve
7/// (e.g. `deepseek-chat`, `claude-opus-4-20250514`). Falls back to Claude
8/// Sonnet rates for unknown models.
9fn model_pricing(model: &str) -> (f64, f64) {
10    let m = model.to_ascii_lowercase();
11    match () {
12        // DeepSeek (per their published API pricing, cache-miss rates)
13        _ if m.contains("deepseek-reasoner") || m.contains("deepseek-r1") => (0.55, 2.19),
14        _ if m.contains("deepseek") => (0.27, 1.10),
15        // Anthropic
16        _ if m.contains("opus") => (15.0, 75.0),
17        _ if m.contains("haiku") => (0.80, 4.0),
18        _ if m.contains("sonnet") => (3.0, 15.0),
19        // OpenAI (common ones)
20        _ if m.contains("gpt-4o-mini") => (0.15, 0.60),
21        _ if m.contains("gpt-4o") => (2.50, 10.0),
22        // Unknown → assume Sonnet-class so the figure is non-zero but sane.
23        _ => (3.0, 15.0),
24    }
25}
26
27#[derive(Clone)]
28pub struct SessionSummary {
29    pub id: String,
30    pub title: String,
31    pub updated_at: u64,
32    pub pinned: bool,
33}
34
35pub struct SidebarState {
36    pub visible: bool,
37    pub title: String,
38    pub session_id: String,
39    pub version: String,
40    pub sessions: Vec<SessionSummary>,
41}
42
43impl SidebarState {
44    pub fn new() -> Self {
45        Self {
46            visible: true,
47            title: "New session".to_string(),
48            session_id: String::new(),
49            version: env!("CARGO_PKG_VERSION").to_string(),
50            sessions: Vec::new(),
51        }
52    }
53}
54
55impl Default for SidebarState {
56    fn default() -> Self { Self::new() }
57}
58
59pub struct AppState {
60    pub input: InputState,
61    pub conversation: ConversationState,
62    pub modal: ModalState,
63    pub sidebar: SidebarState,
64    pub toasts: ToastState,
65    pub model_name: String,
66    pub permission_mode: String,
67    pub total_cost: f64,
68    pub git_branch: Option<String>,
69    pub cwd: String,
70    pub is_streaming: bool,
71    pub is_paused: bool,
72    pub spinner_frame: usize,
73    pub spinner_tick: u8,
74    pub total_input: u64,
75    pub total_output: u64,
76    pub recent_models: Vec<String>,
77    pub tool_details: bool,
78
79    pub live_thinking: String,
80
81    pub sub_agents: Vec<(String, String)>,
82
83    pub last_summary: Option<Vec<String>>,
84
85    pub tool_history: ToolHistoryState,
86
87    pub is_pending: bool,
88    pub elapsed_secs: u64,
89    pub stale_warned: bool,
90}
91
92#[derive(Default)]
93pub struct ToolHistoryState {
94    pub selected: Option<usize>,
95    pub scroll: usize,
96    pub focused: bool,
97    pub detail_open: bool,
98}
99
100impl AppState {
101    pub fn push_recent_model(&mut self, id: &str) {
102        self.recent_models.retain(|m| m != id);
103        self.recent_models.insert(0, id.to_string());
104        if self.recent_models.len() > 8 {
105            self.recent_models.truncate(8);
106        }
107    }
108
109    pub fn cycle_recent_model(&mut self) -> Option<String> {
110        if self.recent_models.len() < 2 {
111            return None;
112        }
113        let next = self.recent_models.remove(1);
114        self.recent_models.insert(0, next.clone());
115        Some(next)
116    }
117}
118
119impl AppState {
120    pub fn new() -> Self {
121        Self {
122            input: InputState::new(),
123            conversation: ConversationState::new(),
124            modal: ModalState::new(),
125            sidebar: SidebarState::new(),
126            toasts: ToastState::new(),
127            model_name: String::from("claude-sonnet-4-20250514"),
128            permission_mode: String::from("Normal"),
129            total_cost: 0.0,
130            git_branch: None,
131            cwd: std::env::current_dir().ok()
132                .and_then(|p| p.to_str().map(|s| s.to_string()))
133                .unwrap_or_default(),
134            is_streaming: false,
135            is_paused: false,
136            spinner_frame: 0,
137            spinner_tick: 0,
138            total_input: 0,
139            total_output: 0,
140            recent_models: Vec::new(),
141            tool_details: true,
142            live_thinking: String::new(),
143            sub_agents: Vec::new(),
144            last_summary: None,
145            tool_history: ToolHistoryState::default(),
146            is_pending: false,
147            elapsed_secs: 0,
148            stale_warned: false,
149        }
150    }
151
152    pub fn push_user_message(&mut self, text: impl Into<String>) {
153        self.last_summary = None;
154        self.is_paused = false;
155        self.conversation.messages.push(DisplayMessage {
156            role: "user".to_string(),
157            content: text.into(),
158            thinking: String::new(),
159            tool_uses: Vec::new(),
160            is_streaming: false,
161        });
162        self.conversation.auto_scroll = true;
163    }
164
165    pub fn push_system_message(&mut self, text: impl Into<String>) {
166        self.conversation.messages.push(DisplayMessage {
167            role: "system".to_string(),
168            content: text.into(),
169            thinking: String::new(),
170            tool_uses: Vec::new(),
171            is_streaming: false,
172        });
173        self.conversation.auto_scroll = true;
174    }
175
176    pub fn apply_engine_event(&mut self, event: EngineEvent) {
177        self.is_pending = false;
178        match event {
179            EngineEvent::TextDelta(text) => {
180                self.is_streaming = true;
181                match self.conversation.messages.last_mut() {
182                    Some(m) if m.role == "assistant" && m.is_streaming => m.content.push_str(&text),
183                    _ => self.conversation.messages.push(DisplayMessage {
184                        role: "assistant".to_string(), content: text,
185                        thinking: String::new(), tool_uses: Vec::new(), is_streaming: true,
186                    }),
187                }
188            }
189            EngineEvent::ThinkingDelta(text) => {
190                self.is_streaming = true;
191                self.live_thinking.push_str(&text);
192                // Make sure a streaming assistant bubble exists so the "Stynx"
193                // header and its thinking indicator render while only reasoning
194                // (no text/tools yet) has streamed in.
195                if !matches!(self.conversation.messages.last(),
196                    Some(m) if m.role == "assistant" && m.is_streaming)
197                {
198                    self.conversation.messages.push(DisplayMessage {
199                        role: "assistant".to_string(), content: String::new(),
200                        thinking: String::new(), tool_uses: Vec::new(), is_streaming: true,
201                    });
202                }
203            }
204            EngineEvent::ToolStart { name, .. } => {
205                self.is_streaming = true;
206                let tool = DisplayToolUse {
207                    name,
208                    status: ToolUseStatus::Running,
209                    output_preview: String::new(),
210                    input_json: String::new(),
211                    input_summary: String::new(),
212                    output_excerpt: Vec::new(),
213                    diff: Vec::new(),
214                    sub_progress: Vec::new(),
215                };
216                match self.conversation.messages.last_mut().filter(|m| m.role == "assistant") {
217                    Some(m) => m.tool_uses.push(tool),
218                    None => self.conversation.messages.push(DisplayMessage {
219                        role: "assistant".to_string(), content: String::new(),
220                        thinking: String::new(), tool_uses: vec![tool], is_streaming: true,
221                    }),
222                }
223            }
224            EngineEvent::ToolInput { json_chunk } => {
225                if let Some(m) = self.conversation.messages.last_mut() {
226                    if let Some(t) = m.tool_uses.iter_mut().rev()
227                        .find(|t| t.status == ToolUseStatus::Running)
228                    {
229                        t.input_json.push_str(&json_chunk);
230                        t.input_summary = summarize_tool_input(&t.name, &t.input_json);
231                    }
232                }
233            }
234            EngineEvent::ToolResult { name, output, is_error } => {
235                let clean_output = crate::util::strip_ansi(&output);
236                let preview_limit = if is_error { 400 } else { 80 };
237                if let Some(m) = self.conversation.messages.last_mut() {
238                    if let Some(t) = m.tool_uses.iter_mut().rev()
239                        .find(|t| t.name == name && t.status == ToolUseStatus::Running) {
240                        t.status = if is_error { ToolUseStatus::Error } else { ToolUseStatus::Completed };
241                        t.output_preview = clean_output.lines().next().unwrap_or("").chars().take(preview_limit).collect();
242                        if t.input_summary.is_empty() {
243                            t.input_summary = summarize_tool_input(&t.name, &t.input_json);
244                        }
245                        t.output_excerpt = excerpt_lines(&clean_output, 6, 200);
246                        if t.name == "file_edit" || t.name == "file_write" {
247                            t.diff = build_diff_for(&t.name, &t.input_json);
248                        }
249
250                        if matches!(t.name.as_str(), "read" | "grep" | "glob") && !is_error {
251                            let n = clean_output.lines().filter(|l| !l.trim().is_empty()).count();
252                            if n > 0 && !t.input_summary.contains("(")  {
253                                t.input_summary = format!("{}  ({n} lines)", t.input_summary);
254                            }
255                        }
256                    }
257                }
258                if is_error {
259                    self.conversation.messages.push(DisplayMessage {
260                        role: "error".to_string(),
261                        content: format!("{name}: {clean_output}"),
262                        thinking: String::new(),
263                        tool_uses: Vec::new(),
264                        is_streaming: false,
265                    });
266                    tracing::error!(tool = %name, output = %clean_output, "tool returned error");
267                }
268            }
269            EngineEvent::TurnComplete => {
270                self.is_streaming = false;
271                let tool_summary = self.conversation.messages.last().and_then(|m| {
272                    if m.role != "assistant" { return None; }
273                    if m.tool_uses.is_empty() { return None; }
274                    let parts: Vec<String> = m.tool_uses.iter().map(|t| {
275                        let pretty = match t.name.as_str() {
276                            "bash" => "Bash".into(),
277                            "read" => "Read".into(),
278                            "file_write" => "Write".into(),
279                            "file_edit" => "Edit".into(),
280                            "glob" => "Glob".into(),
281                            "grep" => "Grep".into(),
282                            "web_fetch" => "WebFetch".into(),
283                            "web_search" => "WebSearch".into(),
284                            "todo_write" => "TodoWrite".into(),
285                            "todo_read" => "TodoRead".into(),
286                            "ask_user_question" => "AskUser".into(),
287                            "agent" => "Agent".into(),
288                            other => {
289                                let mut s = other.replace('_', " ");
290                                s = s.split_whitespace()
291                                    .map(|w| { let mut c = w.chars(); c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default() })
292                                    .collect::<Vec<_>>().join("");
293                                s
294                            }
295                        };
296                        if t.input_summary.is_empty() {
297                            pretty
298                        } else {
299                            format!("{}({})", pretty, t.input_summary)
300                        }
301                    }).collect();
302                    if parts.is_empty() { None } else { Some(parts) }
303                });
304                if let Some(m) = self.conversation.messages.last_mut() {
305                    m.is_streaming = false;
306                    if !self.live_thinking.is_empty() && m.role == "assistant" {
307                        if m.thinking.is_empty() {
308                            m.thinking = std::mem::take(&mut self.live_thinking);
309                        } else {
310                            m.thinking.push_str(&self.live_thinking);
311                            self.live_thinking.clear();
312                        }
313                    }
314                }
315                self.live_thinking.clear();
316                if let Some(summary) = tool_summary {
317                    self.last_summary = Some(summary);
318                    self.conversation.auto_scroll = true;
319                }
320            }
321            EngineEvent::Usage { input_tokens, output_tokens } => {
322                if input_tokens > 0 { self.total_input += input_tokens; }
323                if output_tokens > 0 { self.total_output += output_tokens; }
324                let (in_price, out_price) = model_pricing(&self.model_name);
325                self.total_cost = (self.total_input as f64 * in_price
326                    + self.total_output as f64 * out_price) / 1_000_000.0;
327            }
328            EngineEvent::Error(e) => {
329                self.is_streaming = false;
330                self.conversation.messages.push(DisplayMessage {
331                    role: "error".to_string(), content: e,
332                    thinking: String::new(), tool_uses: Vec::new(), is_streaming: false,
333                });
334            }
335            EngineEvent::ModeChanged { mode } => {
336                self.permission_mode = mode.label().to_string();
337            }
338            EngineEvent::SubAgentProgress { label, summary } => {
339                match self.sub_agents.iter_mut().find(|(l, _)| l == &label) {
340                    Some((_, s)) => *s = summary.clone(),
341                    None => self.sub_agents.push((label.clone(), summary.clone())),
342                }
343                if let Some(m) = self.conversation.messages.last_mut() {
344                    if let Some(t) = m.tool_uses.iter_mut().rev()
345                        .find(|t| t.status == ToolUseStatus::Running
346                            && (t.name == "agent" || t.name == "explore"
347                                || t.name.starts_with("delegate_to_")))
348                    {
349                        t.sub_progress.push(format!("{label}: {summary}"));
350                        if t.sub_progress.len() > 50 {
351                            let drop = t.sub_progress.len() - 50;
352                            t.sub_progress.drain(0..drop);
353                        }
354                    }
355                }
356            }
357            EngineEvent::SubAgentDone { label } => {
358                self.sub_agents.retain(|(l, _)| l != &label);
359            }
360            _ => {}
361        }
362    }
363}
364
365impl Default for AppState {
366    fn default() -> Self { Self::new() }
367}
368
369fn try_parse(json: &str) -> Option<serde_json::Value> {
370    if json.trim().is_empty() { return None; }
371    serde_json::from_str(json).ok()
372}
373
374fn shorten(s: &str, max: usize) -> String {
375    let trimmed = s.trim();
376    if trimmed.chars().count() <= max {
377        return trimmed.to_string();
378    }
379    let mut out: String = trimmed.chars().take(max.saturating_sub(1)).collect();
380    out.push('…');
381    out
382}
383
384fn first_line(s: &str) -> &str {
385    s.lines().next().unwrap_or("")
386}
387
388pub fn summarize_tool_input(tool: &str, json: &str) -> String {
389    let parsed = try_parse(json);
390    let get = |k: &str| -> String {
391        parsed
392            .as_ref()
393            .and_then(|v| v.get(k))
394            .and_then(|v| v.as_str())
395            .map(|s| s.to_string())
396            .unwrap_or_default()
397    };
398    match tool {
399        "bash" => {
400            if parsed.as_ref().and_then(|v| v.get("list")).and_then(|v| v.as_bool()).unwrap_or(false) {
401                return "list background processes".to_string();
402            }
403            if let Some(h) = parsed.as_ref().and_then(|v| v.get("kill")).and_then(|v| v.as_str()) {
404                return format!("kill {h}");
405            }
406            if let Some(h) = parsed.as_ref().and_then(|v| v.get("status")).and_then(|v| v.as_str()) {
407                return format!("status {h}");
408            }
409            let cmd = get("command");
410            if cmd.is_empty() { return String::new(); }
411            let bg = parsed.as_ref().and_then(|v| v.get("background")).and_then(|v| v.as_bool()).unwrap_or(false);
412            let suffix = if bg { "  &" } else { "" };
413            format!("$ {}{suffix}", shorten(first_line(&cmd), 140))
414        }
415        "read" => {
416            let path = get("file_path");
417            if path.is_empty() { return String::new(); }
418            let offset = parsed.as_ref().and_then(|v| v.get("offset")).and_then(|v| v.as_u64());
419            let limit = parsed.as_ref().and_then(|v| v.get("limit")).and_then(|v| v.as_u64());
420            match (offset, limit) {
421                (Some(o), Some(l)) => format!("{path}:{o}-{}", o + l),
422                (Some(o), None) => format!("{path}:{o}-"),
423                _ => path,
424            }
425        }
426        "file_write" => {
427            let path = get("file_path");
428            let content_len = parsed
429                .as_ref()
430                .and_then(|v| v.get("content"))
431                .and_then(|v| v.as_str())
432                .map(|s| s.lines().count())
433                .unwrap_or(0);
434            if path.is_empty() { return String::new(); }
435            if content_len > 0 { format!("{path}  ({content_len} lines)") } else { path }
436        }
437        "file_edit" => {
438            let path = get("file_path");
439            if path.is_empty() { return String::new(); }
440            path
441        }
442        "glob" => {
443            let pattern = get("pattern");
444            if pattern.is_empty() { return String::new(); }
445            shorten(&pattern, 140)
446        }
447        "grep" => {
448            let pattern = get("pattern");
449            let path = get("path");
450            let mut s = shorten(&pattern, 100);
451            if !path.is_empty() {
452                s.push_str(" in ");
453                s.push_str(&shorten(&path, 40));
454            }
455            s
456        }
457        "web_fetch" | "web_search" => {
458            let url = get("url");
459            let q = get("query");
460            if !url.is_empty() { shorten(&url, 140) } else { shorten(&q, 140) }
461        }
462        "delegate_to_intern" => {
463            let task = get("task");
464            shorten(first_line(&task), 140)
465        }
466        "agent" | "explore" => {
467            let task = get("task");
468            shorten(first_line(&task), 140)
469        }
470        "todo_write" | "todo_read" => String::new(),
471        _ => {
472
473            parsed
474                .as_ref()
475                .and_then(|v| v.as_object())
476                .and_then(|m| m.values().find_map(|v| v.as_str()))
477                .map(|s| shorten(first_line(s), 120))
478                .unwrap_or_default()
479        }
480    }
481}
482
483pub fn build_diff_for(tool: &str, input_json: &str) -> Vec<DiffLine> {
484    let Some(v) = try_parse(input_json) else { return Vec::new(); };
485    let max_lines = 14usize;
486    let context_lines = 2usize;
487
488    if tool == "file_write" {
489        let content = v.get("content").and_then(|c| c.as_str()).unwrap_or("");
490        return content
491            .lines()
492            .take(max_lines)
493            .map(|l| DiffLine {
494                kind: DiffLineKind::Added,
495                text: l.to_string(),
496            })
497            .collect();
498    }
499
500    let old_s = v.get("old_string").and_then(|s| s.as_str()).unwrap_or("");
501    let new_s = v.get("new_string").and_then(|s| s.as_str()).unwrap_or("");
502
503    let old_lines: Vec<&str> = old_s.split('\n').collect();
504    let new_lines: Vec<&str> = new_s.split('\n').collect();
505
506    let mut p = 0;
507    while p < old_lines.len() && p < new_lines.len() && old_lines[p] == new_lines[p] {
508        p += 1;
509    }
510
511    let mut s = 0;
512    while s < old_lines.len() - p && s < new_lines.len() - p
513        && old_lines[old_lines.len() - 1 - s] == new_lines[new_lines.len() - 1 - s]
514    {
515        s += 1;
516    }
517
518    let mut out: Vec<DiffLine> = Vec::new();
519
520    let ctx_start = p.saturating_sub(context_lines);
521    for line in &old_lines[ctx_start..p] {
522        out.push(DiffLine { kind: DiffLineKind::Context, text: line.to_string() });
523    }
524
525    for line in &old_lines[p..old_lines.len() - s] {
526        out.push(DiffLine { kind: DiffLineKind::Removed, text: line.to_string() });
527        if out.len() >= max_lines { return out; }
528    }
529
530    for line in &new_lines[p..new_lines.len() - s] {
531        out.push(DiffLine { kind: DiffLineKind::Added, text: line.to_string() });
532        if out.len() >= max_lines { return out; }
533    }
534
535    let ctx_end_start = old_lines.len() - s;
536    let ctx_end_stop = (ctx_end_start + context_lines).min(old_lines.len());
537    for line in &old_lines[ctx_end_start..ctx_end_stop] {
538        out.push(DiffLine { kind: DiffLineKind::Context, text: line.to_string() });
539        if out.len() >= max_lines { return out; }
540    }
541
542    out
543}
544
545pub fn excerpt_lines(text: &str, max_lines: usize, max_width: usize) -> Vec<String> {
546    let mut lines: Vec<String> = text
547        .lines()
548        .filter(|l| !l.trim().is_empty())
549        .take(max_lines + 1)
550        .map(|l| {
551            if l.chars().count() > max_width {
552                let mut s: String = l.chars().take(max_width.saturating_sub(1)).collect();
553                s.push('…');
554                s
555            } else {
556                l.to_string()
557            }
558        })
559        .collect();
560    let total = text.lines().filter(|l| !l.trim().is_empty()).count();
561    if total > max_lines {
562        lines.truncate(max_lines);
563        lines.push(format!("… +{} more lines", total - max_lines));
564    }
565    lines
566}