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