Skip to main content

wisp/app/
acp_reducer.rs

1use super::session::builtin_commands;
2use super::{App, ExitState, Overlay, Route};
3use crate::attachment::placeholder_for_content_block;
4use crate::command::{AgentCommand, Command, TerminalCommand};
5use crate::conversation::ContextUsageDisplay;
6use crate::conversation::tool_calls::ToolStatus;
7use crate::screens::plan_review::PlanReviewScreen;
8use crate::surfaces::modal::ElicitationModal;
9use crate::surfaces::picker::CommandEntry;
10use crate::surfaces::session_picker::SessionPicker;
11use acp_utils::client::{AcpEvent, LoadedSession};
12use acp_utils::notifications::McpNotification;
13use agent_client_protocol::schema::v1::{self as acp, CreateElicitationRequest, ElicitationMode, SessionId};
14use std::time::Instant;
15
16impl App {
17    #[allow(clippy::too_many_lines)]
18    pub fn on_acp_event(&mut self, event: AcpEvent) {
19        match event {
20            AcpEvent::SessionUpdate { session_id, update } => {
21                if &session_id == self.session.session_id() {
22                    self.on_session_update(&update);
23                }
24            }
25            AcpEvent::PromptCompleted(stop_reason) => {
26                let status = match stop_reason {
27                    acp::StopReason::Cancelled => ToolStatus::Error("cancelled".to_string()),
28                    _ => ToolStatus::Success,
29                };
30                self.finish_prompt(&status);
31            }
32            AcpEvent::ContextCompaction(params) => {
33                if self.conversation.progress_indicator().accepts_activity() {
34                    self.conversation.turn_mut().set_compaction_active(params.active);
35                }
36            }
37            AcpEvent::ContextCleared(_) => {
38                self.reset_conversation();
39            }
40            AcpEvent::ElicitationRequest { params, responder } => {
41                let params = *params;
42                self.close_elicitation_owner();
43                if let Some(meta) = plan_review_meta(&params) {
44                    self.open_route(Route::PlanReview(Box::new(PlanReviewScreen::new(meta, responder))));
45                    return;
46                }
47                // The settings overlay answers its own elicitations in place so
48                // an OAuth prompt does not tear down the pane that started it.
49                if let Some(Overlay::Settings(overlay)) = self.overlay.as_mut() {
50                    overlay.on_elicitation_request(
51                        params,
52                        responder,
53                        self.browser_opener.clone(),
54                        self.clipboard_writer.clone(),
55                    );
56                    return;
57                }
58                if let Some(modal) = ElicitationModal::with_url_handlers(
59                    params,
60                    responder,
61                    self.browser_opener.clone(),
62                    self.clipboard_writer.clone(),
63                ) {
64                    self.open_overlay(Overlay::Elicitation(modal));
65                }
66            }
67            AcpEvent::McpNotification(notification) => self.on_mcp_notification(&notification),
68            AcpEvent::AuthMethodsUpdated(params) => {
69                self.session.set_auth_methods(&params.auth_methods);
70                if let Some(Overlay::Settings(overlay)) = self.overlay.as_mut() {
71                    overlay.update_auth_methods(&params.auth_methods);
72                }
73            }
74            AcpEvent::ConnectionClosed => self.on_connection_closed(),
75            AcpEvent::SubAgentProgress(progress) => {
76                if self.conversation.progress_indicator().accepts_activity() {
77                    self.conversation.on_sub_agent_progress(&progress);
78                }
79            }
80        }
81    }
82
83    /// Reports why a workspace move could not proceed and leaves move mode.
84    pub(super) fn abandon_workspace_move(&mut self, message: &str) {
85        self.notify(message);
86        self.session.end_workspace_move();
87    }
88
89    pub(super) fn open_session_picker(&mut self, sessions: Vec<acp::SessionInfo>) {
90        let current_id = self.session.session_id().clone();
91        let others = sessions.into_iter().filter(|session| session.session_id != current_id).collect();
92        let picker = SessionPicker::new(others, self.session.capabilities().session_preview);
93        if let Some(id) = picker.initial_preview_request() {
94            self.queue(Command::Agent(AgentCommand::SessionPreview { session_id: id }));
95        }
96        self.open_overlay(Overlay::Sessions(picker));
97    }
98
99    pub(super) fn on_loaded_session(&mut self, loaded: LoadedSession) {
100        let LoadedSession { session_id, response, replay } = loaded;
101        self.reset_turn_state();
102        for notification in replay {
103            self.on_session_update(&notification.update);
104        }
105        self.session.set_session(session_id, response.config_options.unwrap_or_default());
106        self.return_to_conversation();
107        self.session.end_workspace_move();
108    }
109
110    pub(super) fn on_new_session(&mut self, session_id: SessionId, config_options: Vec<acp::SessionConfigOption>) {
111        self.close_elicitation_owner();
112        self.return_to_conversation();
113        let previous_selections: Vec<(String, String)> = self
114            .session
115            .config_options()
116            .iter()
117            .filter_map(|option| option.select().map(|select| (option.id.clone(), select.current_value.to_string())))
118            .collect();
119        self.session.set_session(session_id, config_options);
120        self.reset_conversation();
121        self.restore_config_selections(&previous_selections);
122    }
123
124    /// Server notifications feed the status summary in the status line and settings overlay.
125    fn on_mcp_notification(&mut self, notification: &McpNotification) {
126        let McpNotification::ServerStatus { servers } = notification;
127        self.session.update_server_statuses(servers);
128        let servers = servers.clone();
129        if let Some(Overlay::Settings(overlay)) = self.overlay.as_mut() {
130            overlay.update_server_statuses(servers);
131        }
132    }
133
134    /// The agent is gone: answer anything it is still waiting on, tear down
135    /// every route and overlay, and ask the event loop to exit.
136    fn on_connection_closed(&mut self) {
137        self.close_elicitation_owner();
138        self.return_to_conversation();
139        self.session.end_workspace_move();
140        self.commands.retain(|command| !matches!(command, Command::Terminal(TerminalCommand::RingBell)));
141        self.exit_state = ExitState::Exiting;
142    }
143
144    /// Answers any elicitation the current route or overlay is holding, leaving the
145    /// settings overlay itself open so its pane survives.
146    fn close_elicitation_owner(&mut self) {
147        match self.overlay.as_mut() {
148            Some(Overlay::Settings(overlay)) => overlay.cancel_pending_elicitation(),
149            Some(Overlay::Elicitation(_)) => self.close_overlay(),
150            _ => {}
151        }
152    }
153
154    fn on_session_update(&mut self, update: &acp::SessionUpdate) {
155        if is_agent_activity(update) && !self.conversation.progress_indicator().accepts_activity() {
156            return;
157        }
158        match update {
159            acp::SessionUpdate::UserMessageChunk(chunk) => {
160                if let Some(text) = match &chunk.content {
161                    acp::ContentBlock::Text(text) => Some(text.text.clone()),
162                    block => placeholder_for_content_block(block).map(str::to_string),
163                } {
164                    self.conversation.append_user_content(text);
165                }
166            }
167            acp::SessionUpdate::AgentMessageChunk(chunk) => {
168                if let acp::ContentBlock::Text(text_content) = &chunk.content {
169                    if !text_content.text.is_empty() {
170                        self.conversation.progress_indicator_mut().response_started();
171                    }
172                    self.conversation.append_assistant_chunk(&text_content.text);
173                }
174            }
175            acp::SessionUpdate::AgentThoughtChunk(chunk) => {
176                if let acp::ContentBlock::Text(text_content) = &chunk.content
177                    && !text_content.text.is_empty()
178                {
179                    self.conversation.progress_indicator_mut().record_thought(&text_content.text);
180                }
181            }
182            acp::SessionUpdate::ToolCall(tool_call) => {
183                self.conversation.progress_indicator_mut().tool_activity();
184                self.conversation.on_tool_call(tool_call);
185            }
186            acp::SessionUpdate::ToolCallUpdate(update) => {
187                self.conversation.progress_indicator_mut().tool_activity();
188                self.conversation.on_tool_call_update(update);
189            }
190            acp::SessionUpdate::AvailableCommandsUpdate(update) => {
191                let agent_commands: Vec<_> = update
192                    .available_commands
193                    .iter()
194                    .map(|command| CommandEntry {
195                        name: command.name.clone(),
196                        description: command.description.clone(),
197                        has_input: command.input.is_some(),
198                        hint: match &command.input {
199                            Some(acp::AvailableCommandInput::Unstructured(input)) => Some(input.hint.clone()),
200                            _ => None,
201                        },
202                        builtin: false,
203                    })
204                    .collect();
205                let mut all = builtin_commands(self.session.capabilities());
206                all.extend(agent_commands);
207                self.available_commands = all;
208            }
209            acp::SessionUpdate::ConfigOptionUpdate(update) => {
210                self.session.update_config_options(update.config_options.clone());
211                self.conversation.finish_current_block();
212                if let Some(Overlay::Settings(overlay)) = self.overlay.as_mut() {
213                    overlay.update_config_options(self.session.config_options());
214                }
215            }
216            acp::SessionUpdate::Plan(plan) => {
217                self.conversation.plan_tracker_mut().replace(plan.entries.clone(), Instant::now());
218                self.conversation.finish_current_block();
219            }
220            acp::SessionUpdate::UsageUpdate(usage) => {
221                self.conversation.turn_mut().set_context_usage(Some(ContextUsageDisplay {
222                    used_tokens: u32::try_from(usage.used).unwrap_or(u32::MAX),
223                    limit_tokens: u32::try_from(usage.size).unwrap_or(u32::MAX),
224                }));
225            }
226            _ => {
227                self.conversation.finish_current_block();
228            }
229        }
230    }
231
232    pub(super) fn finish_prompt(&mut self, terminal_status: &ToolStatus) {
233        let was_in_flight = self.waiting_for_response();
234        self.conversation.turn_mut().set_prompt_in_flight(false);
235        self.conversation.turn_mut().set_compaction_active(false);
236        self.conversation.progress_indicator_mut().prompt_finished();
237        self.conversation.finish_turn(terminal_status);
238        if was_in_flight && matches!(terminal_status, ToolStatus::Success) {
239            self.queue(Command::Terminal(TerminalCommand::RingBell));
240        }
241    }
242}
243
244fn is_agent_activity(update: &acp::SessionUpdate) -> bool {
245    matches!(
246        update,
247        acp::SessionUpdate::AgentMessageChunk(_)
248            | acp::SessionUpdate::AgentThoughtChunk(_)
249            | acp::SessionUpdate::ToolCall(_)
250            | acp::SessionUpdate::ToolCallUpdate(_)
251    )
252}
253
254pub(super) fn plan_review_meta(
255    params: &CreateElicitationRequest,
256) -> Option<utils::plan_review::PlanReviewElicitationMeta> {
257    if !matches!(params.mode, ElicitationMode::Form(_)) {
258        return None;
259    }
260    utils::plan_review::PlanReviewElicitationMeta::parse(params.meta.as_ref())
261}