Skip to main content

wisp/components/app/
mod.rs

1pub mod attachments;
2pub mod git_diff_mode;
3mod plan_review_mode;
4mod screen_router;
5mod view;
6
7use crate::session_loading_buffer::SessionLoadingBuffer;
8use crate::settings::cycle_quick_option;
9use crate::settings::cycle_reasoning_option;
10use crate::settings::resolve_content_padding;
11use crate::settings::resolve_status_line_settings;
12use agent_client_protocol::schema::v1::SessionConfigKind;
13use agent_client_protocol::schema::v1::SessionUpdate;
14pub use git_diff_mode::{GitDiffLoadState, GitDiffMode, GitDiffViewMessage};
15pub use plan_review_mode::{PlanReviewAction, PlanReviewInput, PlanReviewMode};
16use screen_router::ScreenRouter;
17use screen_router::ScreenRouterMessage;
18
19use crate::components::conversation_screen::ConversationScreen;
20use crate::components::conversation_screen::ConversationScreenMessage;
21use crate::components::plan_review::PlanDocument;
22use crate::components::status_line::ContextUsageDisplay;
23use crate::keybindings::Keybindings;
24use crate::settings;
25use crate::settings::overlay::{SettingsMessage, SettingsOverlay};
26use crate::settings::{ResolvedStatusLineSettings, WispSettings};
27use crate::workspace_status::WorkspaceStatus;
28use acp_utils::client::{AcpEvent, AcpPromptHandle};
29use acp_utils::config_meta::SelectOptionMeta;
30use acp_utils::config_option_id::ConfigOptionId;
31use acp_utils::notifications::{AetherCapabilities, ElicitRequestParams, ElicitationAction, ElicitationResponse};
32use agent_client_protocol::Responder;
33use agent_client_protocol::schema::v1::{self as acp, SessionId};
34use attachments::build_attachment_blocks;
35use std::path::{Path, PathBuf};
36use std::time::{Duration, Instant};
37use tui::RendererCommand;
38use tui::{Component, Event, Frame, KeyEvent, ViewContext};
39use utils::plan_review::{PlanReviewDecision, PlanReviewElicitationMeta};
40
41#[derive(Debug, Clone)]
42pub struct PromptAttachment {
43    pub path: PathBuf,
44    pub display_name: String,
45}
46
47/// Result of processing a single ACP event.
48pub enum EventOutcome {
49    Render { commands: Vec<RendererCommand> },
50    DontRender,
51}
52
53impl EventOutcome {
54    pub fn render() -> Self {
55        Self::Render { commands: Vec::new() }
56    }
57
58    pub fn dont_render() -> Self {
59        Self::DontRender
60    }
61}
62
63pub struct AppInfo {
64    pub session_id: SessionId,
65    pub agent_name: String,
66    pub prompt_capabilities: acp::PromptCapabilities,
67    pub session_capabilities: acp::SessionCapabilities,
68    pub config_options: Vec<acp::SessionConfigOption>,
69    pub auth_methods: Vec<acp::AuthMethod>,
70    pub working_dir: PathBuf,
71    pub workspace_status: WorkspaceStatus,
72    pub prompt_handle: AcpPromptHandle,
73    pub settings: WispSettings,
74}
75
76#[doc = include_str!("../../docs/app.md")]
77pub struct App {
78    agent_name: String,
79    context_usage: Option<ContextUsageDisplay>,
80    exit_requested: bool,
81    ctrl_c_pressed_at: Option<Instant>,
82    conversation_screen: ConversationScreen,
83    prompt_capabilities: acp::PromptCapabilities,
84    config_options: Vec<acp::SessionConfigOption>,
85    server_statuses: Vec<acp_utils::notifications::McpServerStatusEntry>,
86    auth_methods: Vec<acp::AuthMethod>,
87    settings_overlay: Option<SettingsOverlay>,
88    screen_router: ScreenRouter,
89    pending_plan_review_response: Option<Responder<ElicitationResponse>>,
90    keybindings: Keybindings,
91    session_id: SessionId,
92    session_loading_buffer: SessionLoadingBuffer,
93    prompt_handle: AcpPromptHandle,
94    working_dir: PathBuf,
95    workspace_status: WorkspaceStatus,
96    content_padding: usize,
97    status_line_settings: ResolvedStatusLineSettings,
98}
99
100impl App {
101    pub fn new(info: AppInfo) -> Self {
102        let AppInfo {
103            session_id,
104            agent_name,
105            prompt_capabilities,
106            session_capabilities,
107            config_options,
108            auth_methods,
109            working_dir,
110            workspace_status,
111            prompt_handle,
112            settings,
113        } = info;
114        let keybindings = Keybindings::default();
115        let content_padding = resolve_content_padding(&settings);
116        let status_line_settings = resolve_status_line_settings(&settings);
117        let capabilities = AetherCapabilities::from_meta(session_capabilities.meta.as_ref());
118        Self {
119            agent_name,
120            context_usage: None,
121            exit_requested: false,
122            ctrl_c_pressed_at: None,
123            conversation_screen: ConversationScreen::new(
124                keybindings.clone(),
125                content_padding,
126                working_dir.clone(),
127                capabilities,
128            ),
129            prompt_capabilities,
130            config_options,
131            server_statuses: Vec::new(),
132            auth_methods,
133            settings_overlay: None,
134            screen_router: ScreenRouter::new(working_dir.clone()),
135            pending_plan_review_response: None,
136            keybindings,
137            session_id,
138            session_loading_buffer: SessionLoadingBuffer::new(),
139            prompt_handle,
140            working_dir,
141            workspace_status,
142            content_padding,
143            status_line_settings,
144        }
145    }
146
147    pub fn exit_requested(&self) -> bool {
148        self.exit_requested
149    }
150
151    pub fn exit_confirmation_active(&self) -> bool {
152        self.ctrl_c_pressed_at.is_some()
153    }
154
155    pub fn has_settings_overlay(&self) -> bool {
156        self.settings_overlay.is_some()
157    }
158
159    pub fn needs_mouse_capture(&self) -> bool {
160        self.settings_overlay.as_ref().is_some_and(SettingsOverlay::needs_mouse_capture)
161            || self.screen_router.is_full_screen_mode()
162    }
163
164    pub fn wants_tick(&self) -> bool {
165        self.conversation_screen.wants_tick() || self.ctrl_c_pressed_at.is_some()
166    }
167
168    fn git_diff_mode_mut(&mut self) -> &mut GitDiffMode {
169        self.screen_router.git_diff_mode_mut()
170    }
171
172    pub fn on_acp_event(&mut self, event: AcpEvent) -> EventOutcome {
173        let mut commands = Vec::new();
174        match event {
175            AcpEvent::SessionUpdate { session_id, update } => {
176                return self.on_acp_session_update(&session_id, *update);
177            }
178            AcpEvent::ContextCleared(_) => {
179                self.conversation_screen.reset_after_context_cleared();
180                self.context_usage = None;
181            }
182            AcpEvent::ContextCompaction(params) => {
183                self.conversation_screen.set_compaction_active(params.active);
184            }
185            AcpEvent::ContextUsage(params) => {
186                self.context_usage = params
187                    .usage
188                    .context_limit
189                    .filter(|limit| *limit > 0)
190                    .map(|limit| ContextUsageDisplay::new(params.usage.input_tokens, limit));
191            }
192            AcpEvent::SubAgentProgress(progress) => self.conversation_screen.on_sub_agent_progress(&progress),
193            AcpEvent::AuthMethodsUpdated(params) => self.update_auth_methods(params.auth_methods),
194            AcpEvent::McpNotification(notification) => self.on_mcp_notification(notification),
195            AcpEvent::PromptDone(stop_reason) => self.on_prompt_done(stop_reason, &mut commands),
196            AcpEvent::PromptError(error) => {
197                self.session_loading_buffer.clear();
198                self.conversation_screen.on_prompt_error(&error);
199            }
200            AcpEvent::ElicitationRequest { params, responder } => self.on_elicitation_request(params, responder),
201            AcpEvent::AuthenticateComplete { method_id } => self.on_authenticate_complete(&method_id),
202            AcpEvent::AuthenticateFailed { method_id, error } => self.on_authenticate_failed(&method_id, &error),
203            AcpEvent::ConfigOptionUpdateFailed { error } => {
204                tracing::warn!("set_session_config_option failed: {error}");
205                self.conversation_screen
206                    .conversation
207                    .push_user_message(&format!("[wisp] Failed to update setting: {error}"));
208            }
209            AcpEvent::SessionsListed { sessions } => {
210                let current_id = &self.session_id;
211                let filtered: Vec<_> = sessions.into_iter().filter(|s| s.session_id != *current_id).collect();
212                let messages = self.conversation_screen.open_session_picker(filtered);
213                self.handle_conversation_messages_sync(messages);
214            }
215            // SessionLoaded intentionally does NOT restore previous config selections:
216            // when the user loads an existing session, the server's stored config for
217            // that session is authoritative.
218            AcpEvent::SessionLoaded { session_id, config_options } => {
219                let replay_updates = self.session_loading_buffer.take(&session_id);
220                self.session_id = session_id;
221                self.conversation_screen.on_workspace_move_finished();
222                for update in replay_updates {
223                    self.on_session_update(&update);
224                }
225                self.update_config_options(&config_options);
226            }
227            AcpEvent::NewSessionCreated { session_id, config_options } => {
228                self.session_loading_buffer.clear();
229                let previous_selections = current_config_selections(&self.config_options);
230                self.session_id = session_id;
231                self.update_config_options(&config_options);
232                self.context_usage = None;
233                self.restore_config_selections(&previous_selections);
234            }
235            AcpEvent::ConnectionClosed => {
236                self.session_loading_buffer.clear();
237                self.exit_requested = true;
238            }
239            AcpEvent::PromptSearchResults(response) => {
240                self.conversation_screen.on_prompt_search_results(response);
241            }
242            AcpEvent::PromptSearchFailed { query, error } => {
243                self.conversation_screen.on_prompt_search_failed(&query, error);
244            }
245            AcpEvent::SessionPreviewLoaded(preview) => {
246                self.conversation_screen.on_session_preview_loaded(preview);
247            }
248            AcpEvent::SessionPreviewFailed { session_id, error } => {
249                self.conversation_screen.on_session_preview_failed(&session_id, error);
250            }
251            AcpEvent::WorkspacesListed(response) => {
252                self.conversation_screen.open_workspace_picker(response.workspaces);
253            }
254            AcpEvent::WorkspaceListFailed { error } => {
255                self.conversation_screen.on_workspace_list_failed(&error);
256            }
257            AcpEvent::WorkspaceMoved(response) => {
258                self.on_workspace_moved(&response.new_cwd, &mut commands);
259            }
260            AcpEvent::WorkspaceMoveFailed { error } => {
261                self.conversation_screen.on_workspace_move_failed(&error);
262            }
263        }
264        EventOutcome::Render { commands }
265    }
266
267    fn on_workspace_moved(&mut self, new_cwd: &Path, commands: &mut Vec<RendererCommand>) {
268        self.working_dir = new_cwd.to_path_buf();
269        self.conversation_screen.set_working_dir(new_cwd.to_path_buf());
270        self.workspace_status = WorkspaceStatus::resolve(new_cwd);
271        self.screen_router.set_git_diff_working_dir(new_cwd.to_path_buf());
272
273        self.conversation_screen.reset_after_context_cleared();
274        commands.push(RendererCommand::ClearScreen);
275        let session_id = self.session_id.clone();
276        if self.start_session_load(&session_id, new_cwd) {
277            self.conversation_screen.on_workspace_session_loading();
278        } else {
279            self.conversation_screen.on_workspace_move_finished();
280        }
281    }
282
283    fn start_session_load(&mut self, session_id: &SessionId, cwd: &Path) -> bool {
284        self.session_loading_buffer.begin_load(session_id.clone());
285        if let Err(e) = self.prompt_handle.load_session(session_id, cwd) {
286            self.session_loading_buffer.remove(session_id);
287            tracing::warn!("Failed to load session: {e}");
288            return false;
289        }
290        true
291    }
292
293    async fn handle_key(&mut self, commands: &mut Vec<RendererCommand>, key_event: KeyEvent) {
294        if self.keybindings.exit.matches(key_event) {
295            if self.ctrl_c_pressed_at.is_some() {
296                self.exit_requested = true;
297            } else {
298                self.conversation_screen.clear_prompt_composer();
299                self.ctrl_c_pressed_at = Some(Instant::now());
300            }
301            return;
302        }
303
304        if self.keybindings.toggle_git_diff.matches(key_event) && !self.conversation_screen.has_modal() {
305            if let Some(msg) = self.screen_router.toggle_git_diff() {
306                self.handle_screen_router_message(commands, msg).await;
307            }
308            return;
309        }
310
311        let event = Event::Key(key_event);
312
313        if self.screen_router.is_full_screen_mode() {
314            for msg in self.screen_router.on_event(&event).await.unwrap_or_default() {
315                self.handle_screen_router_message(commands, msg).await;
316            }
317        } else if self.settings_overlay.is_some() {
318            self.handle_settings_overlay_event(commands, &event).await;
319        } else {
320            let outcome = self.conversation_screen.on_event(&event).await;
321            let consumed = outcome.is_some();
322            self.handle_conversation_messages(commands, outcome).await;
323            if !consumed {
324                self.handle_fallthrough_keybindings(key_event);
325            }
326        }
327    }
328
329    async fn submit_prompt(&mut self, user_input: String, attachments: Vec<PromptAttachment>) {
330        let outcome = build_attachment_blocks(&attachments).await;
331        self.conversation_screen.conversation.push_user_message("");
332        self.conversation_screen.conversation.push_user_message(&user_input);
333        for placeholder in &outcome.transcript_placeholders {
334            self.conversation_screen.conversation.push_user_message(placeholder);
335        }
336        for w in outcome.warnings {
337            self.conversation_screen.conversation.push_user_message(&format!("[wisp] {w}"));
338        }
339
340        if let Some(message) = self.media_support_error(&outcome.blocks) {
341            self.conversation_screen.reject_local_prompt(&message);
342            return;
343        }
344
345        let _ = self.prompt_handle.prompt(
346            &self.session_id,
347            &user_input,
348            if outcome.blocks.is_empty() { None } else { Some(outcome.blocks) },
349        );
350    }
351
352    async fn handle_conversation_messages(
353        &mut self,
354        commands: &mut Vec<RendererCommand>,
355        outcome: Option<Vec<ConversationScreenMessage>>,
356    ) {
357        for msg in outcome.unwrap_or_default() {
358            match msg {
359                ConversationScreenMessage::SendPrompt { user_input, attachments } => {
360                    self.conversation_screen.on_prompt_sent();
361                    self.submit_prompt(user_input, attachments).await;
362                }
363                ConversationScreenMessage::ClearScreen => {
364                    commands.push(RendererCommand::ClearScreen);
365                }
366                ConversationScreenMessage::NewSession => {
367                    commands.push(RendererCommand::ClearScreen);
368                    let _ = self.prompt_handle.new_session(&self.working_dir);
369                }
370                ConversationScreenMessage::OpenSettings => {
371                    self.open_settings_overlay();
372                }
373                ConversationScreenMessage::OpenSessionPicker => {
374                    let _ = self.prompt_handle.list_sessions();
375                }
376                ConversationScreenMessage::OpenWorkspacePicker => {
377                    if let Err(e) = self.prompt_handle.list_workspaces(&self.session_id) {
378                        self.conversation_screen.on_workspace_list_failed(&e.to_string());
379                        tracing::warn!("Failed to request workspace list: {e}");
380                    }
381                }
382                ConversationScreenMessage::MoveWorkspace { target } => {
383                    self.conversation_screen.on_workspace_move_started();
384                    if let Err(e) = self.prompt_handle.move_workspace(&self.session_id, target) {
385                        self.conversation_screen.on_workspace_move_failed(&e.to_string());
386                        tracing::warn!("Failed to request workspace move: {e}");
387                    }
388                }
389                ConversationScreenMessage::LoadSession { session_id, cwd } => {
390                    self.start_session_load(&session_id, &cwd);
391                }
392                ConversationScreenMessage::SearchPrompts(params) => {
393                    if let Err(e) = self.prompt_handle.search_prompts(params) {
394                        tracing::warn!("Failed to send prompt search: {e}");
395                    }
396                }
397                ConversationScreenMessage::RequestSessionPreview { session_id } => {
398                    self.request_session_preview(&session_id);
399                }
400            }
401        }
402    }
403
404    fn handle_conversation_messages_sync(&mut self, messages: Vec<ConversationScreenMessage>) {
405        for msg in messages {
406            if let ConversationScreenMessage::RequestSessionPreview { session_id } = msg {
407                self.request_session_preview(&session_id);
408            }
409        }
410    }
411
412    fn request_session_preview(&self, session_id: &SessionId) {
413        if let Err(e) = self.prompt_handle.session_preview(session_id) {
414            tracing::warn!("Failed to send session preview request: {e}");
415        }
416    }
417
418    fn handle_fallthrough_keybindings(&mut self, key_event: KeyEvent) {
419        if self.keybindings.cycle_reasoning.matches(key_event) {
420            if let Some((id, val)) = cycle_reasoning_option(&self.config_options)
421                && self.prompt_handle.set_config_option(&self.session_id, &id, &val).is_ok()
422            {
423                self.update_config_option_value(&id, &val);
424            }
425            return;
426        }
427
428        if self.keybindings.cycle_mode.matches(key_event) {
429            if let Some((id, val)) = cycle_quick_option(&self.config_options)
430                && self.prompt_handle.set_config_option(&self.session_id, &id, &val).is_ok()
431            {
432                self.update_config_option_value(&id, &val);
433            }
434            return;
435        }
436
437        if self.keybindings.cancel.matches(key_event)
438            && self.conversation_screen.is_busy()
439            && let Err(e) = self.prompt_handle.cancel(&self.session_id)
440        {
441            tracing::warn!("Failed to send cancel: {e}");
442        }
443    }
444
445    async fn handle_settings_overlay_event(&mut self, commands: &mut Vec<RendererCommand>, event: &Event) {
446        let Some(ref mut overlay) = self.settings_overlay else {
447            return;
448        };
449        let messages = overlay.on_event(event).await.unwrap_or_default();
450
451        for msg in messages {
452            match msg {
453                SettingsMessage::Close => {
454                    self.settings_overlay = None;
455                    return;
456                }
457                SettingsMessage::SetConfigOption { config_id, value } => {
458                    let _ = self.prompt_handle.set_config_option(&self.session_id, &config_id, &value);
459                }
460                SettingsMessage::SetTheme(theme) => {
461                    commands.push(RendererCommand::SetTheme(theme));
462                }
463                SettingsMessage::AuthenticateServer(name) => {
464                    let _ = self.prompt_handle.authenticate_mcp_server(&self.session_id, &name);
465                }
466                SettingsMessage::AuthenticateProvider(ref method_id) => {
467                    if let Some(ref mut overlay) = self.settings_overlay {
468                        overlay.on_authenticate_started(method_id);
469                    }
470                    let _ = self.prompt_handle.authenticate(method_id);
471                }
472            }
473        }
474    }
475
476    fn open_settings_overlay(&mut self) {
477        self.settings_overlay =
478            Some(settings::create_overlay(&self.config_options, &self.server_statuses, &self.auth_methods));
479    }
480
481    fn update_config_options(&mut self, config_options: &[acp::SessionConfigOption]) {
482        self.config_options = config_options.to_vec();
483        if let Some(ref mut overlay) = self.settings_overlay {
484            overlay.update_config_options(config_options);
485        }
486    }
487
488    fn update_config_option_value(&mut self, config_id: &str, value: &str) {
489        let Some(option) = self.config_options.iter_mut().find(|option| option.id.0.as_ref() == config_id) else {
490            return;
491        };
492
493        let SessionConfigKind::Select(select) = &mut option.kind else {
494            return;
495        };
496
497        select.current_value = value.to_string().into();
498    }
499
500    fn update_auth_methods(&mut self, auth_methods: Vec<acp::AuthMethod>) {
501        self.auth_methods = auth_methods;
502        if let Some(ref mut overlay) = self.settings_overlay {
503            overlay.update_auth_methods(self.auth_methods.clone());
504        }
505    }
506
507    fn restore_config_selections(&self, previous: &[(String, String)]) {
508        let new_selections = current_config_selections(&self.config_options);
509        for (id, old_value) in previous {
510            let still_exists = new_selections.iter().any(|(new_id, _)| new_id == id);
511            if !still_exists {
512                tracing::debug!(config_id = id, "config option no longer present in new session");
513                continue;
514            }
515            let server_reset = new_selections.iter().any(|(new_id, new_val)| new_id == id && new_val != old_value);
516            if server_reset && let Err(e) = self.prompt_handle.set_config_option(&self.session_id, id, old_value) {
517                tracing::warn!(config_id = id, error = %e, "failed to restore config option");
518            }
519        }
520    }
521
522    async fn handle_screen_router_message(&mut self, commands: &mut Vec<RendererCommand>, msg: ScreenRouterMessage) {
523        match msg {
524            ScreenRouterMessage::LoadGitDiff | ScreenRouterMessage::RefreshGitDiff => {
525                self.git_diff_mode_mut().complete_load().await;
526            }
527            ScreenRouterMessage::SendPrompt { user_input } => {
528                if self.conversation_screen.is_waiting() {
529                    return;
530                }
531
532                self.conversation_screen.on_prompt_sent();
533                self.submit_prompt(user_input, Vec::new()).await;
534                self.screen_router.close_git_diff();
535            }
536            ScreenRouterMessage::FinishPlanReview(action) => {
537                let response = plan_review_response(action);
538                if let Some(responder) = self.pending_plan_review_response.take() {
539                    let _ = responder.respond(response);
540                }
541            }
542        }
543        let _ = commands;
544    }
545
546    fn on_acp_session_update(&mut self, session_id: &SessionId, update: SessionUpdate) -> EventOutcome {
547        let Some(update) = self.session_loading_buffer.push(session_id, update) else {
548            return EventOutcome::dont_render();
549        };
550        self.on_session_update(&update);
551        EventOutcome::render()
552    }
553
554    fn on_session_update(&mut self, update: &acp::SessionUpdate) {
555        self.conversation_screen.on_session_update(update);
556
557        if let acp::SessionUpdate::ConfigOptionUpdate(config_update) = update {
558            self.update_config_options(&config_update.config_options);
559        }
560    }
561
562    fn on_prompt_done(&mut self, stop_reason: acp::StopReason, commands: &mut Vec<RendererCommand>) {
563        let was_waiting = self.conversation_screen.is_waiting();
564        let cancelled = matches!(stop_reason, acp::StopReason::Cancelled);
565        self.conversation_screen.on_prompt_done(stop_reason);
566        if was_waiting && !cancelled {
567            commands.push(RendererCommand::Bell);
568        }
569    }
570
571    fn on_elicitation_request(
572        &mut self,
573        params: acp_utils::notifications::ElicitationParams,
574        responder: Responder<ElicitationResponse>,
575    ) {
576        if let Some(meta) = plan_review_meta_from_request(&params.request) {
577            self.settings_overlay = None;
578            if let Some(existing) = self.pending_plan_review_response.replace(responder) {
579                let _ = existing.respond(cancel_response());
580            }
581            let document = PlanDocument::parse(meta.plan_path, &meta.markdown);
582            let input = PlanReviewInput { title: meta.title, document };
583            self.screen_router.open_plan_review(input);
584            return;
585        }
586
587        if let Some(ref mut overlay) = self.settings_overlay {
588            overlay.on_elicitation_request(params, responder);
589        } else {
590            self.conversation_screen.on_elicitation_request(params, responder);
591        }
592    }
593
594    fn on_mcp_notification(&mut self, notification: acp_utils::notifications::McpNotification) {
595        use acp_utils::notifications::McpNotification;
596        match notification {
597            McpNotification::ServerStatus { servers } => {
598                if let Some(ref mut overlay) = self.settings_overlay {
599                    overlay.update_server_statuses(servers.clone());
600                }
601                self.server_statuses = servers;
602            }
603        }
604    }
605
606    fn on_authenticate_complete(&mut self, method_id: &str) {
607        if let Some(ref mut overlay) = self.settings_overlay {
608            overlay.on_authenticate_complete(method_id);
609        }
610    }
611
612    fn on_authenticate_failed(&mut self, method_id: &str, error: &str) {
613        tracing::warn!("Provider auth failed for {method_id}: {error}");
614        if let Some(ref mut overlay) = self.settings_overlay {
615            overlay.on_authenticate_failed(method_id);
616        }
617    }
618
619    fn media_support_error(&self, blocks: &[acp::ContentBlock]) -> Option<String> {
620        let requires_image = blocks.iter().any(|block| matches!(block, acp::ContentBlock::Image(_)));
621        let requires_audio = blocks.iter().any(|block| matches!(block, acp::ContentBlock::Audio(_)));
622
623        if !requires_image && !requires_audio {
624            return None;
625        }
626
627        if requires_image && !self.prompt_capabilities.image {
628            return Some("ACP agent does not support image input.".to_string());
629        }
630        if requires_audio && !self.prompt_capabilities.audio {
631            return Some("ACP agent does not support audio input.".to_string());
632        }
633
634        let option =
635            self.config_options.iter().find(|option| option.id.0.as_ref() == ConfigOptionId::Model.as_str())?;
636        let acp::SessionConfigKind::Select(select) = &option.kind else {
637            return None;
638        };
639
640        let values: Vec<_> =
641            select.current_value.0.split(',').map(str::trim).filter(|value| !value.is_empty()).collect();
642
643        if values.is_empty() {
644            return None;
645        }
646
647        let acp::SessionConfigSelectOptions::Ungrouped(options) = &select.options else {
648            return None;
649        };
650
651        let selected_meta: Vec<_> = values
652            .iter()
653            .filter_map(|value| {
654                options
655                    .iter()
656                    .find(|option| option.value.0.as_ref() == *value)
657                    .map(|option| SelectOptionMeta::from_meta(option.meta.as_ref()))
658            })
659            .collect();
660
661        if selected_meta.len() != values.len() {
662            return Some("Current model selection is missing prompt capability metadata.".into());
663        }
664
665        if requires_image && selected_meta.iter().any(|meta| !meta.supports_image) {
666            return Some("Current model selection does not support image input.".to_string());
667        }
668        if requires_audio && selected_meta.iter().any(|meta| !meta.supports_audio) {
669            return Some("Current model selection does not support audio input.".to_string());
670        }
671
672        None
673    }
674}
675
676impl Component for App {
677    type Message = RendererCommand;
678
679    async fn on_event(&mut self, event: &Event) -> Option<Vec<RendererCommand>> {
680        let mut commands = Vec::new();
681        match event {
682            Event::Key(key_event) => self.handle_key(&mut commands, *key_event).await,
683            Event::Paste(_) => {
684                self.settings_overlay = None;
685                if self.screen_router.is_full_screen_mode() {
686                    for msg in self.screen_router.on_event(event).await.unwrap_or_default() {
687                        self.handle_screen_router_message(&mut commands, msg).await;
688                    }
689                } else {
690                    let outcome = self.conversation_screen.on_event(event).await;
691                    self.handle_conversation_messages(&mut commands, outcome).await;
692                }
693            }
694            Event::Tick => {
695                if let Some(instant) = self.ctrl_c_pressed_at
696                    && instant.elapsed() > Duration::from_secs(1)
697                {
698                    self.ctrl_c_pressed_at = None;
699                }
700                let now = Instant::now();
701                self.conversation_screen.on_tick(now);
702            }
703            Event::Mouse(_) => {
704                if self.screen_router.is_full_screen_mode() {
705                    for msg in self.screen_router.on_event(event).await.unwrap_or_default() {
706                        self.handle_screen_router_message(&mut commands, msg).await;
707                    }
708                } else if self.settings_overlay.is_some() {
709                    self.handle_settings_overlay_event(&mut commands, event).await;
710                } else if self.conversation_screen.has_modal() {
711                    let outcome = self.conversation_screen.on_event(event).await;
712                    self.handle_conversation_messages(&mut commands, outcome).await;
713                }
714            }
715            Event::Resize(_) => {}
716        }
717        Some(commands)
718    }
719
720    fn render(&mut self, ctx: &ViewContext) -> Frame {
721        self.conversation_screen.refresh_caches(ctx);
722
723        let height = (ctx.size.height.saturating_sub(1)) as usize;
724        if let Some(ref mut overlay) = self.settings_overlay
725            && height >= 3
726        {
727            overlay.update_child_viewport(height.saturating_sub(4));
728        }
729
730        view::build_frame(self, ctx)
731    }
732}
733
734fn plan_review_meta_from_request(request: &ElicitRequestParams) -> Option<PlanReviewElicitationMeta> {
735    match request {
736        ElicitRequestParams::FormElicitationParams { meta, .. } => {
737            PlanReviewElicitationMeta::parse(meta.as_ref().map(|meta| &meta.0.0))
738        }
739        _ => None,
740    }
741}
742
743fn plan_review_response(action: PlanReviewAction) -> ElicitationResponse {
744    match action {
745        PlanReviewAction::Approve => ElicitationResponse {
746            action: ElicitationAction::Accept,
747            content: Some(PlanReviewDecision::Approve.response_content(None)),
748        },
749        PlanReviewAction::RequestChanges { feedback } => ElicitationResponse {
750            action: ElicitationAction::Accept,
751            content: Some(PlanReviewDecision::Deny.response_content(Some(&feedback))),
752        },
753        PlanReviewAction::Cancel => cancel_response(),
754    }
755}
756
757fn cancel_response() -> ElicitationResponse {
758    ElicitationResponse { action: ElicitationAction::Cancel, content: None }
759}
760
761fn current_config_selections(options: &[acp::SessionConfigOption]) -> Vec<(String, String)> {
762    options
763        .iter()
764        .filter_map(|opt| {
765            let acp::SessionConfigKind::Select(ref select) = opt.kind else {
766                return None;
767            };
768            Some((opt.id.0.to_string(), select.current_value.0.to_string()))
769        })
770        .collect()
771}
772
773#[cfg(test)]
774pub(crate) mod test_helpers {
775    use crate::settings::StatusLineSettings;
776
777    use super::*;
778    use acp_utils::client::PromptCommand;
779    use tokio::sync::mpsc;
780
781    pub fn test_workspace_status() -> WorkspaceStatus {
782        WorkspaceStatus::new("~/code/foo", Some("main".to_string()))
783    }
784
785    pub fn make_app() -> App {
786        make_app_with_options("test", acp::PromptCapabilities::new(), &[], vec![], AcpPromptHandle::noop())
787    }
788
789    pub fn make_app_with_config(config_options: &[acp::SessionConfigOption]) -> App {
790        make_app_with_options("test", acp::PromptCapabilities::new(), config_options, vec![], AcpPromptHandle::noop())
791    }
792
793    pub fn make_app_with_auth(auth_methods: Vec<acp::AuthMethod>) -> App {
794        make_app_with_options("test", acp::PromptCapabilities::new(), &[], auth_methods, AcpPromptHandle::noop())
795    }
796
797    pub fn make_app_with_config_recording(
798        config_options: &[acp::SessionConfigOption],
799    ) -> (App, mpsc::UnboundedReceiver<PromptCommand>) {
800        let (handle, rx) = AcpPromptHandle::recording();
801        let app = make_app_with_options("test", acp::PromptCapabilities::new(), config_options, vec![], handle);
802        (app, rx)
803    }
804
805    pub fn make_app_with_session_id(session_id: &str) -> App {
806        make_app_with_options(session_id, acp::PromptCapabilities::new(), &[], vec![], AcpPromptHandle::noop())
807    }
808
809    pub fn make_app_with_config_and_capabilities_recording(
810        config_options: &[acp::SessionConfigOption],
811        prompt_capabilities: acp::PromptCapabilities,
812    ) -> (App, mpsc::UnboundedReceiver<PromptCommand>) {
813        let (handle, rx) = AcpPromptHandle::recording();
814        let app = make_app_with_options("test", prompt_capabilities, config_options, vec![], handle);
815        (app, rx)
816    }
817
818    fn make_app_with_options(
819        session_id: &str,
820        prompt_capabilities: acp::PromptCapabilities,
821        config_options: &[acp::SessionConfigOption],
822        auth_methods: Vec<acp::AuthMethod>,
823        prompt_handle: AcpPromptHandle,
824    ) -> App {
825        App::new(AppInfo {
826            session_id: SessionId::new(session_id),
827            agent_name: "test-agent".to_string(),
828            prompt_capabilities,
829            session_capabilities: acp::SessionCapabilities::new().meta(Some(
830                AetherCapabilities { prompt_search: true, session_preview: true, workspace_move: true }.to_meta(),
831            )),
832            config_options: config_options.to_vec(),
833            auth_methods,
834            working_dir: PathBuf::from("."),
835            workspace_status: test_workspace_status(),
836            prompt_handle,
837            settings: WispSettings::default().with_default_status_line(StatusLineSettings::defaults()),
838        })
839    }
840}
841
842#[cfg(test)]
843mod tests {
844    use super::test_helpers::*;
845    use super::*;
846    use crate::components::command_picker::CommandEntry;
847    use crate::components::conversation_screen::Modal;
848    use crate::components::conversation_window::SegmentContent;
849    use crate::components::elicitation_form::ElicitationForm;
850    use crate::components::progress_indicator::ProgressActivity;
851    use crate::settings::{DEFAULT_CONTENT_PADDING, save_settings};
852    use crate::settings::{ThemeSettings, WispSettings};
853    use crate::test_helpers::{elicitation_params, modified_key, url_elicitation_params, with_wisp_home};
854    use acp_utils::ElicitationSchema;
855    use acp_utils::testing::test_connection;
856    use std::fs;
857    use std::path::Path;
858    use std::time::Duration;
859    use tempfile::TempDir;
860    use tokio::task::LocalSet;
861    use tui::testing::render_component;
862    use tui::{Frame, KeyCode, KeyModifiers, Renderer, Theme, ViewContext};
863    use utils::plan_review::PlanReviewElicitationMeta;
864
865    fn make_renderer() -> Renderer<Vec<u8>> {
866        Renderer::new(Vec::new(), Theme::default(), (80, 24))
867    }
868
869    fn render_app(renderer: &mut Renderer<Vec<u8>>, app: &mut App, context: &ViewContext) -> Frame {
870        renderer.render_frame(|ctx| app.render(ctx)).unwrap();
871        app.render(context)
872    }
873
874    fn frame_contains(output: &Frame, text: &str) -> bool {
875        output.lines().iter().any(|line| line.plain_text().contains(text))
876    }
877
878    async fn send_key(app: &mut App, code: KeyCode, modifiers: KeyModifiers) {
879        app.on_event(&modified_key(code, modifiers)).await;
880    }
881
882    fn setup_themes_dir(files: &[&str]) -> TempDir {
883        let temp_dir = TempDir::new().unwrap();
884        let themes_dir = temp_dir.path().join("themes");
885        fs::create_dir_all(&themes_dir).unwrap();
886        for f in files {
887            fs::write(themes_dir.join(f), "x").unwrap();
888        }
889        temp_dir
890    }
891
892    fn make_plan_entry(name: &str, status: acp::PlanEntryStatus) -> acp::PlanEntry {
893        acp::PlanEntry::new(name, acp::PlanEntryPriority::Medium, status)
894    }
895
896    fn make_plan_review_params(markdown: &str) -> acp_utils::notifications::ElicitationParams {
897        let meta = PlanReviewElicitationMeta::new(Path::new("/tmp/test-plan.md"), markdown)
898            .to_json()
899            .expect("serialize plan review metadata");
900
901        acp_utils::notifications::ElicitationParams {
902            server_name: "plan-server".to_string(),
903            request: acp_utils::notifications::ElicitRequestParams::FormElicitationParams {
904                meta: Some(
905                    serde_json::from_value(serde_json::Value::Object(meta))
906                        .expect("deserialize plan review metadata into rmcp meta"),
907                ),
908                message: "Approve plan?".to_string(),
909                requested_schema: acp_utils::ElicitationSchema::builder()
910                    .required_string("decision")
911                    .optional_string("feedback")
912                    .build()
913                    .expect("build plan review requested schema"),
914            },
915        }
916    }
917
918    fn mode_model_options(
919        current_mode: impl Into<String>,
920        current_model: impl Into<String>,
921    ) -> Vec<acp::SessionConfigOption> {
922        vec![
923            acp::SessionConfigOption::select(
924                "mode",
925                "Mode",
926                current_mode.into(),
927                vec![
928                    acp::SessionConfigSelectOption::new("Planner", "Planner"),
929                    acp::SessionConfigSelectOption::new("Coder", "Coder"),
930                ],
931            )
932            .category(acp::SessionConfigOptionCategory::Mode),
933            acp::SessionConfigOption::select(
934                "model",
935                "Model",
936                current_model.into(),
937                vec![
938                    acp::SessionConfigSelectOption::new("gpt-4o", "GPT-4o"),
939                    acp::SessionConfigSelectOption::new("claude", "Claude"),
940                ],
941            )
942            .category(acp::SessionConfigOptionCategory::Model),
943        ]
944    }
945
946    fn image_model_options() -> Vec<acp::SessionConfigOption> {
947        vec![
948            acp::SessionConfigOption::select(
949                "model",
950                "Model",
951                "anthropic:claude-sonnet-4-5",
952                vec![
953                    acp::SessionConfigSelectOption::new("anthropic:claude-sonnet-4-5", "Claude Sonnet").meta(
954                        SelectOptionMeta { reasoning_levels: vec![], supports_image: true, supports_audio: false }
955                            .into_meta(),
956                    ),
957                    acp::SessionConfigSelectOption::new("deepseek:deepseek-chat", "DeepSeek").meta(
958                        SelectOptionMeta { reasoning_levels: vec![], supports_image: false, supports_audio: false }
959                            .into_meta(),
960                    ),
961                ],
962            )
963            .category(acp::SessionConfigOptionCategory::Model),
964        ]
965    }
966
967    #[test]
968    fn settings_overlay_with_themes() {
969        let temp_dir = setup_themes_dir(&["sage.tmTheme"]);
970        with_wisp_home(temp_dir.path(), || {
971            let mut app = make_app();
972            app.open_settings_overlay();
973            assert!(app.settings_overlay.is_some());
974        });
975
976        let temp_dir = setup_themes_dir(&["sage.tmTheme", "nord.tmTheme"]);
977        with_wisp_home(temp_dir.path(), || {
978            let settings =
979                WispSettings { theme: ThemeSettings { file: Some("nord.tmTheme".to_string()) }, ..Default::default() };
980            save_settings(&settings).unwrap();
981            let mut app = make_app();
982            app.open_settings_overlay();
983            assert!(app.settings_overlay.is_some());
984        });
985    }
986
987    #[test]
988    fn command_picker_cursor_stays_in_input_prompt() {
989        let mut app = make_app();
990        let mut renderer = make_renderer();
991        app.conversation_screen.prompt_composer.open_command_picker_with_entries(vec![CommandEntry {
992            name: "settings".to_string(),
993            description: "Open settings".to_string(),
994            has_input: false,
995            hint: None,
996            builtin: true,
997        }]);
998
999        let context = ViewContext::new((120, 40));
1000        let output = render_app(&mut renderer, &mut app, &context);
1001        let input_row =
1002            output.lines().iter().position(|line| line.plain_text().contains("> ")).expect("input prompt should exist");
1003        assert_eq!(output.cursor().row, input_row);
1004    }
1005
1006    #[test]
1007    fn settings_overlay_replaces_conversation_window() {
1008        let options = vec![acp::SessionConfigOption::select(
1009            "model",
1010            "Model",
1011            "m1",
1012            vec![acp::SessionConfigSelectOption::new("m1", "M1")],
1013        )];
1014        let mut app = make_app_with_config(&options);
1015        let mut renderer = make_renderer();
1016        app.open_settings_overlay();
1017
1018        let ctx = ViewContext::new((120, 40));
1019        assert!(frame_contains(&render_app(&mut renderer, &mut app, &ctx), "Configuration"));
1020        app.settings_overlay = None;
1021        assert!(!frame_contains(&render_app(&mut renderer, &mut app, &ctx), "Configuration"));
1022    }
1023
1024    #[test]
1025    fn extract_model_display_handles_comma_separated_value() {
1026        use crate::components::status_line::extract_model_display;
1027        let options = vec![acp::SessionConfigOption::select(
1028            "model",
1029            "Model",
1030            "a:x,b:y",
1031            vec![
1032                acp::SessionConfigSelectOption::new("a:x", "Alpha / X"),
1033                acp::SessionConfigSelectOption::new("b:y", "Beta / Y"),
1034                acp::SessionConfigSelectOption::new("c:z", "Gamma / Z"),
1035            ],
1036        )];
1037        assert_eq!(extract_model_display(&options).as_deref(), Some("Alpha / X + Beta / Y"));
1038    }
1039
1040    #[test]
1041    fn extract_reasoning_effort_returns_none_for_none_value() {
1042        use crate::components::status_line::extract_reasoning_effort;
1043        use acp_utils::config_option_id::ConfigOptionId;
1044        let options = vec![acp::SessionConfigOption::select(
1045            ConfigOptionId::ReasoningEffort.as_str(),
1046            "Reasoning",
1047            "none",
1048            vec![
1049                acp::SessionConfigSelectOption::new("none", "None"),
1050                acp::SessionConfigSelectOption::new("low", "Low"),
1051            ],
1052        )];
1053        assert_eq!(extract_reasoning_effort(&options), None);
1054    }
1055
1056    #[test]
1057    fn render_hides_plan_header_when_no_entries_are_visible() {
1058        let mut app = make_app();
1059        let mut renderer = make_renderer();
1060        let grace_period = app.conversation_screen.plan_tracker.grace_period;
1061        app.conversation_screen.plan_tracker.replace(
1062            vec![make_plan_entry("1", acp::PlanEntryStatus::Completed)],
1063            Instant::now().checked_sub(grace_period + Duration::from_millis(1)).unwrap(),
1064        );
1065        app.conversation_screen.plan_tracker.on_tick(Instant::now());
1066
1067        let output = render_app(&mut renderer, &mut app, &ViewContext::new((120, 40)));
1068        assert!(!frame_contains(&output, "Plan"));
1069    }
1070
1071    #[test]
1072    fn plan_version_increments_on_replace_and_clear() {
1073        let mut app = make_app();
1074        let v0 = app.conversation_screen.plan_tracker.version();
1075
1076        app.conversation_screen
1077            .plan_tracker
1078            .replace(vec![make_plan_entry("Task A", acp::PlanEntryStatus::Pending)], Instant::now());
1079        let v1 = app.conversation_screen.plan_tracker.version();
1080        assert!(v1 > v0, "replace should increment version");
1081
1082        app.conversation_screen.plan_tracker.clear();
1083        assert!(app.conversation_screen.plan_tracker.version() > v1, "clear should increment version");
1084    }
1085
1086    #[test]
1087    fn sessions_listed_filters_out_current_session() {
1088        let mut app = make_app_with_session_id("current-session");
1089        app.on_acp_event(AcpEvent::SessionsListed {
1090            sessions: vec![
1091                acp::SessionInfo::new("other-session-1", PathBuf::from("/project"))
1092                    .title("First other session".to_string()),
1093                acp::SessionInfo::new("current-session", PathBuf::from("/project"))
1094                    .title("Current session title".to_string()),
1095                acp::SessionInfo::new("other-session-2", PathBuf::from("/other"))
1096                    .title("Second other session".to_string()),
1097            ],
1098        });
1099
1100        let Some(Modal::SessionPicker(picker)) = &mut app.conversation_screen.active_modal else {
1101            panic!("expected session picker modal");
1102        };
1103        let lines = render_component(|ctx| picker.render(ctx), 60, 10).get_lines();
1104
1105        let has = |text: &str| lines.iter().any(|l| l.contains(text));
1106        assert!(!has("Current session title"), "current session should be filtered out");
1107        assert!(has("First other session"), "first other session should be present");
1108        assert!(has("Second other session"), "second other session should be present");
1109    }
1110
1111    #[tokio::test]
1112    async fn custom_exit_keybinding_triggers_exit() {
1113        use crate::keybindings::KeyBinding;
1114        let mut app = make_app();
1115        app.keybindings.exit = KeyBinding::new(KeyCode::Char('q'), KeyModifiers::CONTROL);
1116
1117        send_key(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;
1118        assert!(!app.exit_requested(), "default Ctrl+C should not exit");
1119        assert!(!app.exit_confirmation_active(), "Ctrl+C should not trigger exit confirmation when rebound");
1120
1121        send_key(&mut app, KeyCode::Char('q'), KeyModifiers::CONTROL).await;
1122        assert!(!app.exit_requested(), "first Ctrl+Q should trigger confirmation, not exit");
1123        assert!(app.exit_confirmation_active(), "first Ctrl+Q should activate confirmation");
1124
1125        send_key(&mut app, KeyCode::Char('q'), KeyModifiers::CONTROL).await;
1126        assert!(app.exit_requested(), "second Ctrl+Q should exit");
1127    }
1128
1129    #[tokio::test]
1130    async fn ctrl_g_toggles_git_diff_viewer() {
1131        let mut app = make_app();
1132
1133        send_key(&mut app, KeyCode::Char('g'), KeyModifiers::CONTROL).await;
1134        assert!(app.screen_router.is_git_diff(), "should open git diff");
1135
1136        send_key(&mut app, KeyCode::Char('g'), KeyModifiers::CONTROL).await;
1137        assert!(!app.screen_router.is_git_diff(), "should close git diff");
1138    }
1139
1140    #[tokio::test]
1141    async fn needs_mouse_capture_in_git_diff() {
1142        let mut app = make_app();
1143        assert!(!app.needs_mouse_capture());
1144
1145        send_key(&mut app, KeyCode::Char('g'), KeyModifiers::CONTROL).await;
1146        assert!(app.needs_mouse_capture());
1147
1148        send_key(&mut app, KeyCode::Char('g'), KeyModifiers::CONTROL).await;
1149        assert!(!app.needs_mouse_capture());
1150    }
1151
1152    #[tokio::test(flavor = "current_thread")]
1153    async fn ctrl_g_blocked_during_elicitation() {
1154        LocalSet::new()
1155            .run_until(async {
1156                let mut app = make_app();
1157                let (cx, mut peer) = test_connection().await;
1158                let (responder, _rx) = peer.fake_elicitation(&cx).await;
1159                app.conversation_screen.active_modal = Some(Modal::Elicitation(ElicitationForm::from_params(
1160                    elicitation_params("test-server", "test", ElicitationSchema::builder().build().unwrap()),
1161                    responder,
1162                )));
1163
1164                send_key(&mut app, KeyCode::Char('g'), KeyModifiers::CONTROL).await;
1165                assert!(!app.screen_router.is_git_diff(), "git diff should not open during elicitation");
1166            })
1167            .await;
1168    }
1169
1170    #[tokio::test(flavor = "current_thread")]
1171    async fn plan_review_elicitation_opens_full_screen_review() {
1172        LocalSet::new()
1173            .run_until(async {
1174                let mut app = make_app();
1175                let (cx, mut peer) = test_connection().await;
1176                let (responder, _rx) = peer.fake_elicitation(&cx).await;
1177
1178                app.on_elicitation_request(make_plan_review_params("# Plan\n\n- item"), responder);
1179
1180                assert!(app.screen_router.is_plan_review(), "plan review mode should open");
1181                assert!(app.conversation_screen.active_modal.is_none(), "plan review should bypass modal form");
1182            })
1183            .await;
1184    }
1185
1186    #[tokio::test(flavor = "current_thread")]
1187    async fn regular_form_elicitation_still_uses_modal_form() {
1188        LocalSet::new()
1189            .run_until(async {
1190                let mut app = make_app();
1191                let (cx, mut peer) = test_connection().await;
1192                let (responder, _rx) = peer.fake_elicitation(&cx).await;
1193
1194                app.on_elicitation_request(
1195                    elicitation_params("test-server", "regular form", ElicitationSchema::builder().build().unwrap()),
1196                    responder,
1197                );
1198
1199                assert!(!app.screen_router.is_plan_review());
1200                assert!(matches!(app.conversation_screen.active_modal, Some(Modal::Elicitation(_))));
1201            })
1202            .await;
1203    }
1204
1205    #[tokio::test(flavor = "current_thread")]
1206    async fn plan_review_finish_routes_response_and_closes_mode() {
1207        LocalSet::new()
1208            .run_until(async {
1209                let mut app = make_app();
1210                let (cx, mut peer) = test_connection().await;
1211                let (responder, rx) = peer.fake_elicitation(&cx).await;
1212                app.on_elicitation_request(make_plan_review_params("# Plan"), responder);
1213
1214                send_key(&mut app, KeyCode::Char('a'), KeyModifiers::NONE).await;
1215
1216                assert!(!app.screen_router.is_plan_review(), "plan review mode should close after finish");
1217                let response = rx.await.expect("plan review response should be sent");
1218                assert_eq!(response.action, acp_utils::notifications::ElicitationAction::Accept);
1219                assert_eq!(response.content.expect("approve content")["decision"], "approve");
1220            })
1221            .await;
1222    }
1223
1224    #[tokio::test(flavor = "current_thread")]
1225    async fn plan_review_cancel_routes_cancel_response() {
1226        LocalSet::new()
1227            .run_until(async {
1228                let mut app = make_app();
1229                let (cx, mut peer) = test_connection().await;
1230                let (responder, rx) = peer.fake_elicitation(&cx).await;
1231                app.on_elicitation_request(make_plan_review_params("# Plan"), responder);
1232
1233                send_key(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
1234
1235                let response = rx.await.expect("plan review response should be sent");
1236                assert_eq!(response.action, acp_utils::notifications::ElicitationAction::Cancel);
1237                assert!(response.content.is_none());
1238            })
1239            .await;
1240    }
1241
1242    #[tokio::test(flavor = "current_thread")]
1243    async fn replacing_pending_plan_review_cancels_the_previous_response() {
1244        LocalSet::new()
1245            .run_until(async {
1246                let mut app = make_app();
1247                let (cx, mut peer) = test_connection().await;
1248                let (first_responder, first_rx) = peer.fake_elicitation(&cx).await;
1249                let (second_responder, second_rx) = peer.fake_elicitation(&cx).await;
1250
1251                app.on_elicitation_request(make_plan_review_params("# First"), first_responder);
1252                app.on_elicitation_request(make_plan_review_params("# Second"), second_responder);
1253
1254                let first_response = first_rx.await.expect("first plan review response should be sent");
1255                assert_eq!(first_response.action, acp_utils::notifications::ElicitationAction::Cancel);
1256                assert!(first_response.content.is_none());
1257                assert!(app.screen_router.is_plan_review(), "replacement plan review should stay open");
1258
1259                send_key(&mut app, KeyCode::Char('a'), KeyModifiers::NONE).await;
1260
1261                let second_response = second_rx.await.expect("replacement plan review response should be sent");
1262                assert_eq!(second_response.action, acp_utils::notifications::ElicitationAction::Accept);
1263                assert_eq!(second_response.content.expect("approve content")["decision"], "approve");
1264            })
1265            .await;
1266    }
1267
1268    #[tokio::test]
1269    async fn esc_in_diff_mode_does_not_cancel() {
1270        let mut app = make_app();
1271        app.conversation_screen.on_prompt_sent();
1272        app.screen_router.enter_git_diff_for_test();
1273
1274        send_key(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
1275
1276        assert!(!app.exit_requested());
1277        assert!(
1278            app.conversation_screen.is_waiting(),
1279            "Esc should NOT cancel a running prompt while git diff mode is active"
1280        );
1281    }
1282
1283    #[tokio::test]
1284    async fn git_diff_submit_sends_prompt_and_closes_diff_when_idle() {
1285        use acp_utils::client::PromptCommand;
1286
1287        let (mut app, mut rx) = make_app_with_config_recording(&[]);
1288        app.screen_router.enter_git_diff_for_test();
1289
1290        let mut commands = Vec::new();
1291        app.handle_screen_router_message(
1292            &mut commands,
1293            ScreenRouterMessage::SendPrompt { user_input: "Looks good".to_string() },
1294        )
1295        .await;
1296
1297        assert!(!app.screen_router.is_git_diff(), "successful submit should exit git diff mode");
1298        assert!(app.conversation_screen.is_waiting(), "submit should transition into waiting state");
1299
1300        let cmd = rx.try_recv().expect("expected Prompt command to be sent");
1301        match cmd {
1302            PromptCommand::Prompt { text, .. } => {
1303                assert!(text.contains("Looks good"));
1304            }
1305            other => panic!("expected Prompt command, got {other:?}"),
1306        }
1307    }
1308
1309    #[tokio::test]
1310    async fn git_diff_submit_while_waiting_is_ignored_and_keeps_diff_open() {
1311        let (mut app, mut rx) = make_app_with_config_recording(&[]);
1312        app.conversation_screen.on_prompt_sent();
1313        app.screen_router.enter_git_diff_for_test();
1314
1315        let mut commands = Vec::new();
1316        app.handle_screen_router_message(
1317            &mut commands,
1318            ScreenRouterMessage::SendPrompt { user_input: "Needs follow-up".to_string() },
1319        )
1320        .await;
1321
1322        assert!(app.screen_router.is_git_diff(), "blocked submit should keep git diff mode open");
1323        assert!(rx.try_recv().is_err(), "no prompt should be sent while waiting");
1324    }
1325
1326    #[tokio::test]
1327    async fn mouse_scroll_ignored_in_conversation_mode() {
1328        use tui::{MouseEvent, MouseEventKind};
1329        let mut app = make_app();
1330        let mouse = MouseEvent { kind: MouseEventKind::ScrollDown, column: 0, row: 0, modifiers: KeyModifiers::NONE };
1331        app.on_event(&Event::Mouse(mouse)).await;
1332    }
1333
1334    #[tokio::test]
1335    async fn prompt_composer_submit_pushes_echo_lines() {
1336        use crate::components::conversation_window::SegmentContent;
1337        let mut app = make_app();
1338        let mut commands = Vec::new();
1339        app.handle_conversation_messages(
1340            &mut commands,
1341            Some(vec![ConversationScreenMessage::SendPrompt { user_input: "hello".to_string(), attachments: vec![] }]),
1342        )
1343        .await;
1344
1345        let has_hello = app
1346            .conversation_screen
1347            .conversation
1348            .segments()
1349            .any(|seg| matches!(seg, SegmentContent::UserMessage(text) if text == "hello"));
1350        assert!(has_hello, "conversation buffer should contain the user input");
1351    }
1352
1353    #[tokio::test]
1354    async fn unsupported_media_is_blocked_locally() {
1355        let (mut app, mut rx) = make_app_with_config_and_capabilities_recording(
1356            &image_model_options(),
1357            acp::PromptCapabilities::new().image(true).audio(false),
1358        );
1359        let mut commands = Vec::new();
1360        let temp = tempfile::tempdir().unwrap();
1361        let audio_path = temp.path().join("clip.wav");
1362        std::fs::write(&audio_path, b"fake wav").unwrap();
1363
1364        app.handle_conversation_messages(
1365            &mut commands,
1366            Some(vec![ConversationScreenMessage::SendPrompt {
1367                user_input: "listen".to_string(),
1368                attachments: vec![PromptAttachment { path: audio_path, display_name: "clip.wav".to_string() }],
1369            }]),
1370        )
1371        .await;
1372
1373        assert!(rx.try_recv().is_err(), "prompt should be blocked locally");
1374        assert!(!app.conversation_screen.is_waiting());
1375        let messages: Vec<_> = app
1376            .conversation_screen
1377            .conversation
1378            .segments()
1379            .filter_map(|segment| match segment {
1380                SegmentContent::UserMessage(text) => Some(text.clone()),
1381                _ => None,
1382            })
1383            .collect();
1384        assert!(messages.iter().any(|text| text == "listen"));
1385        assert!(messages.iter().any(|text| text == "[audio attachment: clip.wav]"));
1386        assert!(messages.iter().any(|text| {
1387            text == "[wisp] ACP agent does not support audio input."
1388                || text == "[wisp] Current model selection does not support audio input."
1389        }));
1390    }
1391
1392    #[test]
1393    fn replayed_media_user_chunks_render_placeholders() {
1394        use crate::components::conversation_window::SegmentContent;
1395        let mut app = make_app();
1396
1397        app.on_session_update(&acp::SessionUpdate::UserMessageChunk(acp::ContentChunk::new(acp::ContentBlock::Image(
1398            acp::ImageContent::new("aW1n", "image/png"),
1399        ))));
1400        app.on_session_update(&acp::SessionUpdate::UserMessageChunk(acp::ContentChunk::new(acp::ContentBlock::Audio(
1401            acp::AudioContent::new("YXVkaW8=", "audio/wav"),
1402        ))));
1403
1404        let segments: Vec<_> = app.conversation_screen.conversation.segments().collect();
1405        assert!(matches!(
1406            segments[0],
1407            SegmentContent::UserMessage(text) if text == "[image attachment]"
1408        ));
1409        assert!(matches!(
1410            segments[1],
1411            SegmentContent::UserMessage(text) if text == "[audio attachment]"
1412        ));
1413    }
1414
1415    #[test]
1416    fn prompt_composer_open_settings() {
1417        let mut app = make_app();
1418        let mut commands = Vec::new();
1419        tokio::runtime::Runtime::new().unwrap().block_on(
1420            app.handle_conversation_messages(&mut commands, Some(vec![ConversationScreenMessage::OpenSettings])),
1421        );
1422        assert!(app.settings_overlay.is_some(), "settings overlay should be opened");
1423    }
1424
1425    #[test]
1426    fn settings_overlay_close_clears_overlay() {
1427        let mut app = make_app();
1428        app.open_settings_overlay();
1429        app.settings_overlay = None;
1430        assert!(app.settings_overlay.is_none(), "close should clear overlay");
1431    }
1432
1433    #[tokio::test]
1434    async fn tick_advances_spinner_animations() {
1435        let mut app = make_app();
1436        let tool_call = acp::ToolCall::new("tool-1".to_string(), "test_tool");
1437        app.conversation_screen.tool_call_statuses.on_tool_call(&tool_call);
1438        app.conversation_screen.progress_indicator.update(ProgressActivity { agent_busy: true, ..Default::default() });
1439
1440        let ctx = ViewContext::new((80, 24));
1441        let tool_before = app.conversation_screen.tool_call_statuses.render_tool("tool-1", &ctx);
1442        let prog_before = app.conversation_screen.progress_indicator.render(&ctx);
1443
1444        app.on_event(&Event::Tick).await;
1445
1446        let tool_after = app.conversation_screen.tool_call_statuses.render_tool("tool-1", &ctx);
1447        let prog_after = app.conversation_screen.progress_indicator.render(&ctx);
1448
1449        assert_ne!(
1450            tool_before.lines()[0].plain_text(),
1451            tool_after.lines()[0].plain_text(),
1452            "tick should advance tool spinner"
1453        );
1454        assert_ne!(
1455            prog_before.lines()[1].plain_text(),
1456            prog_after.lines()[1].plain_text(),
1457            "tick should advance progress spinner"
1458        );
1459    }
1460
1461    #[test]
1462    fn prompt_done_does_not_bell_when_not_waiting_or_cancelled() {
1463        let mut app = make_app();
1464        let outcome = app.on_acp_event(AcpEvent::PromptDone(acp::StopReason::EndTurn));
1465        match outcome {
1466            EventOutcome::Render { commands } => assert!(commands.is_empty(), "duplicate PromptDone should not bell"),
1467            EventOutcome::DontRender => panic!("prompt done should render"),
1468        }
1469
1470        let mut app = make_app();
1471        app.conversation_screen.on_prompt_sent();
1472        let outcome = app.on_acp_event(AcpEvent::PromptDone(acp::StopReason::Cancelled));
1473        match outcome {
1474            EventOutcome::Render { commands } => assert!(commands.is_empty(), "cancelled prompt should not bell"),
1475            EventOutcome::DontRender => panic!("prompt done should render"),
1476        }
1477    }
1478
1479    #[test]
1480    fn on_prompt_error_clears_waiting_state() {
1481        let mut app = make_app();
1482        app.conversation_screen.on_prompt_sent();
1483        app.conversation_screen.on_prompt_error(&acp::Error::internal_error());
1484        assert!(!app.conversation_screen.is_waiting());
1485        assert!(!app.exit_requested());
1486    }
1487
1488    #[test]
1489    fn auth_events_and_connection_close_exit_behavior() {
1490        let mut app =
1491            make_app_with_auth(vec![acp::AuthMethod::Agent(acp::AuthMethodAgent::new("anthropic", "Anthropic"))]);
1492        app.on_authenticate_complete("anthropic");
1493        assert!(!app.exit_requested(), "authenticate_complete should not exit");
1494
1495        let mut app = make_app();
1496        app.on_authenticate_failed("anthropic", "bad token");
1497        assert!(!app.exit_requested(), "authenticate_failed should not exit");
1498
1499        let mut app = make_app();
1500        app.on_acp_event(AcpEvent::ConnectionClosed);
1501        assert!(app.exit_requested(), "connection_closed should exit");
1502    }
1503
1504    #[tokio::test]
1505    async fn clear_screen_returns_clear_command() {
1506        let mut app = make_app();
1507        let mut commands = Vec::new();
1508        app.handle_conversation_messages(&mut commands, Some(vec![ConversationScreenMessage::ClearScreen])).await;
1509        assert!(
1510            commands.iter().any(|c| matches!(c, RendererCommand::ClearScreen)),
1511            "should contain ClearScreen command"
1512        );
1513    }
1514
1515    #[tokio::test]
1516    async fn cancel_sends_directly_via_prompt_handle() {
1517        let mut app = make_app();
1518        app.conversation_screen.on_prompt_sent();
1519        send_key(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
1520        assert!(!app.exit_requested());
1521    }
1522
1523    #[test]
1524    fn new_session_restores_changed_config_selections() {
1525        use acp_utils::client::PromptCommand;
1526
1527        let (mut app, mut rx) = make_app_with_config_recording(&mode_model_options("Planner", "gpt-4o"));
1528        app.update_config_options(&mode_model_options("Coder", "gpt-4o"));
1529
1530        app.on_acp_event(AcpEvent::NewSessionCreated {
1531            session_id: SessionId::new("new-session"),
1532            config_options: mode_model_options("Planner", "gpt-4o"),
1533        });
1534
1535        assert_eq!(app.session_id, SessionId::new("new-session"));
1536        assert!(app.context_usage.is_none());
1537
1538        let cmd = rx.try_recv().expect("expected a SetConfigOption command");
1539        match cmd {
1540            PromptCommand::SetConfigOption { config_id, value, .. } => {
1541                assert_eq!(config_id, "mode");
1542                assert_eq!(value, "Coder");
1543            }
1544            other => panic!("expected SetConfigOption, got {other:?}"),
1545        }
1546        assert!(rx.try_recv().is_err(), "model was unchanged, no extra command expected");
1547    }
1548
1549    #[tokio::test(flavor = "current_thread")]
1550    async fn ctrl_g_blocked_during_url_elicitation_modal() {
1551        LocalSet::new()
1552            .run_until(async {
1553                let mut app = make_app();
1554                let (cx, mut peer) = test_connection().await;
1555                let (responder, _rx) = peer.fake_elicitation(&cx).await;
1556                app.conversation_screen.active_modal = Some(Modal::Elicitation(ElicitationForm::from_params(
1557                    url_elicitation_params("test-server", "el-1", "https://example.com/auth"),
1558                    responder,
1559                )));
1560
1561                send_key(&mut app, KeyCode::Char('g'), KeyModifiers::CONTROL).await;
1562                assert!(!app.screen_router.is_git_diff(), "git diff should not open during URL elicitation modal");
1563            })
1564            .await;
1565    }
1566
1567    #[tokio::test]
1568    async fn first_ctrl_c_clears_prompt_input() {
1569        let mut app = make_app();
1570        app.conversation_screen.prompt_composer.set_input("draft prompt".to_string());
1571
1572        send_key(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;
1573
1574        assert_eq!(app.conversation_screen.prompt_composer.buffer(), "");
1575        assert!(!app.exit_requested(), "first Ctrl-C should not exit");
1576        assert!(app.exit_confirmation_active(), "first Ctrl-C should activate confirmation");
1577    }
1578
1579    #[tokio::test]
1580    async fn first_ctrl_c_does_not_exit() {
1581        let mut app = make_app();
1582        send_key(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;
1583        assert!(!app.exit_requested(), "first Ctrl-C should not exit");
1584        assert!(app.exit_confirmation_active(), "first Ctrl-C should activate confirmation");
1585    }
1586
1587    #[tokio::test]
1588    async fn second_ctrl_c_exits() {
1589        let mut app = make_app();
1590        send_key(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;
1591        assert!(!app.exit_requested());
1592        send_key(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL).await;
1593        assert!(app.exit_requested(), "second Ctrl-C should exit");
1594    }
1595
1596    #[tokio::test]
1597    async fn ctrl_c_confirmation_expires_on_tick() {
1598        let mut app = make_app();
1599        app.ctrl_c_pressed_at = Some(Instant::now().checked_sub(Duration::from_secs(4)).unwrap());
1600        assert!(app.exit_confirmation_active());
1601        app.on_event(&Event::Tick).await;
1602        assert!(!app.exit_confirmation_active(), "confirmation should expire after timeout");
1603    }
1604
1605    #[tokio::test]
1606    async fn prompt_error_mid_tool_call_finalizes_running_tools() {
1607        let (mut app, mut rx) = make_app_with_config_recording(&[]);
1608        app.conversation_screen.on_prompt_sent();
1609        app.on_session_update(&acp::SessionUpdate::ToolCall(acp::ToolCall::new("tool-1".to_string(), "slow_tool")));
1610        assert!(
1611            app.conversation_screen.tool_call_statuses.running_any(),
1612            "precondition: tool call should be tracked as running"
1613        );
1614
1615        app.on_acp_event(AcpEvent::PromptError(acp::Error::internal_error()));
1616
1617        assert!(
1618            !app.conversation_screen.tool_call_statuses.running_any(),
1619            "prompt error should finalize running tool calls like on_prompt_done does"
1620        );
1621
1622        let ctx = ViewContext::new((200, 24));
1623        app.conversation_screen.refresh_caches(&ctx);
1624        let frame = app.conversation_screen.progress_indicator.render(&ctx);
1625        assert!(
1626            frame.lines().is_empty(),
1627            "progress indicator must go idle after a prompt error; otherwise it renders an animated spinner \
1628             with '(esc to interrupt)' while Esc is dead (cancel is gated on waiting_for_response, already false)"
1629        );
1630
1631        send_key(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
1632        assert!(rx.try_recv().is_err(), "no cancel should be needed once the UI is idle");
1633    }
1634
1635    #[tokio::test]
1636    async fn esc_hint_renders_when_only_sub_agents_are_running() {
1637        use acp_utils::notifications::{SubAgentEvent, SubAgentProgressParams};
1638
1639        let (mut app, _rx) = make_app_with_config_recording(&[]);
1640        app.on_session_update(&acp::SessionUpdate::ToolCall(acp::ToolCall::new(
1641            "tool-1".to_string(),
1642            "spawn_subagent",
1643        )));
1644        app.conversation_screen.tool_call_statuses.on_sub_agent_progress(&SubAgentProgressParams {
1645            parent_tool_id: "tool-1".to_string(),
1646            task_id: "task-1".to_string(),
1647            agent_name: "researcher".to_string(),
1648            event: SubAgentEvent::Other,
1649        });
1650        assert!(app.conversation_screen.is_busy(), "precondition: sub-agent work counts as busy");
1651
1652        let ctx = ViewContext::new((200, 24));
1653        app.conversation_screen.refresh_caches(&ctx);
1654        let frame = app.conversation_screen.progress_indicator.render(&ctx);
1655        let rendered: String = frame.lines().iter().map(tui::Line::plain_text).collect();
1656        assert!(
1657            rendered.contains("esc to interrupt"),
1658            "the indicator must advertise Esc whenever the Esc gate would accept it; deriving indicator state \
1659             from top-level tool counts hid sub-agent-only activity"
1660        );
1661    }
1662
1663    #[tokio::test]
1664    async fn esc_cancels_while_tools_running_even_when_not_waiting() {
1665        use acp_utils::client::PromptCommand;
1666
1667        let (mut app, mut rx) = make_app_with_config_recording(&[]);
1668        app.on_session_update(&acp::SessionUpdate::ToolCall(acp::ToolCall::new("tool-1".to_string(), "slow_tool")));
1669        assert!(!app.conversation_screen.is_waiting());
1670
1671        send_key(&mut app, KeyCode::Esc, KeyModifiers::NONE).await;
1672
1673        let cmd = rx.try_recv().expect("Esc should send cancel whenever the UI advertises '(esc to interrupt)'");
1674        assert!(matches!(cmd, PromptCommand::Cancel { .. }));
1675    }
1676
1677    #[tokio::test(flavor = "current_thread")]
1678    async fn replacing_pending_elicitation_modal_cancels_previous_responder() {
1679        LocalSet::new()
1680            .run_until(async {
1681                let mut app = make_app();
1682                let (cx, mut peer) = test_connection().await;
1683                let (first_responder, first_rx) = peer.fake_elicitation(&cx).await;
1684                let (second_responder, _second_rx) = peer.fake_elicitation(&cx).await;
1685
1686                app.on_elicitation_request(
1687                    elicitation_params("server-a", "first", ElicitationSchema::builder().build().unwrap()),
1688                    first_responder,
1689                );
1690                app.on_elicitation_request(
1691                    elicitation_params("server-b", "second", ElicitationSchema::builder().build().unwrap()),
1692                    second_responder,
1693                );
1694
1695                // The requesting agent blocks awaiting this response; dropping the
1696                // responder without answering would wedge it forever.
1697                let first_response = first_rx.await.expect("replaced elicitation must receive a response");
1698                assert_eq!(first_response.action, acp_utils::notifications::ElicitationAction::Cancel);
1699            })
1700            .await;
1701    }
1702
1703    #[test]
1704    fn status_line_shows_warning_when_confirmation_active() {
1705        use crate::components::status_line::StatusLine;
1706        use crate::settings::StatusLineSettings;
1707        let options = vec![acp::SessionConfigOption::select(
1708            "model",
1709            "Model",
1710            "m1",
1711            vec![acp::SessionConfigSelectOption::new("m1", "M1")],
1712        )];
1713        let workspace_status = test_workspace_status();
1714        let resolved = StatusLineSettings::resolved_defaults();
1715        let status = StatusLine {
1716            workspace_status: &workspace_status,
1717            agent_name: "test-agent",
1718            config_options: &options,
1719            context_usage: None,
1720            waiting_for_response: false,
1721            unhealthy_server_count: 0,
1722            content_padding: DEFAULT_CONTENT_PADDING,
1723            exit_confirmation_active: true,
1724            settings: &resolved,
1725        };
1726        let context = ViewContext::new((120, 40));
1727        let frame = status.render(&context);
1728        let text = frame.lines()[0].plain_text();
1729        assert!(text.contains("Ctrl-C again to exit"), "should show warning, got: {text}");
1730        assert!(!text.contains("test-agent"), "should not show agent name during confirmation, got: {text}");
1731    }
1732}