aether-wisp 0.6.3

A terminal UI for AI coding agents via the Agent Client Protocol (ACP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
mod form;
pub(crate) mod frame;
mod url;

use crate::renderer::DrawContext;
use crate::surfaces::elicitation::ElicitationResponder;
use acp_utils::elicitation::source_mcp_server_name;
use agent_client_protocol::Responder;
use agent_client_protocol::schema::v1::{CreateElicitationRequest, CreateElicitationResponse, ElicitationMode};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Position, Rect};
use ratatui::text::Text;
use ratatui::widgets::{Paragraph, Widget};

use self::form::{FormAction, FormModal};
use self::frame::{MODAL_HORIZONTAL_PADDING, MODAL_VERTICAL_CHROME, ModalFrame};
use self::url::UrlModal;
use crate::session::platform::{BrowserOpener, ClipboardWriter};
use crate::surfaces::input::{ElicitationOutput, UiEvent, is_press};
use crate::theme::Theme;
use crate::view::widgets::{KeyHint, SCROLLBAR_WIDTH, key_hints};
use crate::view::wrap::as_u16;

pub struct ElicitationModal {
    kind: ModalKind,
    responder: ElicitationResponder,
    browser_opener: BrowserOpener,
    clipboard_writer: ClipboardWriter,
}

enum ModalKind {
    Form(FormModal),
    Url(UrlModal),
}

impl ElicitationModal {
    pub fn with_url_handlers(
        params: CreateElicitationRequest,
        responder: Responder<CreateElicitationResponse>,
        browser_opener: BrowserOpener,
        clipboard_writer: ClipboardWriter,
    ) -> Option<Self> {
        let server_name = source_mcp_server_name(params.meta.as_ref()).unwrap_or("Agent").to_string();
        let message = params.message;
        let responder = ElicitationResponder::new(responder);
        let kind = match params.mode {
            ElicitationMode::Form(form) => {
                ModalKind::Form(FormModal::new(server_name, message, &form.requested_schema)?)
            }
            ElicitationMode::Url(url) => ModalKind::Url(UrlModal::new(server_name, message, url.url)),
            _ => return None,
        };
        Some(Self { kind, responder, browser_opener, clipboard_writer })
    }

    /// Draws the request inside a host that keeps its own chrome, rather than as
    /// a modal over everything. The settings overlay shows an OAuth prompt this
    /// way so the server row that started it stays on screen.
    pub fn render_inline(&mut self, area: Rect, buf: &mut Buffer, theme: &Theme) {
        match &mut self.kind {
            ModalKind::Form(form) => {
                let _ = form.render(area, buf, theme);
            }
            ModalKind::Url(url) => {
                Paragraph::new(Text::from(url.body_lines(theme, area.width))).render(area, buf);
            }
        }
    }

    /// The rows [`Self::render_inline`] wants at `width`. A form lays out its
    /// own pages, so it takes whatever the host can spare.
    pub fn inline_height(&self, theme: &Theme, width: u16) -> u16 {
        match &self.kind {
            ModalKind::Form(_) => u16::MAX,
            ModalKind::Url(url) => as_u16(url.body_lines(theme, width).len()),
        }
    }

    /// The keys this request answers, for a host that draws its own footer.
    pub fn key_hints(&self) -> Vec<KeyHint> {
        match &self.kind {
            ModalKind::Form(form) => form.hints(),
            ModalKind::Url(_) => url::HINTS.to_vec(),
        }
    }

    fn on_url_key(&mut self, key: KeyEvent) -> Vec<ElicitationOutput> {
        let ModalKind::Url(url) = &mut self.kind else {
            return Vec::new();
        };
        let plain_key = key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT;
        match key.code {
            KeyCode::Esc => {
                self.responder.cancel();
                return vec![ElicitationOutput::Close];
            }
            KeyCode::Enter => {
                if let Err(error) = (self.browser_opener)(&url.url) {
                    url.launch_error = Some(format!("Failed to open browser: {error}"));
                } else {
                    self.responder.accept(None);
                    return vec![ElicitationOutput::Close];
                }
            }
            KeyCode::Char('c' | 'C') if plain_key => {
                url.copy_message = Some(match (self.clipboard_writer)(&url.url) {
                    Ok(()) => "Copied URL to clipboard.".to_string(),
                    Err(error) => format!("Failed to copy URL: {error}"),
                });
            }
            _ => {}
        }
        Vec::new()
    }
}

impl ElicitationModal {
    pub(crate) fn on_ui_event(&mut self, event: UiEvent) -> Vec<ElicitationOutput> {
        match event {
            UiEvent::Key(key) if is_press(key) => self.on_key(key),
            UiEvent::Key(_) => Vec::new(),
            UiEvent::Paste(text) => {
                if let ModalKind::Form(form) = &mut self.kind {
                    form.paste(&text);
                }
                Vec::new()
            }
            UiEvent::Mouse(action, (column, row)) => {
                if let Some(direction) = action.direction() {
                    if let ModalKind::Form(form) = &mut self.kind {
                        form.vertical(direction);
                    }
                } else if let ModalKind::Form(form) = &mut self.kind {
                    form.click(column, row);
                }
                Vec::new()
            }
        }
    }

