BlueGit

ict rusty-teams

Files

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

copilot.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
copilot.rs 13.8 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::{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/copilot";
17const COPILOT_SCROLL_DIVIDER: &str = "shell/islands/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 FAILED: &str = "Copilot could not answer:";
25const GREETING: &str = "Hi, how can I help?";
26const LOGO_ASSET: &str = "symbols/copilot_color.svg";
27const LOGO_BUTTON: f32 = 18.;
28const LOGO_TITLE: f32 = 20.;
29const INPUT_MIN_HEIGHT: f32 = 72.;
30const INPUT_RADIUS: f32 = 12.;
31const CHIP_RADIUS: f32 = 8.;
32const SUGGESTIONS: [&str; 3] = [
33 "Summarize this chat",
34 "What are open items?",
35 "What decisions were made?",
36];
37const PANE_WIDTH: f32 = 400.;
38const ISLAND_RADIUS: f32 = 10.;
39const PANE_PADDING: f32 = 16.;
40const HEADER_HEIGHT: f32 = 48.;
41const BUTTON_SIZE: f32 = 32.;
42const BUBBLE_RADIUS: f32 = 8.;
43
44#[derive(Default)]
45pub(super) struct CopilotPane {
46 open: bool,
47 turns: Vec<CopilotTurn>,
48 input: Option<Entity<InputState>>,
49 scroll: ScrollHandle,
50 generation: u64,
51 _input_events: Option<Subscription>,
52}
53
54struct CopilotTurn {
55 prompt: String,
56 answer: CopilotAnswer,
57}
58
59enum CopilotAnswer {
60 Waiting,
61 Ready(String),
62 Failed(String),
63}
64
65impl ConversationView {
66 fn copilot_chat_id(&self) -> Option<String> {
67 match &self.current.as_ref()?.selection {
68 Selection::Chat(chat_id) => Some(chat_id.clone()),
69 Selection::Channel(_) => None,
70 }
71 }
72
73 pub(super) fn copilot_label(&self) -> &'static str {
74 if self.copilot.open {
75 CLOSE_LABEL
76 } else {
77 OPEN_LABEL
78 }
79 }
80
81 pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
82 self.copilot_chat_id()?;
83 let open = self.copilot.open;
84 Some(
85 Button::new("copilot-toggle")
86 .child(copilot_logo(LOGO_BUTTON))
87 .ghost()
88 .size(px(BUTTON_SIZE))
89 .rounded(px(8.))
90 .when(open, |button| button.selected(true))
91 .tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
92 .on_click(cx.listener(|this, _, window, cx| this.toggle_copilot(window, cx)))
93 .into_any_element(),
94 )
95 }
96
97 pub(super) fn toggle_copilot(&mut self, window: &mut Window, cx: &mut Context<Self>) {
98 self.copilot.open = !self.copilot.open;
99 if self.copilot.open && self.copilot.input.is_none() {
100 let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
101 let subscription = cx.subscribe_in(
102 &input,
103 window,
104 |this, input, event: &InputEvent, window, cx| {
105 if matches!(event, InputEvent::PressEnter { .. }) {
106 let prompt = input.read(cx).value().trim().to_owned();
107 if !prompt.is_empty() {
108 input.update(cx, |input, cx| input.set_value("", window, cx));
109 this.ask_copilot(prompt, cx);
110 }
111 }
112 },
113 );
114 self.copilot.input = Some(input);
115 self.copilot._input_events = Some(subscription);
116 }
117 if self.copilot.open {
118 self.channel_details_open = false;
119 self.find_panel = None;
120 self.find_subscription = None;
121 if let Some(input) = &self.copilot.input {
122 input.update(cx, |input, cx| input.focus(window, cx));
123 }
124 }
125 cx.notify();
126 }
127
128 pub(super) fn close_copilot(&mut self) {
129 self.copilot.open = false;
130 }
131
132 pub(super) fn reset_copilot(&mut self) {
133 let input = self.copilot.input.take();
134 let events = self.copilot._input_events.take();
135 self.copilot = CopilotPane {
136 input,
137 generation: self.copilot.generation + 1,
138 _input_events: events,
139 ..CopilotPane::default()
140 };
141 }
142
143 fn ask_copilot(&mut self, prompt: String, cx: &mut Context<Self>) {
144 let Some(chat_id) = self.copilot_chat_id() else {
145 return;
146 };
147 let index = self.copilot.turns.len();
148 let generation = self.copilot.generation;
149 self.copilot.turns.push(CopilotTurn {
150 prompt: prompt.clone(),
151 answer: CopilotAnswer::Waiting,
152 });
153 self.copilot.scroll.scroll_to_bottom();
154 cx.notify();
155 let Some(engine) = self.app.read(cx).engine.clone() else {
156 self.settle_copilot(generation, index, Err(UNAVAILABLE.to_owned()), cx);
157 return;
158 };
159 let receiver = runtime::spawn(async move { engine.ask_copilot(&chat_id, &prompt).await });
160 cx.spawn(async move |this, cx| {
161 let answer = match receiver.await {
162 Ok(Ok(text)) => Ok(text),
163 Ok(Err(error)) => Err(error.to_string()),
164 Err(error) => Err(error.to_string()),
165 };
166 this.update(cx, |this, cx| {
167 this.settle_copilot(generation, index, answer, cx)
168 })
169 .ok();
170 })
171 .detach();
172 }
173
174 fn settle_copilot(
175 &mut self,
176 generation: u64,
177 index: usize,
178 answer: Result<String, String>,
179 cx: &mut Context<Self>,
180 ) {
181 if generation != self.copilot.generation {
182 return;
183 }
184 let Some(turn) = self.copilot.turns.get_mut(index) else {
185 return;
186 };
187 turn.answer = match answer {
188 Ok(text) => CopilotAnswer::Ready(text),
189 Err(error) => CopilotAnswer::Failed(format!(
190 "{FAILED} {}",
191 error.split(" (https://").next().unwrap_or_default()
192 )),
193 };
194 self.copilot.scroll.scroll_to_bottom();
195 cx.notify();
196 }
197
198 pub(super) fn render_copilot(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
199 if !self.copilot.open {
200 return None;
201 }
202 self.copilot_chat_id()?;
203 let busy = self
204 .copilot
205 .turns
206 .last()
207 .is_some_and(|turn| matches!(turn.answer, CopilotAnswer::Waiting));
208 let input_box = self.copilot.input.as_ref().map(|input| {
209 div()
210 .w_full()
211 .min_h(px(INPUT_MIN_HEIGHT))
212 .px(px(12.))
213 .py(px(10.))
214 .rounded(px(INPUT_RADIUS))
215 .bg(theme::surface_raised())
216 .child(Input::new(input).appearance(false).bordered(false))
217 });
218 let content = if self.copilot.turns.is_empty() {
219 let suggestions =
220 v_flex()
221 .w_full()
222 .gap(px(8.))
223 .children(SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
224 div()
225 .id(("copilot-suggestion", index))
226 .w_full()
227 .px(px(12.))
228 .py(px(10.))
229 .rounded(px(CHIP_RADIUS))
230 .bg(theme::surface_raised())
231 .text_size(px(12.))
232 .font_weight(FontWeight::SEMIBOLD)
233 .text_color(theme::text())
234 .cursor_pointer()
235 .hover(|chip| chip.bg(theme::row_hover()))
236 .child(*prompt)
237 .on_click(cx.listener(move |this, _, _, cx| {
238 this.ask_copilot((*prompt).to_owned(), cx)
239 }))
240 }));
241 v_flex()
242 .flex_1()
243 .min_h_0()
244 .px(px(PANE_PADDING))
245 .pb(px(PANE_PADDING))
246 .justify_center()
247 .gap(px(16.))
248 .child(
249 div()
250 .px(px(4.))
251 .text_size(px(24.))
252 .text_color(theme::text())
253 .child(GREETING),
254 )
255 .children(input_box)
256 .child(suggestions)
257 .into_any_element()
258 } else {
259 let mut body = v_flex()
260 .w_full()
261 .px(px(PANE_PADDING))
262 .pb(px(PANE_PADDING))
263 .gap(px(12.));
264 for (index, turn) in self.copilot.turns.iter().enumerate() {
265 body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(
266 index,
267 &turn.answer,
268 cx,
269 ));
270 }
271 v_flex()
272 .flex_1()
273 .min_h_0()
274 .child(with_top_edge(
275 div()
276 .id("copilot-body")
277 .flex_1()
278 .min_h_0()
279 .overflow_y_scrollbar()
280 .track_scroll(&self.copilot.scroll)
281 .child(body),
282 &self.copilot.scroll,
283 COPILOT_SCROLL_DIVIDER,
284 ))
285 .child(
286 div()
287 .flex_none()
288 .px(px(PANE_PADDING))
289 .pb(px(PANE_PADDING))
290 .when(busy, |footer| footer.opacity(0.6))
291 .children(input_box),
292 )
293 .into_any_element()
294 };
295 Some(
296 h_flex()
297 .h_full()
298 .flex_none()
299 .child(
300 v_flex()
301 .debug_selector(|| COPILOT_PANE_TAG.into())
302 .w(px(PANE_WIDTH))
303 .h_full()
304 .rounded(px(ISLAND_RADIUS))
305 .overflow_hidden()
306 .bg(theme::surface())
307 .child(
308 h_flex()
309 .h(px(HEADER_HEIGHT))
310 .flex_none()
311 .px(px(PANE_PADDING))
312 .items_center()
313 .justify_between()
314 .child(
315 h_flex()
316 .gap(px(8.))
317 .items_center()
318 .child(copilot_logo(LOGO_TITLE))
319 .child(
320 div()
321 .text_size(px(15.))
322 .font_weight(FontWeight::SEMIBOLD)
323 .text_color(theme::text())
324 .child(TITLE),
325 ),
326 )
327 .child(
328 Button::new("copilot-close")
329 .icon(IconName::X)
330 .ghost()
331 .size(px(BUTTON_SIZE))
332 .rounded(px(8.))
333 .tooltip(CLOSE_LABEL)
334 .on_click(cx.listener(|this, _, _, cx| {
335 this.copilot.open = false;
336 cx.notify();
337 })),
338 ),
339 )
340 .child(content),
341 )
342 .into_any_element(),
343 )
344 }
345}
346
347fn copilot_logo(size: f32) -> Img {
348 img(LOGO_ASSET).size(px(size)).flex_none()
349}
350
351fn prompt_bubble(prompt: &str) -> Div {
352 h_flex().w_full().justify_end().child(
353 div()
354 .max_w(px(PANE_WIDTH * 0.8))
355 .px(px(10.))
356 .py(px(6.))
357 .rounded(px(BUBBLE_RADIUS))
358 .bg(theme::row_hover())
359 .text_size(px(13.))
360 .text_color(theme::text())
361 .child(prompt.to_owned()),
362 )
363}
364
365fn answer_view(index: usize, answer: &CopilotAnswer, cx: &App) -> AnyElement {
366 match answer {
367 CopilotAnswer::Waiting => div()
368 .text_size(px(13.))
369 .text_color(theme::text_muted())
370 .child(WORKING)
371 .into_any_element(),
372 CopilotAnswer::Failed(error) => div()
373 .text_size(px(13.))
374 .text_color(theme::red())
375 .child(error.clone())
376 .into_any_element(),
377 CopilotAnswer::Ready(text) => {
378 let spans = teams_core::html_to_spans(&teams_core::markdown_to_html(text));
379 div()
380 .w_full()
381 .text_size(px(13.))
382 .child(render_blocks(
383 &layout_card_blocks(&spans),
384 &format!("copilot-answer-{index}"),
385 false,
386 cx,
387 ))
388 .into_any_element()
389 }
390 }
391}