BlueGit

ict rusty-teams

Files

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

copilot.rs

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