1use gpui_kit::component::input::{InputEvent, RopeExt as _, TextareaState};
14use gpui_kit::prelude::FluentBuilder as _;
15use gpui_kit::{
16 AnyView, App, AppContext as _, Context, Entity, EventEmitter, InteractiveElement as _,
17 IntoElement, KeyBinding, KeyContext, OperatingSystem, ParentElement as _, Render, SharedString,
18 Styled as _, Subscription, Window, actions, div,
19};
20
21use crate::tokens::Tokens;
22use attachments::IngestionBatch;
23use std::fmt;
24pub mod attachments;
25pub mod completion;
26mod counter;
27mod message;
28pub use counter::DraftLimits;
29#[cfg(test)]
30mod layout_tests;
31mod resize;
32mod sizing;
33mod view;
34
35actions!(
36 subspace_chat_input,
37 [
38 ChatNewline,
39 ChatBlockedSubmit,
40 ChatNext,
41 ChatPrevious,
42 ChatComplete,
43 ChatCompleteWithEnter,
44 ChatCancel,
45 ChatNewTab,
46 ChatCloseTab,
47 ChatNextTab,
48 ChatPreviousTab,
49 ChatRenameCancel,
50 ChatSessionNext,
51 ChatSessionPrevious,
52 ChatSessionOpen,
53 ChatSessionRename,
54 ChatSessionDelete
55 ]
56);
57
58pub const CHAT_INPUT_CONTEXT: &str = "SubspaceChatInput";
59pub const CHAT_PANEL_CONTEXT: &str = "SubspaceChat";
61pub const CHAT_RENAME_CONTEXT: &str = "SubspaceChatRename";
63pub const CHAT_SESSIONS_CONTEXT: &str = "SubspaceChatSessions";
65pub const CHAT_SLASH_CONTEXT: &str = "SubspaceChatSlash";
68const CHAT_BLOCKED_SUBMIT_CONTEXT: &str = "SubspaceChatBlockedSubmit";
69pub const CHAT_RECALL_CONTEXT: &str = "SubspaceChatRecall";
72pub const CHAT_LINE_RECALL_CONTEXT: &str = "SubspaceChatLineRecall";
75const MIN_ROWS: usize = 2;
76const MAX_ROWS: usize = 12;
77
78pub fn bind_keys(cx: &mut App) {
83 resize::bind_keys(cx);
84 let input = Some("SubspaceChatInput > Input");
85 let slash = Some("SubspaceChatSlash > Input");
86 let blocked_submit = Some("SubspaceChatBlockedSubmit > Input");
87 let panel = Some(CHAT_PANEL_CONTEXT);
88 let rename = Some("SubspaceChatRename > Input");
89 let sessions = Some(CHAT_SESSIONS_CONTEXT);
90 let recall = Some("SubspaceChatRecall > Input");
91 let line_recall = Some("SubspaceChatLineRecall > Input");
92 cx.bind_keys([
93 KeyBinding::new("up", ChatPrevious, line_recall),
94 KeyBinding::new("down", ChatNext, line_recall),
95 KeyBinding::new("tab", ChatComplete, recall),
96 KeyBinding::new("alt-enter", ChatNewline, input),
97 KeyBinding::new("down", ChatNext, slash),
98 KeyBinding::new("up", ChatPrevious, slash),
99 KeyBinding::new("tab", ChatComplete, slash),
100 KeyBinding::new("enter", ChatCompleteWithEnter, slash),
103 KeyBinding::new("enter", ChatBlockedSubmit, blocked_submit),
104 KeyBinding::new("escape", ChatCancel, slash),
105 KeyBinding::new("escape", ChatRenameCancel, rename),
106 KeyBinding::new(crate::secondary!("t"), ChatNewTab, panel),
107 KeyBinding::new(crate::secondary!("w"), ChatCloseTab, panel),
108 KeyBinding::new(crate::secondary!("shift-]"), ChatNextTab, panel),
110 KeyBinding::new(crate::secondary!("}"), ChatNextTab, panel),
111 KeyBinding::new(crate::secondary!("shift-["), ChatPreviousTab, panel),
112 KeyBinding::new(crate::secondary!("{"), ChatPreviousTab, panel),
113 KeyBinding::new("down", ChatSessionNext, sessions),
114 KeyBinding::new("up", ChatSessionPrevious, sessions),
115 KeyBinding::new("enter", ChatSessionOpen, sessions),
116 KeyBinding::new("f2", ChatSessionRename, sessions),
117 KeyBinding::new("delete", ChatSessionDelete, sessions),
118 KeyBinding::new("backspace", ChatSessionDelete, sessions),
119 ]);
120}
121
122#[derive(Clone)]
123pub struct AttachmentPaste(pub(crate) IngestionBatch);
124
125impl fmt::Debug for AttachmentPaste {
126 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
127 self.0.fmt(formatter)
128 }
129}
130
131impl AttachmentPaste {
132 pub fn batch(&self) -> &IngestionBatch {
133 &self.0
134 }
135}
136
137#[derive(Debug, Clone)]
138pub enum ChatInputEvent {
139 Submit(String),
142 Complete,
144 Next,
146 Previous,
147 Cancel,
149 Changed(String),
151 PasteAttachments(AttachmentPaste),
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum CompletionKey {
160 Tab,
161 Enter,
162}
163
164pub fn submission(text: &str) -> Option<String> {
168 let text = text.trim();
169 (!text.is_empty()).then(|| text.to_owned())
170}
171
172pub struct ChatInput {
174 state: Entity<TextareaState>,
175 attachment_budget: attachments::AttachmentBudget,
176 addon: Option<AnyView>,
177 completing: bool,
179 disabled: bool,
181 recall: bool,
183 recalled: bool,
186 message: Option<message::MessageState>,
187 limits: Option<DraftLimits>,
188 row_limits: (usize, usize),
189 submit_empty: bool,
192 completion_key: Option<CompletionKey>,
194 _subscription: Subscription,
195}
196
197impl EventEmitter<ChatInputEvent> for ChatInput {}
198
199impl ChatInput {
200 pub fn new(engine: &str, window: &mut Window, cx: &mut Context<Self>) -> Self {
202 Self::with_placeholder(format!("Ask {engine}, / for commands"), window, cx)
203 }
204
205 fn with_placeholder(placeholder: String, window: &mut Window, cx: &mut Context<Self>) -> Self {
206 let state = cx.new(|cx| {
207 TextareaState::new(window, cx)
208 .placeholder(placeholder)
209 .submit_on_enter(true)
210 .auto_grow(MIN_ROWS, MAX_ROWS)
211 });
212 let subscription = cx.subscribe(&state, Self::on_input_event);
213 Self {
214 state,
215 attachment_budget: attachments::AttachmentBudget::empty_draft(),
216 addon: None,
217 completing: false,
218 disabled: false,
219 recall: false,
220 recalled: false,
221 message: None,
222 limits: None,
223 row_limits: (MIN_ROWS, MAX_ROWS),
224 submit_empty: false,
225 completion_key: None,
226 _subscription: subscription,
227 }
228 }
229
230 pub fn set_submit_empty(&mut self, submit_empty: bool, cx: &mut Context<Self>) {
234 if self.submit_empty != submit_empty {
235 self.submit_empty = submit_empty;
236 cx.notify();
237 }
238 }
239
240 pub fn set_addon(&mut self, addon: Option<AnyView>, cx: &mut Context<Self>) {
243 self.addon = addon;
244 cx.notify();
245 }
246
247 pub fn text(&self, cx: &App) -> String {
248 self.state.read(cx).value().to_string()
249 }
250
251 pub fn set_limits(&mut self, limits: Option<DraftLimits>, cx: &mut Context<Self>) {
254 if self.limits != limits {
255 self.limits = limits;
256 cx.notify();
257 }
258 }
259
260 fn counter(&self, cx: &App) -> Option<counter::Counter> {
261 self.limits?.counter(&self.text(cx))
262 }
263
264 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
265 let text = text.to_owned();
266 self.state
267 .update(cx, |state, cx| state.set_value(text, window, cx));
268 cx.notify();
269 }
270
271 pub fn set_placeholder(
273 &mut self,
274 placeholder: impl Into<SharedString>,
275 window: &mut Window,
276 cx: &mut Context<Self>,
277 ) {
278 let placeholder = placeholder.into();
279 self.state.update(cx, |state, cx| {
280 state.set_placeholder(placeholder, window, cx)
281 });
282 }
283
284 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
285 self.set_text("", window, cx);
286 }
287
288 pub fn cursor(&self, cx: &App) -> usize {
290 self.state.read(cx).cursor()
291 }
292
293 pub fn selection(&self, cx: &App) -> std::ops::Range<usize> {
296 self.state.read(cx).selected_range()
297 }
298
299 pub fn set_selection(&mut self, range: std::ops::Range<usize>, cx: &mut Context<Self>) {
302 self.state
303 .update(cx, |state, cx| state.set_selected_range(range, cx));
304 }
305
306 pub fn replace_range(
310 &mut self,
311 range: std::ops::Range<usize>,
312 text: &str,
313 window: &mut Window,
314 cx: &mut Context<Self>,
315 ) {
316 let text = text.to_owned();
317 self.state.update(cx, |state, cx| {
318 state.set_selected_range(range, cx);
319 state.replace(text, window, cx);
320 });
321 cx.notify();
322 }
323
324 pub fn focus(&self, window: &mut Window, cx: &mut App) {
325 self.state.update(cx, |state, cx| state.focus(window, cx));
326 }
327
328 pub fn completion_key(&self) -> Option<CompletionKey> {
333 self.completion_key
334 }
335
336 fn complete(&mut self, key: CompletionKey, cx: &mut Context<Self>) {
338 self.completion_key = Some(key);
339 cx.emit(ChatInputEvent::Complete);
340 }
341
342 pub fn set_completing(&mut self, completing: bool, cx: &mut Context<Self>) {
345 self.completing = completing;
346 cx.notify();
347 }
348
349 pub fn set_recall_keys(&mut self, recall: bool, cx: &mut Context<Self>) {
357 self.recall = recall;
358 cx.notify();
359 }
360
361 pub fn set_recalled(&mut self, recalled: bool, cx: &mut Context<Self>) {
367 if self.recalled != recalled {
368 self.recalled = recalled;
369 cx.notify();
370 }
371 }
372
373 pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
376 self.disabled = disabled;
377 cx.notify();
378 }
379
380 fn on_input_event(
381 &mut self,
382 _: Entity<TextareaState>,
383 event: &InputEvent,
384 cx: &mut Context<Self>,
385 ) {
386 match event {
387 InputEvent::Change => {
388 if let Some(message) = &mut self.message {
389 message.error = None;
390 }
391 let text = self.text(cx);
392 cx.emit(ChatInputEvent::Changed(text));
393 cx.notify();
394 }
395 InputEvent::PressEnter { shift: false, .. } => self.enter(cx),
396 _ => {}
397 }
398 }
399
400 fn enter(&mut self, cx: &mut Context<Self>) {
401 if self.disabled
402 || self
403 .message
404 .as_ref()
405 .is_some_and(|message| message.submit_blocked)
406 {
407 return;
408 }
409 if self.completing {
410 self.complete(CompletionKey::Enter, cx);
411 return;
412 }
413 match submission(&self.text(cx)) {
414 Some(text) => cx.emit(ChatInputEvent::Submit(text)),
415 None if self.submit_empty => cx.emit(ChatInputEvent::Submit(String::new())),
416 None => {}
417 }
418 }
419
420 fn newline(&mut self, _: &ChatNewline, window: &mut Window, cx: &mut Context<Self>) {
421 self.state
422 .update(cx, |state, cx| state.insert("\n", window, cx));
423 }
424
425 fn key_context(&self, os: OperatingSystem) -> KeyContext {
427 let mut context = KeyContext::new_with_defaults(os);
428 context.add(CHAT_INPUT_CONTEXT);
429 if self
430 .message
431 .as_ref()
432 .is_some_and(|message| message.submit_blocked)
433 {
434 context.add(CHAT_BLOCKED_SUBMIT_CONTEXT);
435 } else if self.completing {
436 context.add(CHAT_SLASH_CONTEXT);
437 }
438 if self.recall {
439 context.add(CHAT_RECALL_CONTEXT);
440 context.add(CHAT_LINE_RECALL_CONTEXT);
441 }
442 context
443 }
444
445 fn vertical_arrow(&mut self, previous: bool, window: &mut Window, cx: &mut Context<Self>) {
446 let end = self.state.read(cx).text().len();
447 if self.completing || self.recalled || end == 0 {
448 let event = if previous {
449 ChatInputEvent::Previous
450 } else {
451 ChatInputEvent::Next
452 };
453 cx.emit(event);
454 } else {
455 let offset = if previous { 0 } else { end };
456 self.state.update(cx, |state, cx| {
457 let position = state.text().offset_to_position(offset);
458 state.set_cursor_position(position, window, cx);
459 });
460 }
461 }
462}
463
464impl Render for ChatInput {
465 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
466 resize::sync_rows(self, window, cx);
467 let tokens = Tokens::current(cx);
468 div()
469 .id("chat-input-frame")
470 .relative()
471 .w_full()
472 .min_w_0()
473 .flex_shrink_0()
474 .when(self.compact().is_none(), |frame| {
475 frame.border_t_1().border_color(tokens.line)
476 })
477 .key_context(self.key_context(cx.platform_info().os))
478 .on_action(cx.listener(Self::newline))
479 .on_action(|_: &ChatBlockedSubmit, _, _| {})
480 .on_action(
481 cx.listener(|this, _: &ChatNext, window, cx| {
482 this.vertical_arrow(false, window, cx)
483 }),
484 )
485 .on_action(cx.listener(|this, _: &ChatPrevious, window, cx| {
486 this.vertical_arrow(true, window, cx)
487 }))
488 .on_action(cx.listener(|this, _: &ChatComplete, _, cx| {
489 this.complete(CompletionKey::Tab, cx);
490 }))
491 .on_action(cx.listener(|this, _: &ChatCompleteWithEnter, _, cx| {
492 this.complete(CompletionKey::Enter, cx);
493 }))
494 .on_action(cx.listener(|_, _: &ChatCancel, _, cx| cx.emit(ChatInputEvent::Cancel)))
495 .text_size(tokens.row_font)
496 .on_drag_move::<resize::InputResize>(cx.listener(resize::drag))
497 .child(view::group(self, window, cx))
498 .children(resize::handle(self, cx))
499 }
500}
501
502#[cfg(test)]
503mod tests {
504 use super::{ChatInput, ChatInputEvent, submission};
505 use crate::chat_input::attachments::{AttachmentSource, MAX_DRAFT_IMAGES};
506 use gpui_kit::component::input::Paste;
507 use gpui_kit::{
508 AppContext as _, ClipboardEntry, ClipboardItem, Entity, Image, ImageFormat, IntoElement,
509 ParentElement as _, Render, Subscription, TestAppContext, Window, div,
510 };
511 use std::cell::RefCell;
512 use std::rc::Rc;
513 use subspace_agent_model::DRAFT_ATTACHMENT_LIMIT;
514
515 struct PasteHarness {
516 input: Entity<ChatInput>,
517 _subscription: Subscription,
518 }
519
520 impl PasteHarness {
521 fn new(
522 events: Rc<RefCell<Vec<ChatInputEvent>>>,
523 window: &mut Window,
524 cx: &mut gpui_kit::Context<Self>,
525 ) -> Self {
526 let input = cx.new(|cx| ChatInput::new("Copilot", window, cx));
527 let subscription = cx.subscribe(&input, move |_, _, event, _| {
528 events.borrow_mut().push(event.clone());
529 });
530 Self {
531 input,
532 _subscription: subscription,
533 }
534 }
535 }
536
537 impl Render for PasteHarness {
538 fn render(&mut self, _: &mut Window, _: &mut gpui_kit::Context<Self>) -> impl IntoElement {
539 div().child(self.input.clone())
540 }
541 }
542
543 #[test]
544 fn enter_sends_trimmed_text_and_nothing_else() {
545 assert_eq!(submission(" hello \n").as_deref(), Some("hello"));
546 assert_eq!(submission(" "), None, "empty text");
547 assert_eq!(
548 submission("steer left").as_deref(),
549 Some("steer left"),
550 "a running turn no longer blocks the input"
551 );
552 }
553
554 #[gpui_kit::test]
555 fn empty_enter_submits_only_when_the_owner_opts_in(cx: &mut TestAppContext) {
556 cx.update(gpui_kit::init);
557 let events = Rc::new(RefCell::new(Vec::new()));
558 let captured = events.clone();
559 let (harness, cx) =
560 cx.add_window_view(|window, cx| PasteHarness::new(captured, window, cx));
561 let input = harness.read_with(cx, |harness, _| harness.input.clone());
562 input.update(cx, |input, cx| input.enter(cx));
563 assert!(events.borrow().is_empty(), "off by default");
564 input.update(cx, |input, cx| {
565 input.set_submit_empty(true, cx);
566 input.enter(cx);
567 });
568 assert!(matches!(
569 events.borrow().as_slice(),
570 [ChatInputEvent::Submit(text)] if text.is_empty()
571 ));
572 }
573
574 #[gpui_kit::test]
575 fn textarea_paste_emits_images_but_preserves_ordinary_text(cx: &mut TestAppContext) {
576 cx.update(gpui_kit::init);
577 let events = Rc::new(RefCell::new(Vec::new()));
578 let captured = events.clone();
579 let (harness, cx) =
580 cx.add_window_view(|window, cx| PasteHarness::new(captured, window, cx));
581 cx.update(|window, cx| {
582 let input = harness.read(cx).input.clone();
583 input.update(cx, |input, cx| input.focus(window, cx));
584 let _ = window.draw(cx);
585 cx.write_to_clipboard(ClipboardItem::new_image(&Image::from_bytes(
586 ImageFormat::Png,
587 vec![1, 2, 3],
588 )));
589 window.dispatch_action(Box::new(Paste), cx);
590 });
591 cx.run_until_parked();
592 cx.update(|window, cx| {
593 cx.write_to_clipboard(ClipboardItem::new_string("ordinary text".into()));
594 window.dispatch_action(Box::new(Paste), cx);
595 });
596 cx.run_until_parked();
597 assert!(
598 events.borrow().iter().any(|event| matches!(
599 event,
600 ChatInputEvent::PasteAttachments(super::AttachmentPaste(batch))
601 if matches!(batch.sources.as_slice(), [AttachmentSource::ClipboardImage { .. }])
602 )),
603 "the actual textarea callback should emit one bounded image batch"
604 );
605 assert_eq!(
606 cx.update(|_, cx| harness.read(cx).input.read(cx).text(cx)),
607 "ordinary text"
608 );
609 }
610
611 #[gpui_kit::test]
612 fn textarea_paste_never_emits_unbounded_image_payloads(cx: &mut TestAppContext) {
613 cx.update(gpui_kit::init);
614 let events = Rc::new(RefCell::new(Vec::new()));
615 let captured = events.clone();
616 let (harness, cx) =
617 cx.add_window_view(|window, cx| PasteHarness::new(captured, window, cx));
618 cx.update(|window, cx| {
619 let input = harness.read(cx).input.clone();
620 input.update(cx, |input, cx| input.focus(window, cx));
621 let _ = window.draw(cx);
622 let entries =
623 std::iter::once(ClipboardEntry::Image(Image::from_bytes(
624 ImageFormat::Png,
625 vec![0; crate::images::MAX_ENCODED_BYTES + 1],
626 )))
627 .chain((0..3).map(|_| {
628 ClipboardEntry::Image(Image::from_bytes(
629 ImageFormat::Png,
630 vec![1_u8; crate::images::MAX_ENCODED_BYTES],
631 ))
632 }))
633 .chain((0..MAX_DRAFT_IMAGES + 20).map(|_| {
634 ClipboardEntry::Image(Image::from_bytes(ImageFormat::Png, vec![1_u8; 1]))
635 }))
636 .collect();
637 cx.write_to_clipboard(ClipboardItem { entries });
638 window.dispatch_action(Box::new(Paste), cx);
639 });
640 cx.run_until_parked();
641 let events = events.borrow();
642 let Some(ChatInputEvent::PasteAttachments(super::AttachmentPaste(batch))) = events.last()
643 else {
644 panic!("the actual textarea callback did not emit attachments");
645 };
646 let image_bytes = batch
647 .sources
648 .iter()
649 .filter_map(|source| match source {
650 AttachmentSource::ClipboardImage { bytes, .. } => Some(bytes.len()),
651 AttachmentSource::Path(_) => None,
652 })
653 .collect::<Vec<_>>();
654 assert_eq!(image_bytes.len(), MAX_DRAFT_IMAGES);
655 assert_eq!(
656 image_bytes
657 .iter()
658 .filter(|size| **size == crate::images::MAX_ENCODED_BYTES)
659 .count(),
660 2
661 );
662 assert!(image_bytes.iter().sum::<usize>() <= DRAFT_ATTACHMENT_LIMIT);
663 assert!(batch.notice.is_some());
664 }
665}