    pub(crate) fn on_key(&mut self, key: KeyEvent) -> Vec<ElicitationOutput> {
        self.on_request_key(key)
    }

    /// A modal answers a request, so it owns every key: nothing falls through
    /// to the shared list navigation.
    fn on_request_key(&mut self, key: KeyEvent) -> Vec<ElicitationOutput> {
        let ModalKind::Form(form) = &mut self.kind else {
            return self.on_url_key(key);
        };
        match form.on_key(key) {
            FormAction::None => Vec::new(),
            FormAction::Cancel => {
                self.responder.cancel();
                vec![ElicitationOutput::Close]
            }
            FormAction::Accept(content) => {
                self.responder.accept(Some(content));
                vec![ElicitationOutput::Close]
            }
        }
    }

    pub(crate) fn needs_mouse_capture(&self) -> bool {
        matches!(self.kind, ModalKind::Form(_))
    }

    /// Dismissing the modal answers the request it was asking about.
    pub(crate) fn cancel(&mut self) {
        self.responder.cancel();
    }
}

impl ElicitationModal {
    pub(crate) fn render(&mut self, area: Rect, buf: &mut Buffer, cx: &mut DrawContext<'_>) -> Option<Position> {
        // The modal hugs its content: wide enough to read, never more than a
        // fraction of the screen, and only as tall as the page it is asking
        // about (plus a scroll bar when a long page cannot fit).
        let width = area.width.min(76).min(area.width.saturating_mul(92) / 100);
        let content_width = width.saturating_sub(MODAL_HORIZONTAL_PADDING * 2);
        let (title, footer, body_rows) = match &self.kind {
            ModalKind::Form(form) => (
                "Request",
                key_hints(&form.hints(), cx.theme),
                form.content_height(cx.theme, content_width.saturating_sub(SCROLLBAR_WIDTH + 1)),
            ),
            ModalKind::Url(url) => {
                ("Authorization", key_hints(&url::HINTS, cx.theme), url.body_lines(cx.theme, content_width).len())
            }
        };
        let height = as_u16(body_rows + usize::from(MODAL_VERTICAL_CHROME))
            .min(area.height.saturating_mul(70) / 100)
            .clamp(3.min(area.height), area.height);
        let server_name = match &self.kind {
            ModalKind::Form(form) => form.server_name(),
            ModalKind::Url(url) => url.server_name.as_str(),
        };
        let frame =
            ModalFrame::new(title, Some(footer), Constraint::Length(width), Constraint::Length(height), cx.theme)
                .title_right(server_name);
        let inner = frame.inner(area);
        (&frame).render(area, buf);
        match &mut self.kind {
            ModalKind::Form(form) => form.render(inner, buf, cx.theme),
            ModalKind::Url(url) => {
                Paragraph::new(Text::from(url.body_lines(cx.theme, inner.width))).render(inner, buf);
                None
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::absolute_paths, clippy::similar_names)]
mod tests {
    use super::form::permission_like_schema;
    use super::*;
    use acp_utils::testing::test_connection;
    use agent_client_protocol::schema::v1::{
        ElicitationAction, ElicitationFormMode, ElicitationSchema, ElicitationSessionScope, ElicitationUrlMode,
    };
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use tokio::task::LocalSet;

    /// Whether the modal asked to be dismissed.
    fn closes(messages: &[ElicitationOutput]) -> bool {
        messages.iter().any(|message| matches!(message, ElicitationOutput::Close))
    }

    fn noop_handlers() -> (BrowserOpener, ClipboardWriter) {
        (Arc::new(|_| Ok(())), Arc::new(|_| Ok(())))
    }

    fn failing_handlers() -> (BrowserOpener, ClipboardWriter) {
        (
            Arc::new(|_| Err("simulated open failure".to_string())),
            Arc::new(|_| Err("simulated copy failure".to_string())),
        )
    }

    fn form_request(schema: ElicitationSchema) -> CreateElicitationRequest {
        CreateElicitationRequest::new(
            ElicitationFormMode::new(ElicitationSessionScope::new("session-1"), schema),
            String::new(),
        )
    }

    fn url_request(url: &str) -> CreateElicitationRequest {
        CreateElicitationRequest::new(
            ElicitationUrlMode::new(ElicitationSessionScope::new("session-1"), "el-1", url),
            "Authorize GitHub",
        )
    }

    async fn make_modal_for_schema(
        schema: ElicitationSchema,
    ) -> (ElicitationModal, tokio::sync::oneshot::Receiver<CreateElicitationResponse>) {
        let (cx, mut peer) = test_connection().await;
        let (responder, rx) = peer.fake_elicitation(&cx).await;
        let (opener, writer) = noop_handlers();
        (ElicitationModal::with_url_handlers(form_request(schema), responder, opener, writer).unwrap(), rx)
    }

    async fn make_url_modal(
        url: &str,
    ) -> (ElicitationModal, tokio::sync::oneshot::Receiver<CreateElicitationResponse>) {
        let (cx, mut peer) = test_connection().await;
        let (responder, rx) = peer.fake_elicitation(&cx).await;
        let (opener, writer) = noop_handlers();
        (ElicitationModal::with_url_handlers(url_request(url), responder, opener, writer).unwrap(), rx)
    }

    async fn make_url_modal_with_handlers(
        url: &str,
        opener: BrowserOpener,
        writer: ClipboardWriter,
    ) -> ElicitationModal {
        let (cx, mut peer) = test_connection().await;
        let (responder, _rx) = peer.fake_elicitation(&cx).await;
        ElicitationModal::with_url_handlers(url_request(url), responder, opener, writer).unwrap()
    }
    #[tokio::test(flavor = "current_thread")]
    async fn permission_like_form_returns_default_on_enter() {
        LocalSet::new()
            .run_until(async {
                let schema = permission_like_schema();
                let (mut modal, rx) = make_modal_for_schema(schema).await;
                assert!(closes(&modal.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))));
                let response = rx.await.unwrap();
                let ElicitationAction::Accept(accept) = response.action else { panic!("expected accept") };
                assert_eq!(accept.content.unwrap()["decision"], "deny".into());
            })
            .await;
    }
    #[tokio::test(flavor = "current_thread")]
    async fn esc_returns_cancel() {
        LocalSet::new()
            .run_until(async {
                let schema = ElicitationSchema::new();
                let (mut modal, rx) = make_modal_for_schema(schema).await;
                assert!(closes(&modal.on_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))));
                let response = rx.await.unwrap();
                assert!(matches!(response.action, ElicitationAction::Cancel));
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn dropping_modal_responds_cancel() {
        LocalSet::new()
            .run_until(async {
                let schema = ElicitationSchema::new();
                let (modal, rx) = make_modal_for_schema(schema).await;
                drop(modal);
                let response = rx.await.unwrap();
                assert!(matches!(response.action, ElicitationAction::Cancel));
            })
            .await;
    }
    #[tokio::test(flavor = "current_thread")]
    async fn url_enter_opens_browser_and_accepts_request() {
        LocalSet::new()
            .run_until(async {
                let opened = Arc::new(AtomicBool::new(false));
                let url_opener: BrowserOpener = {
                    let opened = opened.clone();
                    Arc::new(move |_| {
                        opened.store(true, Ordering::SeqCst);
                        Ok(())
                    })
                };
                let mut modal =
                    make_url_modal_with_handlers("https://github.com/login", url_opener, noop_handlers().1).await;
                let outcome = modal.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
                assert!(closes(&outcome));
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn url_enter_shows_error_on_open_failure() {
        LocalSet::new()
            .run_until(async {
                let mut modal =
                    make_url_modal_with_handlers("https://github.com/login", failing_handlers().0, noop_handlers().1)
                        .await;
                modal.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
                match &modal.kind {
                    ModalKind::Url(url) => {
                        assert!(url.launch_error.as_deref().unwrap().contains("simulated open failure"));
                    }
                    ModalKind::Form(_) => panic!("expected Url"),
                }
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn url_c_copies_to_clipboard() {
        LocalSet::new()
            .run_until(async {
                let copied: Arc<std::sync::Mutex<String>> = Arc::new(std::sync::Mutex::new(String::new()));
                let writer: ClipboardWriter = {
                    let copied = copied.clone();
                    Arc::new(move |text: &str| {
                        *copied.lock().unwrap() = text.to_string();
                        Ok(())
                    })
                };
                let mut modal =
                    make_url_modal_with_handlers("https://github.com/login", noop_handlers().0, writer).await;
                modal.on_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE));
                match &modal.kind {
                    ModalKind::Url(url) => {
                        assert_eq!(url.copy_message.as_deref(), Some("Copied URL to clipboard."));
                    }
                    ModalKind::Form(_) => panic!("expected Url"),
                }
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn url_copy_shows_error_on_failure() {
        LocalSet::new()
            .run_until(async {
                let mut modal =
                    make_url_modal_with_handlers("https://github.com/login", noop_handlers().0, failing_handlers().1)
                        .await;
                modal.on_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE));
                match &modal.kind {
                    ModalKind::Url(url) => {
                        assert!(url.copy_message.as_deref().unwrap().contains("simulated copy failure"));
                    }
                    ModalKind::Form(_) => panic!("expected Url"),
                }
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn url_esc_cancels() {
        LocalSet::new()
            .run_until(async {
                let (mut modal, rx) = make_url_modal("https://github.com/login").await;
                assert!(closes(&modal.on_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))));
                let response = rx.await.unwrap();
                assert!(matches!(response.action, ElicitationAction::Cancel));
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn url_drop_sends_cancel() {
        LocalSet::new()
            .run_until(async {
                let (modal, rx) = make_url_modal("https://github.com/login").await;
                drop(modal);
                let response = rx.await.unwrap();
                assert!(matches!(response.action, ElicitationAction::Cancel));
            })
            .await;
    }
}