BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / conversation / copilot.rs

copilot.rs

b703fbc2 History
copilot.rs 11.2 KiB Download Raw
1use gpui_kit::assets::IconName;
2use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::input::{Input, InputEvent, InputState};
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{Disableable as _, Selectable as _, h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8
9use super::ConversationView;
10use crate::app_state::Selection;
11use crate::render::{layout_card_blocks, render_blocks};
12use crate::runtime;
13use crate::theme;
14use crate::views::scroll_edge::with_top_edge;
15
16pub const COPILOT_PANE_TAG: &str = "shell/islands/main/copilot";
17const COPILOT_SCROLL_DIVIDER: &str = "shell/islands/main/copilot/divider-scroll";
18const TITLE: &str = "Copilot";
19const OPEN_LABEL: &str = "Open Copilot";
20const CLOSE_LABEL: &str = "Close Copilot";
21const PLACEHOLDER: &str = "Message Copilot";
22const WORKING: &str = "Copilot is reading the chat ...";
23const UNAVAILABLE: &str = "Copilot needs a signed-in account.";
24const INTRO: &str = "Ask Copilot about this chat.";
25const SUGGESTIONS: [&str; 3] = [
26 "Summarize this chat",
27 "What are open items?",
28 "What decisions were made?",
29];
30const PANE_WIDTH: f32 = 360.;
31const PANE_PADDING: f32 = 16.;
32const HEADER_HEIGHT: f32 = 48.;
33const BUTTON_SIZE: f32 = 32.;
34const BUBBLE_RADIUS: f32 = 8.;
35
36#[derive(Default)]
37pub(super) struct CopilotPane {
38 open: bool,
39 turns: Vec<CopilotTurn>,
40 input: Option<Entity<InputState>>,
41 scroll: ScrollHandle,
42 generation: u64,
43 _input_events: Option<Subscription>,
44}
45
46struct CopilotTurn {
47 prompt: String,
48 answer: CopilotAnswer,
49}
50
51enum CopilotAnswer {
52 Waiting,
53 Ready(String),
54 Failed(String),
55}
56
57impl ConversationView {
58 fn copilot_chat_id(&self) -> Option<String> {
59 match &self.current.as_ref()?.selection {
60 Selection::Chat(chat_id) => Some(chat_id.clone()),
61 Selection::Channel(_) => None,
62 }
63 }
64
65 pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
66 self.copilot_chat_id()?;
67 let open = self.copilot.open;
68 Some(
69 Button::new("copilot-toggle")
70 .icon(IconName::Sparkles)
71 .ghost()
72 .size(px(BUTTON_SIZE))
73 .rounded(px(8.))
74 .when(open, |button| button.selected(true))
75 .tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
76 .on_click(cx.listener(|this, _, window, cx| this.toggle_copilot(window, cx)))
77 .into_any_element(),
78 )
79 }
80
81 fn toggle_copilot(&mut self, window: &mut Window, cx: &mut Context<Self>) {
82 self.copilot.open = !self.copilot.open;
83 if self.copilot.open && self.copilot.input.is_none() {
84 let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
85 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
86 if matches!(event, InputEvent::PressEnter { .. }) {
87 let prompt = input.read(cx).value().trim().to_owned();
88 if !prompt.is_empty() {
89 input.update(cx, |input, cx| input.set_value("", window, cx));
90 this.ask_copilot(prompt, cx);
91 }
92 }
93 });
94 self.copilot.input = Some(input);
95 self.copilot._input_events = Some(subscription);
96 }
97 if self.copilot.open {
98 self.channel_details_open = false;
99 self.find_panel = None;
100 self.find_subscription = None;
101 if let Some(input) = &self.copilot.input {
102 input.update(cx, |input, cx| input.focus(window, cx));
103 }
104 }
105 cx.notify();
106 }
107
108 pub(super) fn close_copilot(&mut self) {
109 self.copilot.open = false;
110 }
111
112 pub(super) fn reset_copilot(&mut self) {
113 let input = self.copilot.input.take();
114 let events = self.copilot._input_events.take();
115 self.copilot = CopilotPane {
116 input,
117 generation: self.copilot.generation + 1,
118 _input_events: events,
119 ..CopilotPane::default()
120 };
121 }
122
123 fn ask_copilot(&mut self, prompt: String, cx: &mut Context<Self>) {
124 let Some(chat_id) = self.copilot_chat_id() else {
125 return;
126 };
127 let index = self.copilot.turns.len();
128 let generation = self.copilot.generation;
129 self.copilot.turns.push(CopilotTurn {
130 prompt: prompt.clone(),
131 answer: CopilotAnswer::Waiting,
132 });
133 self.copilot.scroll.scroll_to_bottom();
134 cx.notify();
135 let Some(engine) = self.app.read(cx).engine.clone() else {
136 self.settle_copilot(generation, index, Err(UNAVAILABLE.to_owned()), cx);
137 return;
138 };
139 let receiver = runtime::spawn(async move { engine.ask_copilot(&chat_id, &prompt).await });
140 cx.spawn(async move |this, cx| {
141 let answer = match receiver.await {
142 Ok(Ok(text)) => Ok(text),
143 Ok(Err(error)) => Err(error.to_string()),
144 Err(error) => Err(error.to_string()),
145 };
146 this.update(cx, |this, cx| this.settle_copilot(generation, index, answer, cx))
147 .ok();
148 })
149 .detach();
150 }
151
152 fn settle_copilot(
153 &mut self,
154 generation: u64,
155 index: usize,
156 answer: Result<String, String>,
157 cx: &mut Context<Self>,
158 ) {
159 if generation != self.copilot.generation {
160 return;
161 }
162 let Some(turn) = self.copilot.turns.get_mut(index) else {
163 return;
164 };
165 turn.answer = match answer {
166 Ok(text) => CopilotAnswer::Ready(text),
167 Err(error) => CopilotAnswer::Failed(error),
168 };
169 self.copilot.scroll.scroll_to_bottom();
170 cx.notify();
171 }
172
173 pub(super) fn render_copilot(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
174 if !self.copilot.open {
175 return None;
176 }
177 self.copilot_chat_id()?;
178 let mut body = v_flex()
179 .w_full()
180 .px(px(PANE_PADDING))
181 .pb(px(PANE_PADDING))
182 .gap(px(12.));
183 if self.copilot.turns.is_empty() {
184 body = body.child(
185 div()
186 .text_size(px(13.))
187 .text_color(theme::text_muted())
188 .child(INTRO),
189 );
190 }
191 for (index, turn) in self.copilot.turns.iter().enumerate() {
192 body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(index, &turn.answer, cx));
193 }
194 let busy = self
195 .copilot
196 .turns
197 .last()
198 .is_some_and(|turn| matches!(turn.answer, CopilotAnswer::Waiting));
199 let suggestions = h_flex().flex_wrap().gap(px(6.)).children(
200 SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
201 Button::new(("copilot-suggestion", index))
202 .label(*prompt)
203 .outline()
204 .rounded(px(BUBBLE_RADIUS))
205 .disabled(busy)
206 .on_click(cx.listener(move |this, _, _, cx| {
207 this.ask_copilot((*prompt).to_owned(), cx)
208 }))
209 }),
210 );
211 let footer = v_flex()
212 .flex_none()
213 .px(px(PANE_PADDING))
214 .py(px(12.))
215 .gap(px(8.))
216 .child(suggestions)
217 .children(self.copilot.input.as_ref().map(|input| Input::new(input)));
218 Some(
219 h_flex()
220 .h_full()
221 .flex_none()
222 .child(div().w(px(1.)).h_full().flex_none().bg(theme::border()))
223 .child(
224 v_flex()
225 .debug_selector(|| COPILOT_PANE_TAG.into())
226 .w(px(PANE_WIDTH))
227 .h_full()
228 .bg(theme::surface())
229 .child(
230 h_flex()
231 .h(px(HEADER_HEIGHT))
232 .flex_none()
233 .px(px(PANE_PADDING))
234 .items_center()
235 .justify_between()
236 .child(
237 div()
238 .text_size(px(15.))
239 .font_weight(FontWeight::SEMIBOLD)
240 .text_color(theme::text())
241 .child(TITLE),
242 )
243 .child(
244 Button::new("copilot-close")
245 .icon(IconName::X)
246 .ghost()
247 .size(px(BUTTON_SIZE))
248 .rounded(px(8.))
249 .tooltip(CLOSE_LABEL)
250 .on_click(cx.listener(|this, _, _, cx| {
251 this.copilot.open = false;
252 cx.notify();
253 })),
254 ),
255 )
256 .child(with_top_edge(
257 div()
258 .id("copilot-body")
259 .flex_1()
260 .min_h_0()
261 .overflow_y_scrollbar()
262 .track_scroll(&self.copilot.scroll)
263 .child(body),
264 &self.copilot.scroll,
265 COPILOT_SCROLL_DIVIDER,
266 ))
267 .child(footer),
268 )
269 .into_any_element(),
270 )
271 }
272}
273
274fn prompt_bubble(prompt: &str) -> Div {
275 h_flex().w_full().justify_end().child(
276 div()
277 .max_w(px(PANE_WIDTH * 0.8))
278 .px(px(10.))
279 .py(px(6.))
280 .rounded(px(BUBBLE_RADIUS))
281 .bg(theme::row_hover())
282 .text_size(px(13.))
283 .text_color(theme::text())
284 .child(prompt.to_owned()),
285 )
286}
287
288fn answer_view(index: usize, answer: &CopilotAnswer, cx: &App) -> AnyElement {
289 match answer {
290 CopilotAnswer::Waiting => div()
291 .text_size(px(13.))
292 .text_color(theme::text_muted())
293 .child(WORKING)
294 .into_any_element(),
295 CopilotAnswer::Failed(error) => div()
296 .text_size(px(13.))
297 .text_color(theme::red())
298 .child(error.clone())
299 .into_any_element(),
300 CopilotAnswer::Ready(text) => {
301 let spans = teams_core::html_to_spans(&teams_core::markdown_to_html(text));
302 div()
303 .w_full()
304 .text_size(px(13.))
305 .child(render_blocks(
306 &layout_card_blocks(&spans),
307 &format!("copilot-answer-{index}"),
308 false,
309 cx,
310 ))
311 .into_any_element()
312 }
313 }
314}