Skip to main content

wisp/app/
acp_reducer.rs

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