Skip to main content

devbook_tui/
app.rs

1#![allow(dead_code)]
2
3use std::path::PathBuf;
4
5use anyhow::Result;
6use arboard::Clipboard;
7use crossterm::event::KeyCode;
8
9use crate::api::ApiClient;
10use crate::checklist::{
11    append_to_prompt, parse_checklist_items, toggle_checklist_item_by_index, ChecklistItem,
12};
13use crate::config::{get_preset_hosts, Config};
14use crate::models::{Project, ProjectInput, Prompt, PromptDetail, PromptInput, Stats};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Pane {
18    Sidebar,
19    Prompts,
20    Detail,
21}
22
23impl Pane {
24    pub fn next(self) -> Self {
25        match self {
26            Pane::Sidebar => Pane::Prompts,
27            Pane::Prompts => Pane::Detail,
28            Pane::Detail => Pane::Sidebar,
29        }
30    }
31
32    pub fn prev(self) -> Self {
33        match self {
34            Pane::Sidebar => Pane::Detail,
35            Pane::Prompts => Pane::Sidebar,
36            Pane::Detail => Pane::Prompts,
37        }
38    }
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum ViewMode {
43    Preview,
44    Raw,
45}
46
47impl ViewMode {
48    pub fn toggle(self) -> Self {
49        match self {
50            ViewMode::Preview => ViewMode::Raw,
51            ViewMode::Raw => ViewMode::Preview,
52        }
53    }
54
55    pub fn label(self) -> &'static str {
56        match self {
57            ViewMode::Preview => "Preview",
58            ViewMode::Raw => "Raw",
59        }
60    }
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum ScopeItem {
65    All,
66    Pinned,
67    Standalone,
68    Project(Project),
69    PinnedPrompt(Prompt),
70}
71
72#[derive(Debug, Clone)]
73pub enum DeleteTarget {
74    Project(Project),
75    Prompt(Prompt),
76    Attachment {
77        prompt_id: u64,
78        attachment_id: u64,
79        filename: String,
80    },
81}
82
83#[derive(Debug, Clone)]
84pub enum Modal {
85    HostSwitcher {
86        cursor: usize,
87        custom_input: String,
88        entering_custom: bool,
89    },
90    Search {
91        input: String,
92    },
93    QuickAppendPrompt {
94        content_input: String,
95        section_input: String,
96        as_task: bool,
97        focus_field: usize, // 0: content, 1: section, 2: as_task
98    },
99    ProjectForm {
100        id: Option<u64>,
101        name_input: String,
102        desc_input: String,
103        focus_desc: bool,
104    },
105    PromptForm {
106        id: Option<u64>,
107        title_input: String,
108        project_choice_idx: usize, // 0 = None (Standalone), 1.. = index into projects
109        pinned: bool,
110        focus_field: usize, // 0: title, 1: project, 2: pinned
111    },
112    ConfirmDelete {
113        target: DeleteTarget,
114    },
115    Attachments {
116        cursor: usize,
117        upload_input: Option<String>,
118        dest_input: Option<String>,
119    },
120    Help,
121}
122
123pub struct App {
124    pub config: Config,
125    pub client: ApiClient,
126    pub should_quit: bool,
127    pub pending_editor: Option<(u64, PathBuf)>, // prompt_id, temp_path
128    pub status: Option<(String, bool)>,         // (message, is_error)
129
130    // Layout & Navigation
131    pub focused_pane: Pane,
132    pub view_mode: ViewMode,
133    pub modal: Option<Modal>,
134
135    // Data
136    pub stats: Stats,
137    pub preset_hosts: Vec<String>,
138    pub projects: Vec<Project>,
139    pub pinned_prompts: Vec<Prompt>,
140    pub prompts: Vec<Prompt>,
141    pub current_prompt: Option<PromptDetail>,
142    pub checklist_items: Vec<ChecklistItem>,
143
144    // Selections
145    pub sidebar_selected: usize,
146    pub prompts_selected: usize,
147    pub detail_selected_checklist: Option<usize>,
148    pub detail_scroll: usize,
149
150    // Search query
151    pub search_query: Option<String>,
152
153    pub clipboard: Option<Clipboard>,
154}
155
156pub fn sort_prompts(prompts: &mut [Prompt]) {
157    prompts.sort_by(|a, b| {
158        b.pinned
159            .cmp(&a.pinned)
160            .then_with(|| a.title.to_lowercase().cmp(&b.title.to_lowercase()))
161            .then_with(|| a.title.cmp(&b.title))
162            .then_with(|| a.id.cmp(&b.id))
163    });
164}
165
166impl App {
167    pub fn new(config: Config) -> Self {
168        let client = ApiClient::new(&config);
169        let clipboard = Clipboard::new().ok();
170
171        let mut app = Self {
172            config,
173            client,
174            should_quit: false,
175            pending_editor: None,
176            status: None,
177
178            focused_pane: Pane::Prompts,
179            view_mode: ViewMode::Preview,
180            modal: None,
181
182            stats: Stats::default(),
183            preset_hosts: get_preset_hosts(),
184            projects: Vec::new(),
185            pinned_prompts: Vec::new(),
186            prompts: Vec::new(),
187            current_prompt: None,
188            checklist_items: Vec::new(),
189
190            sidebar_selected: 0,
191            prompts_selected: 0,
192            detail_selected_checklist: None,
193            detail_scroll: 0,
194
195            search_query: None,
196            clipboard,
197        };
198
199        app.reload_all();
200        app
201    }
202
203    pub fn set_status(&mut self, msg: impl Into<String>, is_error: bool) {
204        self.status = Some((msg.into(), is_error));
205    }
206
207    pub fn clear_status(&mut self) {
208        self.status = None;
209    }
210
211    // Host Management
212    pub fn switch_host(&mut self, new_url: &str) {
213        let normalized = crate::config::normalize_url(new_url);
214        self.config.set_url(&normalized);
215        self.client.set_base_url(&normalized);
216        self.set_status(format!("Switched host to {}", normalized), false);
217        self.reload_all();
218    }
219
220    // Data Fetching
221    pub fn reload_all(&mut self) {
222        self.load_stats();
223        self.load_projects();
224        self.load_pinned_prompts();
225        self.load_prompts();
226    }
227
228    pub fn load_stats(&mut self) {
229        match self.client.get_stats() {
230            Ok(s) => self.stats = s,
231            Err(e) => self.set_status(format!("Stats error: {}", e), true),
232        }
233    }
234
235    pub fn load_projects(&mut self) {
236        match self.client.list_projects(None) {
237            Ok(projs) => {
238                self.projects = projs;
239                if self.sidebar_selected >= self.total_sidebar_items() {
240                    self.sidebar_selected = self.total_sidebar_items().saturating_sub(1);
241                }
242            }
243            Err(e) => self.set_status(format!("Projects error: {}", e), true),
244        }
245    }
246
247    pub fn load_pinned_prompts(&mut self) {
248        match self.client.list_prompts(None, None, Some(true), None) {
249            Ok(mut prompts) => {
250                sort_prompts(&mut prompts);
251                self.pinned_prompts = prompts;
252                if self.sidebar_selected >= self.total_sidebar_items() {
253                    self.sidebar_selected = self.total_sidebar_items().saturating_sub(1);
254                }
255            }
256            Err(e) => self.set_status(format!("Pinned prompts error: {}", e), true),
257        }
258    }
259
260    pub fn total_sidebar_items(&self) -> usize {
261        3 + self.projects.len() + self.pinned_prompts.len()
262    }
263
264    pub fn get_sidebar_item(&self, idx: usize) -> ScopeItem {
265        match idx {
266            0 => ScopeItem::All,
267            1 => ScopeItem::Pinned,
268            2 => ScopeItem::Standalone,
269            n => {
270                let proj_idx = n - 3;
271                if proj_idx < self.projects.len() {
272                    ScopeItem::Project(self.projects[proj_idx].clone())
273                } else {
274                    let pinned_idx = proj_idx - self.projects.len();
275                    if let Some(prompt) = self.pinned_prompts.get(pinned_idx) {
276                        ScopeItem::PinnedPrompt(prompt.clone())
277                    } else {
278                        ScopeItem::All
279                    }
280                }
281            }
282        }
283    }
284
285    pub fn load_prompts(&mut self) {
286        let scope_item = self.get_sidebar_item(self.sidebar_selected);
287        let q = self.search_query.as_deref();
288
289        let res = match scope_item {
290            ScopeItem::All => self.client.list_prompts(None, None, None, q),
291            ScopeItem::Pinned => self.client.list_prompts(None, None, Some(true), q),
292            ScopeItem::Standalone => self.client.list_prompts(None, Some("standalone"), None, q),
293            ScopeItem::Project(p) => self.client.list_prompts(Some(p.id), None, None, q),
294            ScopeItem::PinnedPrompt(prompt) => {
295                if let Some(query) = q {
296                    let query_lower = query.to_lowercase();
297                    if prompt.title.to_lowercase().contains(&query_lower) {
298                        Ok(vec![prompt])
299                    } else {
300                        Ok(vec![])
301                    }
302                } else {
303                    Ok(vec![prompt])
304                }
305            }
306        };
307
308        match res {
309            Ok(mut list) => {
310                sort_prompts(&mut list);
311                self.prompts = list;
312                if self.prompts.is_empty() {
313                    self.prompts_selected = 0;
314                    self.current_prompt = None;
315                    self.checklist_items.clear();
316                    self.detail_selected_checklist = None;
317                    self.detail_scroll = 0;
318                } else {
319                    if self.prompts_selected >= self.prompts.len() {
320                        self.prompts_selected = self.prompts.len() - 1;
321                    }
322                    self.load_current_prompt_detail();
323                }
324            }
325            Err(e) => self.set_status(format!("Prompts error: {}", e), true),
326        }
327    }
328
329    pub fn load_current_prompt_detail(&mut self) {
330        if let Some(prompt) = self.prompts.get(self.prompts_selected) {
331            match self.client.get_prompt(prompt.id) {
332                Ok(detail) => {
333                    self.checklist_items =
334                        parse_checklist_items(detail.body.as_deref().unwrap_or(""));
335                    if self.checklist_items.is_empty() {
336                        self.detail_selected_checklist = None;
337                    } else if let Some(cur) = self.detail_selected_checklist {
338                        if cur >= self.checklist_items.len() {
339                            self.detail_selected_checklist = Some(self.checklist_items.len() - 1);
340                        }
341                    } else {
342                        self.detail_selected_checklist = Some(0);
343                    }
344                    self.detail_scroll = 0;
345                    self.current_prompt = Some(detail);
346                }
347                Err(e) => {
348                    self.set_status(format!("Detail load error: {}", e), true);
349                    self.current_prompt = None;
350                    self.checklist_items.clear();
351                }
352            }
353        } else {
354            self.current_prompt = None;
355            self.checklist_items.clear();
356            self.detail_selected_checklist = None;
357            self.detail_scroll = 0;
358        }
359    }
360
361    // Toggle Checklist Item
362    pub fn toggle_current_checklist_item(&mut self) {
363        let (detail, cur_idx) = match (&self.current_prompt, self.detail_selected_checklist) {
364            (Some(d), Some(idx)) => (d.clone(), idx),
365            _ => return,
366        };
367
368        let body = detail.body.as_deref().unwrap_or("");
369        if let Some((updated_body, item)) = toggle_checklist_item_by_index(body, cur_idx) {
370            let input = PromptInput {
371                title: detail.title.clone(),
372                body: Some(updated_body.clone()),
373                ..Default::default()
374            };
375
376            match self.client.update_prompt(detail.id, &input) {
377                Ok(new_detail) => {
378                    if let Some(list_item) = self.prompts.get_mut(self.prompts_selected) {
379                        list_item.body = new_detail.body.clone();
380                    }
381                    self.checklist_items = parse_checklist_items(&updated_body);
382                    self.current_prompt = Some(new_detail);
383                    let state_str = if item.completed { "done" } else { "pending" };
384                    self.set_status(format!("Task marked {}", state_str), false);
385                }
386                Err(e) => self.set_status(format!("Failed to update prompt: {}", e), true),
387            }
388        }
389    }
390
391    // Quick Append to Prompt
392    pub fn append_prompt_content(&mut self, text: &str, section: Option<&str>, as_task: bool) {
393        let detail = match &self.current_prompt {
394            Some(d) => d.clone(),
395            None => return,
396        };
397
398        let current_body = detail.body.as_deref().unwrap_or("");
399        let updated = append_to_prompt(current_body, text, section, as_task);
400
401        let input = PromptInput {
402            title: detail.title.clone(),
403            body: Some(updated.clone()),
404            ..Default::default()
405        };
406
407        match self.client.update_prompt(detail.id, &input) {
408            Ok(new_detail) => {
409                if let Some(list_item) = self.prompts.get_mut(self.prompts_selected) {
410                    list_item.body = new_detail.body.clone();
411                }
412                self.checklist_items = parse_checklist_items(&updated);
413                if !self.checklist_items.is_empty() && self.detail_selected_checklist.is_none() {
414                    self.detail_selected_checklist = Some(0);
415                }
416                self.current_prompt = Some(new_detail);
417                self.set_status("Appended to prompt successfully", false);
418            }
419            Err(e) => self.set_status(format!("Failed to append to prompt: {}", e), true),
420        }
421    }
422
423    // Toggle Pin on selected Prompt
424    pub fn toggle_pin_current(&mut self) {
425        if let Some(prompt) = self.prompts.get(self.prompts_selected) {
426            match self.client.toggle_pin(prompt.id) {
427                Ok(resp) => {
428                    let msg = if resp.pinned {
429                        "Pinned prompt"
430                    } else {
431                        "Unpinned prompt"
432                    };
433                    self.set_status(msg, false);
434                    self.load_stats();
435                    self.load_pinned_prompts();
436                    self.load_prompts();
437                }
438                Err(e) => self.set_status(format!("Toggle pin error: {}", e), true),
439            }
440        }
441    }
442
443    // Reorder pinned prompts up/down
444    pub fn move_pinned_current(&mut self, direction_up: bool) {
445        let is_pinned_scope =
446            matches!(self.get_sidebar_item(self.sidebar_selected), ScopeItem::Pinned);
447        if !is_pinned_scope || self.prompts.len() < 2 {
448            return;
449        }
450
451        let cur_idx = self.prompts_selected;
452        let new_idx = if direction_up {
453            if cur_idx == 0 {
454                return;
455            }
456            cur_idx - 1
457        } else {
458            if cur_idx + 1 >= self.prompts.len() {
459                return;
460            }
461            cur_idx + 1
462        };
463
464        self.prompts.swap(cur_idx, new_idx);
465        self.prompts_selected = new_idx;
466
467        let ids: Vec<u64> = self.prompts.iter().map(|p| p.id).collect();
468        if let Err(e) = self.client.reorder_pinned(&ids) {
469            self.set_status(format!("Reorder error: {}", e), true);
470        } else {
471            self.set_status("Reordered pinned prompts", false);
472        }
473    }
474
475    // Yank to clipboard
476    pub fn yank_current(&mut self, full_body: bool) {
477        let text_to_copy = if full_body {
478            self.current_prompt
479                .as_ref()
480                .and_then(|d| d.body.clone())
481                .unwrap_or_default()
482        } else if let Some(idx) = self.detail_selected_checklist {
483            self.checklist_items
484                .get(idx)
485                .map(|item| item.text.clone())
486                .unwrap_or_default()
487        } else {
488            self.current_prompt
489                .as_ref()
490                .map(|d| d.title.clone())
491                .unwrap_or_default()
492        };
493
494        if text_to_copy.is_empty() {
495            self.set_status("Nothing to copy", false);
496            return;
497        }
498
499        if let Some(cb) = &mut self.clipboard {
500            if let Err(e) = cb.set_text(text_to_copy.clone()) {
501                self.set_status(format!("Clipboard error: {}", e), true);
502            } else {
503                let first_line = text_to_copy.lines().next().unwrap_or("");
504                let preview = if first_line.chars().count() > 30 {
505                    let s: String = first_line.chars().take(30).collect();
506                    format!("{}...", s)
507                } else {
508                    first_line.to_string()
509                };
510                if full_body {
511                    self.set_status(format!("Copied Prompt: \"{}\"", preview), false);
512                } else {
513                    self.set_status(format!("Copied: \"{}\"", preview), false);
514                }
515            }
516        } else {
517            self.set_status("Clipboard unavailable", true);
518        }
519    }
520
521    // External Editor Setup
522    pub fn prepare_external_editor(&mut self) -> Result<()> {
523        let detail = match &self.current_prompt {
524            Some(d) => d.clone(),
525            None => return Ok(()),
526        };
527
528        let temp_dir = std::env::temp_dir();
529        let file_path = temp_dir.join(format!("devbook-prompt-{}.md", detail.id));
530        std::fs::write(&file_path, detail.body.as_deref().unwrap_or(""))?;
531
532        self.pending_editor = Some((detail.id, file_path));
533        Ok(())
534    }
535
536    pub fn complete_external_editor(&mut self) -> Result<()> {
537        if let Some((id, path)) = self.pending_editor.take() {
538            if path.exists() {
539                let content = std::fs::read_to_string(&path)?;
540                let _ = std::fs::remove_file(&path);
541
542                if let Some(detail) = &self.current_prompt {
543                    if detail.id == id {
544                        let input = PromptInput {
545                            title: detail.title.clone(),
546                            body: Some(content.clone()),
547                            ..Default::default()
548                        };
549                        match self.client.update_prompt(id, &input) {
550                            Ok(new_detail) => {
551                                if let Some(list_item) = self.prompts.get_mut(self.prompts_selected) {
552                                    list_item.body = new_detail.body.clone();
553                                }
554                                self.checklist_items = parse_checklist_items(&content);
555                                self.current_prompt = Some(new_detail);
556                                self.set_status("Saved prompt markdown from editor", false);
557                            }
558                            Err(e) => {
559                                self.set_status(format!("Failed to save from editor: {}", e), true)
560                            }
561                        }
562                    }
563                }
564            }
565        }
566        Ok(())
567    }
568
569    fn adjust_scroll_to_checklist_item(&mut self, item_idx: usize) {
570        if let Some(item) = self.checklist_items.get(item_idx) {
571            let target_line = item.line_number.saturating_sub(1);
572            if target_line < self.detail_scroll {
573                self.detail_scroll = target_line;
574            } else if target_line >= self.detail_scroll + 18 {
575                self.detail_scroll = target_line.saturating_sub(15);
576            }
577        }
578    }
579
580    // Keyboard Event Handling
581    pub fn handle_key(&mut self, key: KeyCode) {
582        if self.modal.is_some() {
583            self.handle_modal_key(key);
584            return;
585        }
586
587        match key {
588            KeyCode::Char('q') => self.should_quit = true,
589            KeyCode::Char('?') => self.modal = Some(Modal::Help),
590            KeyCode::Char('H') | KeyCode::Char('u') => {
591                if self.config.allow_host_switcher {
592                    self.modal = Some(Modal::HostSwitcher {
593                        cursor: 0,
594                        custom_input: self.config.base_url.clone(),
595                        entering_custom: false,
596                    });
597                } else {
598                    self.set_status(
599                        "Host switching locked by DEVBOOK_REMOTE_URL (pass --allow-switch to enable)",
600                        true,
601                    );
602                }
603            }
604            KeyCode::Char('/') => {
605                self.modal = Some(Modal::Search {
606                    input: self.search_query.clone().unwrap_or_default(),
607                });
608            }
609            KeyCode::Char('r') => {
610                self.reload_all();
611                self.set_status("Refreshed all data", false);
612            }
613            KeyCode::Char('v') | KeyCode::Char('m') => {
614                self.view_mode = self.view_mode.toggle();
615                self.set_status(
616                    format!("Switched to {} Markdown mode", self.view_mode.label()),
617                    false,
618                );
619            }
620
621            // Pane Navigation
622            KeyCode::Char('1') => self.focused_pane = Pane::Sidebar,
623            KeyCode::Char('2') => self.focused_pane = Pane::Prompts,
624            KeyCode::Char('3') => self.focused_pane = Pane::Detail,
625            KeyCode::Tab => self.focused_pane = self.focused_pane.next(),
626            KeyCode::BackTab => self.focused_pane = self.focused_pane.prev(),
627            KeyCode::Char('h') | KeyCode::Left => self.focused_pane = self.focused_pane.prev(),
628            KeyCode::Char('l') | KeyCode::Right => self.focused_pane = self.focused_pane.next(),
629
630            // Actions per pane
631            _ => match self.focused_pane {
632                Pane::Sidebar => self.handle_sidebar_key(key),
633                Pane::Prompts => self.handle_prompts_key(key),
634                Pane::Detail => self.handle_detail_key(key),
635            },
636        }
637    }
638
639    fn handle_sidebar_key(&mut self, key: KeyCode) {
640        match key {
641            KeyCode::Char('j') | KeyCode::Down => {
642                if self.sidebar_selected + 1 < self.total_sidebar_items() {
643                    self.sidebar_selected += 1;
644                    self.prompts_selected = 0;
645                    self.load_prompts();
646                }
647            }
648            KeyCode::Char('k') | KeyCode::Up => {
649                if self.sidebar_selected > 0 {
650                    self.sidebar_selected -= 1;
651                    self.prompts_selected = 0;
652                    self.load_prompts();
653                }
654            }
655            KeyCode::Enter => match self.get_sidebar_item(self.sidebar_selected) {
656                ScopeItem::PinnedPrompt(_) => {
657                    self.focused_pane = Pane::Detail;
658                }
659                _ => {
660                    self.focused_pane = Pane::Prompts;
661                }
662            },
663            KeyCode::Char('n') => {
664                self.modal = Some(Modal::ProjectForm {
665                    id: None,
666                    name_input: String::new(),
667                    desc_input: String::new(),
668                    focus_desc: false,
669                });
670            }
671            KeyCode::Char('e') => {
672                if let ScopeItem::Project(p) = self.get_sidebar_item(self.sidebar_selected) {
673                    self.modal = Some(Modal::ProjectForm {
674                        id: Some(p.id),
675                        name_input: p.name,
676                        desc_input: p.description.unwrap_or_default(),
677                        focus_desc: false,
678                    });
679                }
680            }
681            KeyCode::Char('d') => {
682                if let ScopeItem::Project(p) = self.get_sidebar_item(self.sidebar_selected) {
683                    self.modal = Some(Modal::ConfirmDelete {
684                        target: DeleteTarget::Project(p),
685                    });
686                }
687            }
688            _ => {}
689        }
690    }
691
692    fn handle_prompts_key(&mut self, key: KeyCode) {
693        match key {
694            KeyCode::Char('j') | KeyCode::Down => {
695                if !self.prompts.is_empty() && self.prompts_selected + 1 < self.prompts.len() {
696                    self.prompts_selected += 1;
697                    self.load_current_prompt_detail();
698                }
699            }
700            KeyCode::Char('k') | KeyCode::Up => {
701                if self.prompts_selected > 0 {
702                    self.prompts_selected -= 1;
703                    self.load_current_prompt_detail();
704                }
705            }
706            KeyCode::Enter => {
707                self.focused_pane = Pane::Detail;
708            }
709            KeyCode::Char('p') => {
710                self.toggle_pin_current();
711            }
712            KeyCode::Char('K') => {
713                self.move_pinned_current(true);
714            }
715            KeyCode::Char('J') => {
716                self.move_pinned_current(false);
717            }
718            KeyCode::Char('y') => {
719                self.yank_current(false);
720            }
721            KeyCode::Char('Y') | KeyCode::Char('c') => {
722                self.yank_current(true);
723            }
724            KeyCode::Char('E') => {
725                if let Err(e) = self.prepare_external_editor() {
726                    self.set_status(format!("Failed to open editor: {}", e), true);
727                }
728            }
729            KeyCode::Char('a') => {
730                if self.current_prompt.is_some() {
731                    self.modal = Some(Modal::QuickAppendPrompt {
732                        content_input: String::new(),
733                        section_input: String::new(),
734                        as_task: false,
735                        focus_field: 0,
736                    });
737                }
738            }
739            KeyCode::Char('A') => {
740                if self.current_prompt.is_some() {
741                    self.modal = Some(Modal::Attachments {
742                        cursor: 0,
743                        upload_input: None,
744                        dest_input: None,
745                    });
746                }
747            }
748            KeyCode::Char('n') => {
749                let default_proj_idx = match self.get_sidebar_item(self.sidebar_selected) {
750                    ScopeItem::Project(p) => self
751                        .projects
752                        .iter()
753                        .position(|pr| pr.id == p.id)
754                        .map(|i| i + 1)
755                        .unwrap_or(0),
756                    _ => 0,
757                };
758                self.modal = Some(Modal::PromptForm {
759                    id: None,
760                    title_input: String::new(),
761                    project_choice_idx: default_proj_idx,
762                    pinned: false,
763                    focus_field: 0,
764                });
765            }
766            KeyCode::Char('e') => {
767                if let Some(detail) = &self.current_prompt {
768                    let proj_choice = detail
769                        .project_id
770                        .and_then(|pid| {
771                            self.projects
772                                .iter()
773                                .position(|p| p.id == pid)
774                                .map(|i| i + 1)
775                        })
776                        .unwrap_or(0);
777                    self.modal = Some(Modal::PromptForm {
778                        id: Some(detail.id),
779                        title_input: detail.title.clone(),
780                        project_choice_idx: proj_choice,
781                        pinned: detail.pinned,
782                        focus_field: 0,
783                    });
784                }
785            }
786            KeyCode::Char('d') => {
787                if let Some(prompt) = self.prompts.get(self.prompts_selected) {
788                    self.modal = Some(Modal::ConfirmDelete {
789                        target: DeleteTarget::Prompt(prompt.clone()),
790                    });
791                }
792            }
793            _ => {}
794        }
795    }
796
797    fn handle_detail_key(&mut self, key: KeyCode) {
798        match key {
799            KeyCode::Char('j') | KeyCode::Down => {
800                if !self.checklist_items.is_empty() && self.view_mode == ViewMode::Preview {
801                    let next = match self.detail_selected_checklist {
802                        Some(i) if i + 1 < self.checklist_items.len() => i + 1,
803                        None => 0,
804                        Some(i) => {
805                            self.detail_scroll = self.detail_scroll.saturating_add(1);
806                            i
807                        }
808                    };
809                    self.detail_selected_checklist = Some(next);
810                    self.adjust_scroll_to_checklist_item(next);
811                } else {
812                    self.detail_scroll = self.detail_scroll.saturating_add(1);
813                }
814            }
815            KeyCode::Char('k') | KeyCode::Up => {
816                if !self.checklist_items.is_empty() && self.view_mode == ViewMode::Preview {
817                    let prev = match self.detail_selected_checklist {
818                        Some(i) if i > 0 => i - 1,
819                        _ => {
820                            self.detail_scroll = self.detail_scroll.saturating_sub(1);
821                            0
822                        }
823                    };
824                    self.detail_selected_checklist = Some(prev);
825                    self.adjust_scroll_to_checklist_item(prev);
826                } else {
827                    self.detail_scroll = self.detail_scroll.saturating_sub(1);
828                }
829            }
830            // Document scrolling
831            KeyCode::Char('J') => {
832                self.detail_scroll = self.detail_scroll.saturating_add(3);
833            }
834            KeyCode::Char('K') => {
835                self.detail_scroll = self.detail_scroll.saturating_sub(3);
836            }
837            KeyCode::PageDown => {
838                self.detail_scroll = self.detail_scroll.saturating_add(10);
839            }
840            KeyCode::PageUp => {
841                self.detail_scroll = self.detail_scroll.saturating_sub(10);
842            }
843            KeyCode::Char('g') => {
844                self.detail_scroll = 0;
845                if !self.checklist_items.is_empty() {
846                    self.detail_selected_checklist = Some(0);
847                }
848            }
849            KeyCode::Char('G') => {
850                let total_lines = self
851                    .current_prompt
852                    .as_ref()
853                    .and_then(|d| d.body.as_deref())
854                    .map(|b| b.lines().count())
855                    .unwrap_or(0);
856                self.detail_scroll = total_lines.saturating_sub(5);
857                if !self.checklist_items.is_empty() {
858                    self.detail_selected_checklist = Some(self.checklist_items.len() - 1);
859                }
860            }
861            // Checklist toggle
862            KeyCode::Char(' ') | KeyCode::Enter => {
863                if !self.checklist_items.is_empty() {
864                    self.toggle_current_checklist_item();
865                }
866            }
867            // Quick append to prompt
868            KeyCode::Char('a') => {
869                if self.current_prompt.is_some() {
870                    self.modal = Some(Modal::QuickAppendPrompt {
871                        content_input: String::new(),
872                        section_input: String::new(),
873                        as_task: false,
874                        focus_field: 0,
875                    });
876                }
877            }
878            // External editor
879            KeyCode::Char('E') => {
880                if let Err(e) = self.prepare_external_editor() {
881                    self.set_status(format!("Failed to open editor: {}", e), true);
882                }
883            }
884            // Yank
885            KeyCode::Char('y') => {
886                self.yank_current(false);
887            }
888            KeyCode::Char('Y') | KeyCode::Char('c') => {
889                self.yank_current(true);
890            }
891            // Pin toggle
892            KeyCode::Char('p') => {
893                self.toggle_pin_current();
894            }
895            // Attachments
896            KeyCode::Char('A') if self.current_prompt.is_some() => {
897                self.modal = Some(Modal::Attachments {
898                    cursor: 0,
899                    upload_input: None,
900                    dest_input: None,
901                });
902            }
903            _ => {}
904        }
905    }
906
907    fn handle_modal_key(&mut self, key: KeyCode) {
908        let modal = self.modal.clone();
909        match modal {
910            Some(Modal::HostSwitcher {
911                cursor,
912                mut custom_input,
913                entering_custom,
914            }) => match key {
915                KeyCode::Esc => self.modal = None,
916                KeyCode::Up => {
917                    if !entering_custom && cursor > 0 {
918                        self.modal = Some(Modal::HostSwitcher {
919                            cursor: cursor - 1,
920                            custom_input,
921                            entering_custom: false,
922                        });
923                    }
924                }
925                KeyCode::Down => {
926                    if !entering_custom && cursor < self.preset_hosts.len() {
927                        self.modal = Some(Modal::HostSwitcher {
928                            cursor: cursor + 1,
929                            custom_input,
930                            entering_custom: false,
931                        });
932                    }
933                }
934                KeyCode::Tab => {
935                    let next_entering = !entering_custom;
936                    self.modal = Some(Modal::HostSwitcher {
937                        cursor,
938                        custom_input,
939                        entering_custom: next_entering,
940                    });
941                }
942                KeyCode::Char('c') if !entering_custom => {
943                    self.modal = Some(Modal::HostSwitcher {
944                        cursor,
945                        custom_input,
946                        entering_custom: true,
947                    });
948                }
949                KeyCode::Char(c) if entering_custom => {
950                    custom_input.push(c);
951                    self.modal = Some(Modal::HostSwitcher {
952                        cursor,
953                        custom_input,
954                        entering_custom: true,
955                    });
956                }
957                KeyCode::Backspace if entering_custom => {
958                    custom_input.pop();
959                    self.modal = Some(Modal::HostSwitcher {
960                        cursor,
961                        custom_input,
962                        entering_custom: true,
963                    });
964                }
965                KeyCode::Enter => {
966                    self.modal = None;
967                    if entering_custom || cursor == self.preset_hosts.len() {
968                        if !custom_input.trim().is_empty() {
969                            self.switch_host(&custom_input);
970                        }
971                    } else if let Some(preset) = self.preset_hosts.get(cursor).cloned() {
972                        self.switch_host(&preset);
973                    }
974                }
975                _ => {}
976            },
977
978            Some(Modal::Search { mut input }) => match key {
979                KeyCode::Esc => {
980                    self.modal = None;
981                    self.search_query = None;
982                    self.load_prompts();
983                }
984                KeyCode::Enter => {
985                    self.modal = None;
986                    self.search_query = if input.trim().is_empty() {
987                        None
988                    } else {
989                        Some(input.trim().to_string())
990                    };
991                    self.load_prompts();
992                }
993                KeyCode::Char(c) => {
994                    input.push(c);
995                    self.modal = Some(Modal::Search {
996                        input: input.clone(),
997                    });
998                    self.search_query = Some(input);
999                    self.load_prompts();
1000                }
1001                KeyCode::Backspace => {
1002                    input.pop();
1003                    self.modal = Some(Modal::Search {
1004                        input: input.clone(),
1005                    });
1006                    self.search_query = if input.is_empty() { None } else { Some(input) };
1007                    self.load_prompts();
1008                }
1009                _ => {}
1010            },
1011
1012            Some(Modal::QuickAppendPrompt {
1013                mut content_input,
1014                mut section_input,
1015                mut as_task,
1016                focus_field,
1017            }) => match key {
1018                KeyCode::Esc => self.modal = None,
1019                KeyCode::Tab => {
1020                    self.modal = Some(Modal::QuickAppendPrompt {
1021                        content_input,
1022                        section_input,
1023                        as_task,
1024                        focus_field: (focus_field + 1) % 3,
1025                    });
1026                }
1027                KeyCode::BackTab => {
1028                    self.modal = Some(Modal::QuickAppendPrompt {
1029                        content_input,
1030                        section_input,
1031                        as_task,
1032                        focus_field: (focus_field + 2) % 3,
1033                    });
1034                }
1035                KeyCode::Char(' ') if focus_field == 2 => {
1036                    as_task = !as_task;
1037                    self.modal = Some(Modal::QuickAppendPrompt {
1038                        content_input,
1039                        section_input,
1040                        as_task,
1041                        focus_field,
1042                    });
1043                }
1044                KeyCode::Enter => {
1045                    if !content_input.trim().is_empty() {
1046                        let sec = if section_input.trim().is_empty() {
1047                            None
1048                        } else {
1049                            Some(section_input.trim())
1050                        };
1051                        self.append_prompt_content(content_input.trim(), sec, as_task);
1052                    }
1053                    self.modal = None;
1054                }
1055                KeyCode::Char(c) => {
1056                    if focus_field == 0 {
1057                        section_input.push(c);
1058                    } else if focus_field == 1 {
1059                        content_input.push(c);
1060                    }
1061                    self.modal = Some(Modal::QuickAppendPrompt {
1062                        content_input,
1063                        section_input,
1064                        as_task,
1065                        focus_field,
1066                    });
1067                }
1068                KeyCode::Backspace => {
1069                    if focus_field == 0 {
1070                        section_input.pop();
1071                    } else if focus_field == 1 {
1072                        content_input.pop();
1073                    }
1074                    self.modal = Some(Modal::QuickAppendPrompt {
1075                        content_input,
1076                        section_input,
1077                        as_task,
1078                        focus_field,
1079                    });
1080                }
1081                _ => {}
1082            },
1083
1084            Some(Modal::ProjectForm {
1085                id,
1086                mut name_input,
1087                mut desc_input,
1088                focus_desc,
1089            }) => match key {
1090                KeyCode::Esc => self.modal = None,
1091                KeyCode::Tab | KeyCode::BackTab => {
1092                    self.modal = Some(Modal::ProjectForm {
1093                        id,
1094                        name_input,
1095                        desc_input,
1096                        focus_desc: !focus_desc,
1097                    });
1098                }
1099                KeyCode::Enter => {
1100                    if !name_input.trim().is_empty() {
1101                        let input = ProjectInput {
1102                            name: name_input.trim().to_string(),
1103                            description: if desc_input.trim().is_empty() {
1104                                None
1105                            } else {
1106                                Some(desc_input.trim().to_string())
1107                            },
1108                        };
1109
1110                        let res = match id {
1111                            Some(pid) => self.client.update_project(pid, &input),
1112                            None => self.client.create_project(&input),
1113                        };
1114
1115                        match res {
1116                            Ok(p) => {
1117                                self.set_status(format!("Saved project '{}'", p.name), false);
1118                                self.load_stats();
1119                                self.load_projects();
1120                            }
1121                            Err(e) => self.set_status(format!("Project save error: {}", e), true),
1122                        }
1123                    }
1124                    self.modal = None;
1125                }
1126                KeyCode::Char(c) => {
1127                    if focus_desc {
1128                        desc_input.push(c);
1129                    } else {
1130                        name_input.push(c);
1131                    }
1132                    self.modal = Some(Modal::ProjectForm {
1133                        id,
1134                        name_input,
1135                        desc_input,
1136                        focus_desc,
1137                    });
1138                }
1139                KeyCode::Backspace => {
1140                    if focus_desc {
1141                        desc_input.pop();
1142                    } else {
1143                        name_input.pop();
1144                    }
1145                    self.modal = Some(Modal::ProjectForm {
1146                        id,
1147                        name_input,
1148                        desc_input,
1149                        focus_desc,
1150                    });
1151                }
1152                _ => {}
1153            },
1154
1155            Some(Modal::PromptForm {
1156                id,
1157                mut title_input,
1158                project_choice_idx,
1159                mut pinned,
1160                focus_field,
1161            }) => match key {
1162                KeyCode::Esc => self.modal = None,
1163                KeyCode::Tab => {
1164                    let next = (focus_field + 1) % 3;
1165                    self.modal = Some(Modal::PromptForm {
1166                        id,
1167                        title_input,
1168                        project_choice_idx,
1169                        pinned,
1170                        focus_field: next,
1171                    });
1172                }
1173                KeyCode::BackTab => {
1174                    let prev = (focus_field + 2) % 3;
1175                    self.modal = Some(Modal::PromptForm {
1176                        id,
1177                        title_input,
1178                        project_choice_idx,
1179                        pinned,
1180                        focus_field: prev,
1181                    });
1182                }
1183                KeyCode::Left if focus_field == 1 => {
1184                    let next_idx = if project_choice_idx > 0 {
1185                        project_choice_idx - 1
1186                    } else {
1187                        self.projects.len()
1188                    };
1189                    self.modal = Some(Modal::PromptForm {
1190                        id,
1191                        title_input,
1192                        project_choice_idx: next_idx,
1193                        pinned,
1194                        focus_field,
1195                    });
1196                }
1197                KeyCode::Right if focus_field == 1 => {
1198                    let next_idx = (project_choice_idx + 1) % (self.projects.len() + 1);
1199                    self.modal = Some(Modal::PromptForm {
1200                        id,
1201                        title_input,
1202                        project_choice_idx: next_idx,
1203                        pinned,
1204                        focus_field,
1205                    });
1206                }
1207                KeyCode::Char(' ') if focus_field == 2 => {
1208                    pinned = !pinned;
1209                    self.modal = Some(Modal::PromptForm {
1210                        id,
1211                        title_input,
1212                        project_choice_idx,
1213                        pinned,
1214                        focus_field,
1215                    });
1216                }
1217                KeyCode::Enter => {
1218                    if !title_input.trim().is_empty() {
1219                        let selected_pid = if project_choice_idx == 0 {
1220                            None
1221                        } else {
1222                            self.projects.get(project_choice_idx - 1).map(|p| p.id)
1223                        };
1224
1225                        let input = PromptInput {
1226                            title: title_input.trim().to_string(),
1227                            project_id: Some(selected_pid),
1228                            pinned: Some(pinned),
1229                            ..Default::default()
1230                        };
1231
1232                        let res = match id {
1233                            Some(nid) => self.client.update_prompt(nid, &input),
1234                            None => self.client.create_prompt(&input),
1235                        };
1236
1237                        match res {
1238                            Ok(p) => {
1239                                self.set_status(format!("Saved prompt '{}'", p.title), false);
1240                                self.load_stats();
1241                                self.load_projects();
1242                                self.load_pinned_prompts();
1243                                self.load_prompts();
1244                            }
1245                            Err(e) => self.set_status(format!("Prompt save error: {}", e), true),
1246                        }
1247                    }
1248                    self.modal = None;
1249                }
1250                KeyCode::Char(c) if focus_field == 0 => {
1251                    title_input.push(c);
1252                    self.modal = Some(Modal::PromptForm {
1253                        id,
1254                        title_input,
1255                        project_choice_idx,
1256                        pinned,
1257                        focus_field,
1258                    });
1259                }
1260                KeyCode::Backspace if focus_field == 0 => {
1261                    title_input.pop();
1262                    self.modal = Some(Modal::PromptForm {
1263                        id,
1264                        title_input,
1265                        project_choice_idx,
1266                        pinned,
1267                        focus_field,
1268                    });
1269                }
1270                _ => {}
1271            },
1272
1273            Some(Modal::ConfirmDelete { target }) => match key {
1274                KeyCode::Esc | KeyCode::Char('n') => self.modal = None,
1275                KeyCode::Char('y') | KeyCode::Enter => {
1276                    self.modal = None;
1277                    match target {
1278                        DeleteTarget::Project(p) => match self.client.delete_project(p.id) {
1279                            Ok(_) => {
1280                                self.set_status(format!("Deleted project '{}'", p.name), false);
1281                                self.sidebar_selected = 0;
1282                                self.load_stats();
1283                                self.load_projects();
1284                                self.load_pinned_prompts();
1285                                self.load_prompts();
1286                            }
1287                            Err(e) => {
1288                                self.set_status(format!("Delete project error: {}", e), true)
1289                            }
1290                        },
1291                        DeleteTarget::Prompt(p) => match self.client.delete_prompt(p.id) {
1292                            Ok(_) => {
1293                                self.set_status(format!("Deleted prompt '{}'", p.title), false);
1294                                self.load_stats();
1295                                self.load_projects();
1296                                self.load_pinned_prompts();
1297                                self.load_prompts();
1298                            }
1299                            Err(e) => {
1300                                self.set_status(format!("Delete prompt error: {}", e), true)
1301                            }
1302                        },
1303                        DeleteTarget::Attachment {
1304                            prompt_id,
1305                            attachment_id,
1306                            filename,
1307                        } => match self.client.delete_attachment(prompt_id, attachment_id) {
1308                            Ok(_) => {
1309                                self.set_status(format!("Deleted attachment {}", filename), false);
1310                                self.load_stats();
1311                                self.load_current_prompt_detail();
1312                            }
1313                            Err(e) => {
1314                                self.set_status(format!("Delete attachment error: {}", e), true)
1315                            }
1316                        },
1317                    }
1318                }
1319                _ => {}
1320            },
1321
1322            Some(Modal::Attachments {
1323                cursor,
1324                upload_input,
1325                dest_input,
1326            }) => {
1327                let attachments = self
1328                    .current_prompt
1329                    .as_ref()
1330                    .map(|d| d.attachments.clone())
1331                    .unwrap_or_default();
1332
1333                if let Some(mut path_str) = upload_input {
1334                    match key {
1335                        KeyCode::Esc => {
1336                            self.modal = Some(Modal::Attachments {
1337                                cursor,
1338                                upload_input: None,
1339                                dest_input: None,
1340                            });
1341                        }
1342                        KeyCode::Char(c) => {
1343                            path_str.push(c);
1344                            self.modal = Some(Modal::Attachments {
1345                                cursor,
1346                                upload_input: Some(path_str),
1347                                dest_input: None,
1348                            });
1349                        }
1350                        KeyCode::Backspace => {
1351                            path_str.pop();
1352                            self.modal = Some(Modal::Attachments {
1353                                cursor,
1354                                upload_input: Some(path_str),
1355                                dest_input: None,
1356                            });
1357                        }
1358                        KeyCode::Enter => {
1359                            if let Some(prompt) = &self.current_prompt {
1360                                let path = std::path::Path::new(path_str.trim());
1361                                if path.exists() {
1362                                    match self.client.upload_attachment(prompt.id, path) {
1363                                        Ok(_) => {
1364                                            self.set_status("Uploaded attachment", false);
1365                                            self.load_stats();
1366                                            self.load_current_prompt_detail();
1367                                        }
1368                                        Err(e) => {
1369                                            self.set_status(format!("Upload error: {}", e), true)
1370                                        }
1371                                    }
1372                                } else {
1373                                    self.set_status(
1374                                        format!("File not found: {}", path_str),
1375                                        true,
1376                                    );
1377                                }
1378                            }
1379                            self.modal = Some(Modal::Attachments {
1380                                cursor,
1381                                upload_input: None,
1382                                dest_input: None,
1383                            });
1384                        }
1385                        _ => {}
1386                    }
1387                    return;
1388                }
1389
1390                if let Some(mut dest_str) = dest_input {
1391                    match key {
1392                        KeyCode::Esc => {
1393                            self.modal = Some(Modal::Attachments {
1394                                cursor,
1395                                upload_input: None,
1396                                dest_input: None,
1397                            });
1398                        }
1399                        KeyCode::Char(c) => {
1400                            dest_str.push(c);
1401                            self.modal = Some(Modal::Attachments {
1402                                cursor,
1403                                upload_input: None,
1404                                dest_input: Some(dest_str),
1405                            });
1406                        }
1407                        KeyCode::Backspace => {
1408                            dest_str.pop();
1409                            self.modal = Some(Modal::Attachments {
1410                                cursor,
1411                                upload_input: None,
1412                                dest_input: Some(dest_str),
1413                            });
1414                        }
1415                        KeyCode::Enter => {
1416                            if let Some(att) = attachments.get(cursor) {
1417                                let path = std::path::Path::new(dest_str.trim());
1418                                match self.client.download_attachment(&att.url, path) {
1419                                    Ok(_) => self.set_status(
1420                                        format!("Saved attachment to {}", dest_str),
1421                                        false,
1422                                    ),
1423                                    Err(e) => {
1424                                        self.set_status(format!("Download error: {}", e), true)
1425                                    }
1426                                }
1427                            }
1428                            self.modal = Some(Modal::Attachments {
1429                                cursor,
1430                                upload_input: None,
1431                                dest_input: None,
1432                            });
1433                        }
1434                        _ => {}
1435                    }
1436                    return;
1437                }
1438
1439                match key {
1440                    KeyCode::Esc => self.modal = None,
1441                    KeyCode::Char('j') | KeyCode::Down => {
1442                        if !attachments.is_empty() && cursor + 1 < attachments.len() {
1443                            self.modal = Some(Modal::Attachments {
1444                                cursor: cursor + 1,
1445                                upload_input: None,
1446                                dest_input: None,
1447                            });
1448                        }
1449                    }
1450                    KeyCode::Char('k') | KeyCode::Up => {
1451                        if cursor > 0 {
1452                            self.modal = Some(Modal::Attachments {
1453                                cursor: cursor - 1,
1454                                upload_input: None,
1455                                dest_input: None,
1456                            });
1457                        }
1458                    }
1459                    KeyCode::Char('u') => {
1460                        self.modal = Some(Modal::Attachments {
1461                            cursor,
1462                            upload_input: Some(String::new()),
1463                            dest_input: None,
1464                        });
1465                    }
1466                    KeyCode::Char('s') => {
1467                        if let Some(att) = attachments.get(cursor) {
1468                            self.modal = Some(Modal::Attachments {
1469                                cursor,
1470                                upload_input: None,
1471                                dest_input: Some(att.filename.clone()),
1472                            });
1473                        }
1474                    }
1475                    KeyCode::Char('y') => {
1476                        if let Some(att) = attachments.get(cursor) {
1477                            if let Some(cb) = &mut self.clipboard {
1478                                let full_url = if att.url.starts_with("http") {
1479                                    att.url.clone()
1480                                } else {
1481                                    format!("{}{}", self.config.base_url, att.url)
1482                                };
1483                                let _ = cb.set_text(full_url);
1484                                self.set_status("Copied attachment URL to clipboard", false);
1485                            }
1486                        }
1487                    }
1488                    KeyCode::Char('d') => {
1489                        if let Some(att) = attachments.get(cursor) {
1490                            if let Some(prompt) = &self.current_prompt {
1491                                self.modal = Some(Modal::ConfirmDelete {
1492                                    target: DeleteTarget::Attachment {
1493                                        prompt_id: prompt.id,
1494                                        attachment_id: att.id,
1495                                        filename: att.filename.clone(),
1496                                    },
1497                                });
1498                            }
1499                        }
1500                    }
1501                    _ => {}
1502                }
1503            }
1504
1505            Some(Modal::Help) => match key {
1506                KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('?') | KeyCode::Enter => {
1507                    self.modal = None;
1508                }
1509                _ => {}
1510            },
1511
1512            None => {}
1513        }
1514    }
1515}
1516
1517#[cfg(test)]
1518pub mod tests {
1519    use super::*;
1520
1521    #[test]
1522    pub fn test_sort_prompts_pinned_first_and_alphabetical() {
1523        let mut prompts = vec![
1524            Prompt {
1525                id: 1,
1526                project_id: None,
1527                project_name: None,
1528                title: "Zebra Prompt".to_string(),
1529                body: None,
1530                pinned: false,
1531                pinned_position: None,
1532                attachments_count: 0,
1533                created_at: None,
1534                updated_at: None,
1535            },
1536            Prompt {
1537                id: 2,
1538                project_id: None,
1539                project_name: None,
1540                title: "Apple Prompt".to_string(),
1541                body: None,
1542                pinned: false,
1543                pinned_position: None,
1544                attachments_count: 0,
1545                created_at: None,
1546                updated_at: None,
1547            },
1548            Prompt {
1549                id: 3,
1550                project_id: None,
1551                project_name: None,
1552                title: "Banana Prompt (Pinned)".to_string(),
1553                body: None,
1554                pinned: true,
1555                pinned_position: Some(1),
1556                attachments_count: 0,
1557                created_at: None,
1558                updated_at: None,
1559            },
1560        ];
1561
1562        sort_prompts(&mut prompts);
1563
1564        assert_eq!(prompts[0].id, 3); // Pinned prompt first
1565        assert_eq!(prompts[1].id, 2); // Apple Prompt
1566        assert_eq!(prompts[2].id, 1); // Zebra Prompt
1567    }
1568
1569    #[test]
1570    pub fn test_sidebar_items_resolution() {
1571        let cfg = Config::new("http://localhost:3000");
1572        let app = App {
1573            config: cfg.clone(),
1574            client: ApiClient::new(&cfg),
1575            should_quit: false,
1576            pending_editor: None,
1577            status: None,
1578            focused_pane: Pane::Prompts,
1579            view_mode: ViewMode::Preview,
1580            modal: None,
1581            stats: Stats::default(),
1582            preset_hosts: vec![],
1583            projects: vec![Project {
1584                id: 10,
1585                name: "AI Agents".to_string(),
1586                description: None,
1587                prompts_count: 2,
1588                created_at: None,
1589                updated_at: None,
1590            }],
1591            pinned_prompts: vec![Prompt {
1592                id: 99,
1593                project_id: None,
1594                project_name: None,
1595                title: "Pinned System Prompt".to_string(),
1596                body: None,
1597                pinned: true,
1598                pinned_position: Some(1),
1599                attachments_count: 0,
1600                created_at: None,
1601                updated_at: None,
1602            }],
1603            prompts: vec![],
1604            current_prompt: None,
1605            checklist_items: vec![],
1606            sidebar_selected: 0,
1607            prompts_selected: 0,
1608            detail_selected_checklist: None,
1609            detail_scroll: 0,
1610            search_query: None,
1611            clipboard: None,
1612        };
1613
1614        assert_eq!(app.total_sidebar_items(), 5);
1615        assert_eq!(app.get_sidebar_item(0), ScopeItem::All);
1616        assert_eq!(app.get_sidebar_item(1), ScopeItem::Pinned);
1617        assert_eq!(app.get_sidebar_item(2), ScopeItem::Standalone);
1618        assert_eq!(app.get_sidebar_item(3), ScopeItem::Project(app.projects[0].clone()));
1619        assert_eq!(app.get_sidebar_item(4), ScopeItem::PinnedPrompt(app.pinned_prompts[0].clone()));
1620    }
1621}