BlueGit

ict rusty-teams

Files

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

copilot.rs

copilot.rs 13.3 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_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
74 self.copilot_chat_id()?;
75 let open = self.copilot.open;
76 Some(
77 Button::new("copilot-toggle")
78 .child(copilot_logo(LOGO_BUTTON))
79 .ghost()
80 .size(px(BUTTON_SIZE))
81 .rounded(px(8.))
82 .when(open, |button| button.selected(true))
83 .tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
84 .on_click(cx.listener(|this, _, window, cx| this.toggle_copilot(window, cx)))
85 .into_any_element(),
86 )
87 }
88
89 fn toggle_copilot(&mut self, window: &mut Window, cx: &mut Context<Self>) {
90 self.copilot.open = !self.copilot.open;
91 if self.copilot.open && self.copilot.input.is_none() {
92 let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
93 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
94 if matches!(event, InputEvent::PressEnter { .. }) {
95 let prompt = input.read(cx).value().trim().to_owned();
96 if !prompt.is_empty() {
97 input.update(cx, |input, cx| input.set_value("", window, cx));
98 this.ask_copilot(prompt, cx);
99 }
100 }
101 });
102 self.copilot.input = Some(input);
103 self.copilot._input_events = Some(subscription);
104 }
105 if self.copilot.open {
106 self.channel_details_open = false;
107 self.find_panel = None;
108 self.find_subscription = None;
109 if let Some(input) = &self.copilot.input {
110 input.update(cx, |input, cx| input.focus(window, cx));
111 }
112 }
113 cx.notify();
114 }
115
116 pub(super) fn close_copilot(&mut self) {
117 self.copilot.open = false;
118 }
119
120 pub(super) fn reset_copilot(&mut self) {
121 let input = self.copilot.input.take();
122 let events = self.copilot._input_events.take();
123 self.copilot = CopilotPane {
124 input,
125 generation: self.copilot.generation + 1,
126 _input_events: events,
127 ..CopilotPane::default()
128 };
129 }
130
131 fn ask_copilot(&mut self, prompt: String, cx: &mut Context<Self>) {
132 let Some(chat_id) = self.copilot_chat_id() else {
133 return;
134 };
135 let index = self.copilot.turns.len();
136 let generation = self.copilot.generation;
137 self.copilot.turns.push(CopilotTurn {
138 prompt: prompt.clone(),
139 answer: CopilotAnswer::Waiting,
140 });
141 self.copilot.scroll.scroll_to_bottom();
142 cx.notify();
143 let Some(engine) = self.app.read(cx).engine.clone() else {
144 self.settle_copilot(generation, index, Err(UNAVAILABLE.to_owned()), cx);
145 return;
146 };
147 let receiver = runtime::spawn(async move { engine.ask_copilot(&chat_id, &prompt).await });
148 cx.spawn(async move |this, cx| {
149 let answer = match receiver.await {
150 Ok(Ok(text)) => Ok(text),
151 Ok(Err(error)) => Err(error.to_string()),
152 Err(error) => Err(error.to_string()),
153 };
154 this.update(cx, |this, cx| this.settle_copilot(generation, index, answer, cx))
155 .ok();
156 })
157 .detach();
158 }
159
160 fn settle_copilot(
161 &mut self,
162 generation: u64,
163 index: usize,
164 answer: Result<String, String>,
165 cx: &mut Context<Self>,
166 ) {
167 if generation != self.copilot.generation {
168 return;
169 }
170 let Some(turn) = self.copilot.turns.get_mut(index) else {
171 return;
172 };
173 turn.answer = match answer {
174 Ok(text) => CopilotAnswer::Ready(text),
175 Err(error) => CopilotAnswer::Failed(format!(
176 "{FAILED} {}",
177 error.split(" (https://").next().unwrap_or_default()
178 )),
179 };
180 self.copilot.scroll.scroll_to_bottom();
181 cx.notify();
182 }
183
184 pub(super) fn render_copilot(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
185 if !self.copilot.open {
186 return None;
187 }
188 self.copilot_chat_id()?;
189 let busy = self
190 .copilot
191 .turns
192 .last()
193 .is_some_and(|turn| matches!(turn.answer, CopilotAnswer::Waiting));
194 let input_box = self.copilot.input.as_ref().map(|input| {
195 div()
196 .w_full()
197 .min_h(px(INPUT_MIN_HEIGHT))
198 .px(px(12.))
199 .py(px(10.))
200 .rounded(px(INPUT_RADIUS))
201 .bg(theme::surface_raised())
202 .child(Input::new(input).appearance(false).bordered(false))
203 });
204 let content = if self.copilot.turns.is_empty() {
205 let suggestions = v_flex().w_full().gap(px(8.)).children(
206 SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
207 div()
208 .id(("copilot-suggestion", index))
209 .w_full()
210 .px(px(12.))
211 .py(px(10.))
212 .rounded(px(CHIP_RADIUS))
213 .bg(theme::surface_raised())
214 .text_size(px(12.))
215 .font_weight(FontWeight::SEMIBOLD)
216 .text_color(theme::text())
217 .cursor_pointer()
218 .hover(|chip| chip.bg(theme::row_hover()))
219 .child(*prompt)
220 .on_click(cx.listener(move |this, _, _, cx| {
221 this.ask_copilot((*prompt).to_owned(), cx)
222 }))
223 }),
224 );
225 v_flex()
226 .flex_1()
227 .min_h_0()
228 .px(px(PANE_PADDING))
229 .pb(px(PANE_PADDING))
230 .justify_center()
231 .gap(px(16.))
232 .child(
233 div()
234 .px(px(4.))
235 .text_size(px(24.))
236 .text_color(theme::text())
237 .child(GREETING),
238 )
239 .children(input_box)
240 .child(suggestions)
241 .into_any_element()
242 } else {
243 let mut body = v_flex()
244 .w_full()
245 .px(px(PANE_PADDING))
246 .pb(px(PANE_PADDING))
247 .gap(px(12.));
248 for (index, turn) in self.copilot.turns.iter().enumerate() {
249 body = body
250 .child(prompt_bubble(&turn.prompt))
251 .child(answer_view(index, &turn.answer, cx));
252 }
253 v_flex()
254 .flex_1()
255 .min_h_0()
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(
268 div()
269 .flex_none()
270 .px(px(PANE_PADDING))
271 .pb(px(PANE_PADDING))
272 .when(busy, |footer| footer.opacity(0.6))
273 .children(input_box),
274 )
275 .into_any_element()
276 };
277 Some(
278 h_flex()
279 .h_full()
280 .flex_none()
281 .child(
282 v_flex()
283 .debug_selector(|| COPILOT_PANE_TAG.into())
284 .w(px(PANE_WIDTH))
285 .h_full()
286 .rounded(px(ISLAND_RADIUS))
287 .overflow_hidden()
288 .bg(theme::surface())
289 .child(
290 h_flex()
291 .h(px(HEADER_HEIGHT))
292 .flex_none()
293 .px(px(PANE_PADDING))
294 .items_center()
295 .justify_between()
296 .child(
297 h_flex()
298 .gap(px(8.))
299 .items_center()
300 .child(copilot_logo(LOGO_TITLE))
301 .child(
302 div()
303 .text_size(px(15.))
304 .font_weight(FontWeight::SEMIBOLD)
305 .text_color(theme::text())
306 .child(TITLE),
307 ),
308 )
309 .child(
310 Button::new("copilot-close")
311 .icon(IconName::X)
312 .ghost()
313 .size(px(BUTTON_SIZE))
314 .rounded(px(8.))
315 .tooltip(CLOSE_LABEL)
316 .on_click(cx.listener(|this, _, _, cx| {
317 this.copilot.open = false;
318 cx.notify();
319 })),
320 ),
321 )
322 .child(content),
323 )
324 .into_any_element(),
325 )
326 }
327}
328
329fn copilot_logo(size: f32) -> Img {
330 img(LOGO_ASSET).size(px(size)).flex_none()
331}
332
333fn prompt_bubble(prompt: &str) -> Div {
334 h_flex().w_full().justify_end().child(
335 div()
336 .max_w(px(PANE_WIDTH * 0.8))
337 .px(px(10.))
338 .py(px(6.))
339 .rounded(px(BUBBLE_RADIUS))
340 .bg(theme::row_hover())
341 .text_size(px(13.))
342 .text_color(theme::text())
343 .child(prompt.to_owned()),
344 )
345}
346
347fn answer_view(index: usize, answer: &CopilotAnswer, cx: &App) -> AnyElement {
348 match answer {
349 CopilotAnswer::Waiting => div()
350 .text_size(px(13.))
351 .text_color(theme::text_muted())
352 .child(WORKING)
353 .into_any_element(),
354 CopilotAnswer::Failed(error) => div()
355 .text_size(px(13.))
356 .text_color(theme::red())
357 .child(error.clone())
358 .into_any_element(),
359 CopilotAnswer::Ready(text) => {
360 let spans = teams_core::html_to_spans(&teams_core::markdown_to_html(text));
361 div()
362 .w_full()
363 .text_size(px(13.))
364 .child(render_blocks(
365 &layout_card_blocks(&spans),
366 &format!("copilot-answer-{index}"),
367 false,
368 cx,
369 ))
370 .into_any_element()
371 }
372 }
373}