BlueGit

ict rusty-teams

Files

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

conversation.rs

conversation.rs 128.7 KiB Download Raw
1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
5use std::time::{Duration, Instant};
6
7use chrono::{DateTime, Local, Offset, Utc};
8use gpui_kit::assets::IconName;
9use gpui_kit::component::{
10 button::{Button, ButtonVariants as _},
11 h_flex,
12 input::{Escape, InputState},
13 message_scroller::{MessageScroller, MessageScrollerState},
14 tooltip::Tooltip,
15 v_flex,
16};
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
20use teams_core::{ExecuteAction, FileCard, LinkPreview};
21
22mod feed;
23mod pins;
24mod proposal;
25mod recap;
26mod render_env;
27mod scheduled;
28mod shared;
29
30use super::attachments::FileActions;
31use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
32use super::call_controls::header_call_controls;
33use super::channel_tabs::ChannelPane;
34use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
35use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
36use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
37use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
38use super::post_card::render_post;
39use super::profile_card::opens_profile;
40use super::reaction_picker::{PickHandler, ReactionPicker};
41use super::reaction_pills::{ReactionControls, ReactionPopover};
42use super::toolbar_placement::{TimelineBounds, record_bounds};
43use super::widgets::{icon, symbol};
44use crate::agents::{AgentRun, StartRequest};
45use crate::app_state::{AppEvent, AppState, Selection, selection_title};
46use crate::backend::Engine;
47use crate::card_state::CardScope;
48use crate::channel_files::DownloadSource;
49use crate::data::{is_one_on_one, others};
50use crate::demo_library::DemoLibrary;
51use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
52use crate::emoji;
53use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
54use crate::notice::short_error;
55use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
56use crate::pending_rows::pending_row;
57use crate::people::{local_names, resolve_names};
58use crate::reaction_model::UNKNOWN_REACTOR;
59use crate::read_state::{ReadTrigger, plan_read};
60use crate::rows::{
61 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
62 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
63 has_own_reaction, message_draft, message_text, place_local_rows, placeholder_rows,
64 reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,
65};
66use crate::runtime;
67use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
68use crate::sidebar_model::{AvatarSpec, Face};
69use crate::theme;
70use crate::translation::TranslationLine;
71use crate::typing::typing_tooltip;
72use feed::{FeedStash, subject_input};
73use render_env::RenderEnv;
74use shared::SharedState;
75
76const CHAT_OPEN_LIMIT: usize = 60;
77const CHANNEL_OPEN_LIMIT: usize = 300;
78const GROWTH_HEADROOM: usize = 20;
79const META_USER_ID: &str = "me_user_id";
80const PENDING_KEY_PREFIX: &str = "pending-";
81const DEMO_DOWNLOAD_STEPS: u8 = 10;
82const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
83const JUMP_SCAN_LIMIT: usize = 5000;
84const JUMP_CONTEXT_MESSAGES: usize = 12;
85const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
86const PROGRESS_DELAY: Duration = Duration::from_millis(400);
87const SLOW_AFTER: Duration = Duration::from_secs(8);
88const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
89const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
90const PROGRESS_BAR_WIDTH: f32 = 0.35;
91const TYPING_LINE_HEIGHT: f32 = 22.;
92const TYPING_DOT_SIZE: f32 = 5.;
93const TYPING_DOT_COUNT: usize = 3;
94const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
95
96actions!(teams, [ReplyToHovered]);
97
98#[derive(Clone, Copy)]
99enum HoverSlot {
100 Row,
101 Toolbar,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
105enum ViewMode {
106 Flat,
107 ThreadList,
108 Thread(String),
109}
110
111#[derive(Default)]
112struct SyncProgress {
113 messages: bool,
114 receipts: bool,
115 empty_cache: bool,
116 newest_cached: Option<DateTime<Utc>>,
117 shown_at: Option<Instant>,
118 slow: bool,
119 failed: bool,
120}
121
122impl SyncProgress {
123 fn running(&self) -> bool {
124 self.messages || self.receipts
125 }
126}
127
128struct Current {
129 selection: Selection,
130 title: String,
131 mode: ViewMode,
132 loaded_limit: usize,
133 loaded_count: usize,
134 has_older: bool,
135 loading_older: bool,
136 older_blocked: bool,
137 fetched: bool,
138 first_unread: Option<String>,
139 sync: SyncProgress,
140}
141
142struct ReactionDetails {
143 message_key: String,
144 anchor_glyph: String,
145 tab: Option<String>,
146}
147
148pub struct ConversationView {
149 app: Entity<AppState>,
150 pinned: bool,
151 scroller: Entity<MessageScrollerState>,
152 composer: Entity<Composer>,
153 subject: Entity<InputState>,
154 new_post_open: bool,
155 reply_composer: Option<Entity<Composer>>,
156 reply_root: Option<String>,
157 feed_stash: Option<FeedStash>,
158 feed_rows_seen: Rc<Cell<usize>>,
159 feed_at_top: bool,
160 draft: Entity<NewChatDraft>,
161 draft_active: bool,
162 draft_created: Option<(Vec<String>, String)>,
163 draft_error: Option<String>,
164 rows: Rc<RefCell<Vec<Row>>>,
165 current: Option<Current>,
166 pending: Vec<MessageRow>,
167 pending_counter: usize,
168 pending_outgoing: HashMap<String, Outgoing>,
169 pending_reactions: PendingReactions,
170 downloads: Downloads,
171 hovered_message: Option<String>,
172 toolbar_hovered: Option<String>,
173 timeline_bounds: TimelineBounds,
174 toolbar_pinned: Option<String>,
175 toolbar_suppressed: Option<String>,
176 recent: Entity<emoji::Recent>,
177 picker: Entity<ReactionPicker>,
178 reaction_details: Option<ReactionDetails>,
179 highlighted_message: Option<String>,
180 pin_index: usize,
181 pin_previews: HashMap<String, pins::PinPreview>,
182 notice: Option<String>,
183 scheduled_failure: Option<scheduled::ScheduledFailure>,
184 scheduled_in_flight: HashSet<String>,
185 drag_file_count: usize,
186 sync_generation: u64,
187 window_active: bool,
188 pane: ChannelPane,
189 recap: recap::RecapState,
190 recap_search: Entity<InputState>,
191 channel_tabs: Vec<ChannelTabRecord>,
192 tab_links: HashMap<String, String>,
193 focus_handle: FocusHandle,
194 shared: SharedState,
195 demo_library: DemoLibrary,
196 new_folder_input: Option<Entity<InputState>>,
197 agent_layouts: HashMap<String, (usize, bool)>,
198 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
199 _subscriptions: Vec<Subscription>,
200}
201
202fn open_limit(selection: &Selection) -> usize {
203 match selection {
204 Selection::Chat(_) => CHAT_OPEN_LIMIT,
205 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
206 }
207}
208
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210enum DropTarget {
211 Chat,
212 Channel,
213 Library,
214 NewChat,
215}
216
217fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
218 let files = if count == 1 {
219 "1 file".to_owned()
220 } else {
221 format!("{count} files")
222 };
223 match target {
224 DropTarget::Chat => (
225 format!("Drop to attach to {title}"),
226 format!("{files}. Images go into the message, other files to your OneDrive."),
227 ),
228 DropTarget::Channel => (
229 format!("Drop to attach to {title}"),
230 format!("{files}. Images go into the message, other files to the channel's Files."),
231 ),
232 DropTarget::Library => (
233 format!("Drop to upload to {title}"),
234 format!("{files}. Files go into the folder you have open."),
235 ),
236 DropTarget::NewChat => (
237 "Drop to attach to the new chat".to_owned(),
238 format!(
239 "{files}. Images go into the message. Files can be added once the chat exists."
240 ),
241 ),
242 }
243}
244
245fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool {
246 match mode {
247 ViewMode::Flat => record.target == OutboxTarget::Flat,
248 ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread),
249 ViewMode::Thread(root_id) => {
250 record.target == OutboxTarget::Thread
251 && record.thread_root_id.as_deref() == Some(root_id.as_str())
252 }
253 }
254}
255
256enum DownloadEvent {
257 Progress(u8),
258 Finished(Result<PathBuf, String>),
259}
260
261async fn save_file(
262 engine: &Engine,
263 card: &FileCard,
264 source: &DownloadSource,
265 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
266) -> Result<PathBuf, String> {
267 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
268 .map_err(|error| short_error(&error))?;
269 let write = |bytes: &[u8]| part.write(bytes);
270 let progress = |percent| {
271 let _ = events.send(DownloadEvent::Progress(percent));
272 };
273 match source {
274 DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,
275 DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,
276 }
277 .map_err(|error| short_error(&error))?;
278 part.finish().map_err(|error| short_error(&error))
279}
280
281impl ConversationView {
282 fn file_actions(
283 &self,
284 message_key: &str,
285 files: &[FileCard],
286 view: WeakEntity<Self>,
287 ) -> FileActions {
288 let conversation_id = self.conversation_id().unwrap_or_default();
289 let (key, cards) = (message_key.to_owned(), files.to_vec());
290 let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect();
291 FileActions {
292 states: self
293 .downloads
294 .states_for(&conversation_id, message_key, &open_urls),
295 activate: Rc::new(move |index, cx| {
296 let Some(card) = cards.get(index).cloned() else {
297 return;
298 };
299 let key = key.clone();
300 let conversation_id = conversation_id.clone();
301 view.update(cx, |this, cx| {
302 this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)
303 })
304 .ok();
305 }),
306 }
307 }
308
309 fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {
310 let Some(current) = self.current.as_ref() else {
311 return;
312 };
313 let now = Local::now();
314 let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());
315 let Some(index) = position_of(&items, message_key, url) else {
316 return;
317 };
318 let request = ViewerRequest {
319 conversation_id: current.selection.conversation_id().to_owned(),
320 conversation_title: selection_title(&self.app.read(cx).sidebar, &current.selection),
321 items,
322 index,
323 };
324 self.app
325 .update(cx, |state, cx| state.request_image_viewer(request, cx));
326 }
327
328 fn activate_file(
329 &mut self,
330 conversation_id: &str,
331 message_key: &str,
332 card: FileCard,
333 source: DownloadSource,
334 cx: &mut Context<Self>,
335 ) {
336 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
337 match downloads::click_action(self.downloads.state(&key)) {
338 ClickAction::Ignore => {}
339 ClickAction::Start => self.start_download(key, card, source, cx),
340 ClickAction::Reveal(path) => {
341 let folder = path
342 .parent()
343 .map(Path::to_path_buf)
344 .unwrap_or_else(downloads::downloads_directory);
345 match downloads::reveal_target(&path, path.exists(), folder) {
346 RevealTarget::File(path) => downloads::reveal_in_file_manager(&path),
347 RevealTarget::Folder(folder) => cx.open_with_system(&folder),
348 }
349 }
350 }
351 }
352
353 fn start_download(
354 &mut self,
355 key: DownloadKey,
356 card: FileCard,
357 source: DownloadSource,
358 cx: &mut Context<Self>,
359 ) {
360 if !self.downloads.begin(&key) {
361 return;
362 }
363 cx.notify();
364 let state = self.app.read(cx);
365 let (demo, engine) = (state.mode.demo, state.engine.clone());
366 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>();
367 if demo {
368 cx.spawn(async move |this, cx| {
369 for step in 1..=DEMO_DOWNLOAD_STEPS {
370 cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await;
371 let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8;
372 let progressed = this.update(cx, |this, cx| {
373 this.downloads.set_progress(&key, percent);
374 cx.notify();
375 });
376 if progressed.is_err() {
377 return;
378 }
379 }
380 let outcome =
381 downloads::write_demo_file(&card.name).map_err(|error| short_error(&error));
382 this.update(cx, |this, cx| {
383 this.downloads.finish(&key, outcome);
384 cx.notify();
385 })
386 .ok();
387 })
388 .detach();
389 return;
390 }
391 let Some(engine) = engine else {
392 self.downloads.finish(&key, Err("not connected".to_owned()));
393 return;
394 };
395 drop(runtime::spawn(async move {
396 let outcome = save_file(&engine, &card, &source, &sender).await;
397 let _ = sender.send(DownloadEvent::Finished(outcome));
398 }));
399 cx.spawn(async move |this, cx| {
400 while let Some(event) = receiver.recv().await {
401 let updated = this.update(cx, |this, cx| {
402 match event {
403 DownloadEvent::Progress(percent) => {
404 this.downloads.set_progress(&key, percent)
405 }
406 DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome),
407 }
408 cx.notify();
409 });
410 if updated.is_err() {
411 break;
412 }
413 }
414 })
415 .detach();
416 }
417
418 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
419 Self::build(app, None, window, cx)
420 }
421
422 pub fn pinned_to(
423 app: Entity<AppState>,
424 selection: Selection,
425 window: &mut Window,
426 cx: &mut Context<Self>,
427 ) -> Self {
428 Self::build(app, Some(selection), window, cx)
429 }
430
431 fn build(
432 app: Entity<AppState>,
433 pinned: Option<Selection>,
434 window: &mut Window,
435 cx: &mut Context<Self>,
436 ) -> Self {
437 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
438 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
439 let subject = subject_input(window, cx);
440 let recap_search = recap::search_input(window, cx);
441 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
442 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
443 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
444 let mut subscriptions = vec![
445 cx.subscribe_in(&app, window, Self::on_app_event),
446 cx.observe(&app, |_, _, cx| cx.notify()),
447 cx.subscribe_in(&composer, window, Self::on_composer_event),
448 cx.subscribe_in(&draft, window, Self::on_draft_event),
449 cx.subscribe_in(&subject, window, Self::on_subject_event),
450 cx.subscribe_in(&recap_search, window, Self::on_recap_search_event),
451 cx.observe_window_activation(window, Self::on_window_activation),
452 cx.on_app_quit(|this, cx| {
453 this.composer
454 .update(cx, |composer, cx| composer.save_draft_now(cx));
455 async {}
456 }),
457 cx.observe_keystrokes(|this, event, _, cx| {
458 if event.keystroke.key == "escape" {
459 this.close_reaction_details(cx);
460 }
461 }),
462 ];
463 if let Some(runs) = crate::agents::runs_handle(cx) {
464 subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx)));
465 }
466 let mut view = ConversationView {
467 app,
468 pinned: pinned.is_some(),
469 scroller,
470 composer,
471 subject,
472 new_post_open: false,
473 reply_composer: None,
474 reply_root: None,
475 feed_stash: None,
476 feed_rows_seen: Rc::new(Cell::new(usize::MAX)),
477 feed_at_top: true,
478 draft,
479 draft_active: false,
480 draft_created: None,
481 draft_error: None,
482 rows: Rc::new(RefCell::new(Vec::new())),
483 current: None,
484 pending: Vec::new(),
485 pending_counter: 0,
486 pending_outgoing: HashMap::new(),
487 pending_reactions: HashMap::new(),
488 downloads: Downloads::default(),
489 hovered_message: None,
490 toolbar_hovered: None,
491 timeline_bounds: TimelineBounds::default(),
492 toolbar_pinned: None,
493 toolbar_suppressed: None,
494 recent,
495 picker,
496 reaction_details: None,
497 highlighted_message: None,
498 pin_index: 0,
499 pin_previews: HashMap::new(),
500 notice: None,
501 scheduled_failure: None,
502 scheduled_in_flight: HashSet::new(),
503 drag_file_count: 0,
504 sync_generation: 0,
505 window_active: window.is_window_active(),
506 pane: ChannelPane::Posts,
507 recap: recap::RecapState::default(),
508 recap_search,
509 channel_tabs: Vec::new(),
510 tab_links: HashMap::new(),
511 focus_handle: cx.focus_handle(),
512 shared: SharedState::default(),
513 demo_library: DemoLibrary::default(),
514 new_folder_input: None,
515 agent_layouts: HashMap::new(),
516 agent_runs: Rc::new(RefCell::new(HashMap::new())),
517 _subscriptions: subscriptions,
518 };
519 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
520 view.open(selection, window, cx);
521 }
522 view
523 }
524
525 #[cfg_attr(not(windows), allow(dead_code))]
526 pub fn composer_is_empty(&self, cx: &App) -> bool {
527 self.composer.read(cx).is_empty(cx)
528 }
529
530 #[cfg_attr(not(windows), allow(dead_code))]
531 pub fn send_in_flight(&self) -> bool {
532 self.pending
533 .iter()
534 .any(|row| matches!(row.delivery, Delivery::Sending))
535 }
536
537 fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
538 self.window_active = window.is_window_active();
539 self.mark_read(ReadTrigger::Activation, cx);
540 }
541
542 fn on_app_event(
543 &mut self,
544 _: &Entity<AppState>,
545 event: &AppEvent,
546 window: &mut Window,
547 cx: &mut Context<Self>,
548 ) {
549 match event {
550 AppEvent::Selection if self.pinned => {}
551 AppEvent::Selection => {
552 self.reaction_details = None;
553 let (new_chat, selection) = {
554 let state = self.app.read(cx);
555 (state.new_chat, state.selection.clone())
556 };
557 if new_chat {
558 self.enter_draft(window, cx);
559 return;
560 }
561 if self.draft_active {
562 let created = self
563 .draft_created
564 .as_ref()
565 .map(|(_, chat_id)| chat_id.clone());
566 if let Some(chat_id) = created {
567 self.composer
568 .update(cx, |composer, _| composer.carry_images_into(chat_id));
569 }
570 self.leave_draft(window, cx);
571 }
572 match selection {
573 Some(selection) => self.open(selection, window, cx),
574 None => {
575 self.current = None;
576 self.rebuild(true, cx);
577 }
578 }
579 }
580 AppEvent::Messages(conversation_id) => {
581 let is_current = self
582 .current
583 .as_ref()
584 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
585 if is_current {
586 if self.shared_active() || self.recap_active() {
587 self.refresh_shared_items(cx);
588 }
589 self.rebuild(false, cx);
590 self.mark_read(ReadTrigger::Incoming, cx);
591 self.on_pins_changed(conversation_id, cx);
592 }
593 }
594 AppEvent::Images(keys) => self.remeasure_images(keys, cx),
595 AppEvent::Cards(conversation_id) => self.refresh_cards(conversation_id, cx),
596 AppEvent::Jump => self.apply_pending_jump(cx),
597 AppEvent::Status => {
598 if let Some(current) = self.current.as_mut()
599 && current.sync.failed
600 {
601 current.fetched = false;
602 }
603 self.start_fetch(cx)
604 }
605 AppEvent::Directory => {
606 self.refresh_reactor_names(cx);
607 cx.notify();
608 }
609 AppEvent::TaskDialog
610 | AppEvent::LocalPreviews
611 | AppEvent::Forward
612 | AppEvent::ImageViewer
613 | AppEvent::StatusMessage
614 | AppEvent::NotificationSettings
615 | AppEvent::Profile
616 | AppEvent::CallHistory
617 | AppEvent::Ring
618 | AppEvent::MissedCall(_)
619 | AppEvent::Call => {}
620 AppEvent::LiveMeeting => cx.notify(),
621 AppEvent::Saved => cx.notify(),
622 AppEvent::Translation => self.rebuild(false, cx),
623 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
624 AppEvent::Typing => cx.notify(),
625 AppEvent::Scheduled => self.rebuild(false, cx),
626 AppEvent::Outbox(conversation_id) => {
627 let is_current = self
628 .current
629 .as_ref()
630 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
631 if is_current {
632 self.reload_pending(cx);
633 self.rebuild(false, cx);
634 }
635 }
636 AppEvent::Sidebar => {
637 self.reload_channel_tabs(cx);
638 self.mark_read(ReadTrigger::Incoming, cx);
639 self.refresh_reactor_names(cx);
640 if self.draft_active {
641 self.on_draft_changed(window, cx);
642 } else if let Some(current) = self.current.as_mut() {
643 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
644 if current.title != title {
645 current.title = title.clone();
646 let conversation_id = current.selection.conversation_id().to_owned();
647 self.composer.update(cx, |composer, cx| {
648 composer.set_conversation(&conversation_id, &title, window, cx)
649 });
650 cx.notify();
651 }
652 }
653 }
654 }
655 }
656
657 fn on_composer_event(
658 &mut self,
659 _: &Entity<Composer>,
660 event: &ComposerEvent,
661 window: &mut Window,
662 cx: &mut Context<Self>,
663 ) {
664 self.report_composer_activity(event, cx);
665 match event {
666 ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),
667 ComposerEvent::Schedule { outgoing, send_at } => {
668 self.schedule((**outgoing).clone(), *send_at, window, cx)
669 }
670 ComposerEvent::EditLast => self.edit_last_own(window, cx),
671 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
672 }
673 }
674
675 fn submit_main(&mut self, mut outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
676 if self.draft_active {
677 return self.send_new_chat(outgoing, window, cx);
678 }
679 let in_feed = self.in_feed();
680 if in_feed && outgoing.edit.is_none() {
681 outgoing.subject = self.take_subject(window, cx);
682 }
683 if in_feed {
684 self.close_new_post(cx);
685 }
686 match &outgoing.edit {
687 Some(edit) if edit.scheduled.is_some() => {
688 self.send_scheduled_edit(outgoing, window, cx)
689 }
690 Some(_) => self.send_edit(outgoing, window, cx),
691 None => self.send(outgoing, window, cx),
692 }
693 }
694
695 fn typing_root(&self) -> Option<String> {
696 match self.current.as_ref().map(|current| &current.mode) {
697 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
698 _ => None,
699 }
700 }
701
702 fn send_typing(&self, active: bool, cx: &App) {
703 self.send_typing_in(self.typing_root(), active, cx);
704 }
705
706 fn send_typing_in(&self, thread_root_id: Option<String>, active: bool, cx: &App) {
707 let state = self.app.read(cx);
708 if state.mode.demo || state.mode.read_only || self.draft_active {
709 return;
710 }
711 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
712 else {
713 return;
714 };
715 drop(runtime::spawn(async move {
716 let sent = engine
717 .send_typing(&conversation_id, thread_root_id.as_deref(), active)
718 .await;
719 if let Err(error) = sent
720 && cfg!(debug_assertions)
721 {
722 crate::diagnostics::record(format!("typing indicator not sent: {error}"));
723 }
724 }));
725 }
726
727 fn stop_typing(&mut self, cx: &mut Context<Self>) {
728 if self
729 .composer
730 .update(cx, |composer, _| composer.stop_typing())
731 {
732 self.send_typing(false, cx);
733 }
734 }
735
736 fn render_typing_line(&self, cx: &App) -> impl IntoElement {
737 let app = self.app.read(cx);
738 let faces = self
739 .current
740 .as_ref()
741 .filter(|_| !self.draft_active)
742 .map(|current| app.typing.faces(current.selection.conversation_id()))
743 .unwrap_or_default();
744 let tooltip_text = typing_tooltip(
745 &faces
746 .iter()
747 .map(|face| face.name.clone())
748 .collect::<Vec<_>>(),
749 );
750 let flat = matches!(
751 self.current.as_ref().map(|current| &current.mode),
752 Some(ViewMode::Flat)
753 );
754 let faces_element = match faces.as_slice() {
755 [face] if flat => person_avatar(
756 &app.directory,
757 face.user_id.as_deref(),
758 &face.name,
759 AVATAR_SIZE,
760 ),
761 _ => member_stack(&app.directory, &faces, faces.len()).into_any_element(),
762 };
763 h_flex()
764 .h(px(if flat {
765 AVATAR_SIZE + 4.
766 } else {
767 TYPING_LINE_HEIGHT
768 }))
769 .flex_none()
770 .px(px(20.))
771 .gap(px(if flat { AVATAR_GAP } else { 6. }))
772 .items_center()
773 .when(!faces.is_empty(), |line| {
774 line.child(
775 div()
776 .id("typing-faces")
777 .tooltip(move |window, cx| {
778 Tooltip::new(tooltip_text.clone()).build(window, cx)
779 })
780 .child(faces_element),
781 )
782 .child(typing_dots())
783 })
784 }
785
786 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
787 self.stop_typing(cx);
788 self.stop_reply_typing(cx);
789 self.new_post_open = false;
790 self.feed_stash = None;
791 self.feed_at_top = true;
792 self.restore_subject(None, window, cx);
793 self.toolbar_hovered = None;
794 self.toolbar_pinned = None;
795 self.toolbar_suppressed = None;
796 self.agent_layouts.clear();
797 self.agent_runs.borrow_mut().clear();
798 let title = selection_title(&self.app.read(cx).sidebar, &selection);
799 let mode = match selection {
800 Selection::Chat(_) => ViewMode::Flat,
801 Selection::Channel(_) => ViewMode::ThreadList,
802 };
803 let first_unread = self.first_unread_id(&selection, cx);
804 self.current = Some(Current {
805 loaded_limit: open_limit(&selection),
806 selection,
807 title,
808 mode,
809 loaded_count: 0,
810 has_older: false,
811 loading_older: false,
812 older_blocked: false,
813 fetched: false,
814 first_unread,
815 sync: SyncProgress::default(),
816 });
817 self.refresh_agent_runs(cx);
818 self.sync_generation += 1;
819 self.reset_channel_tabs(cx);
820 self.reset_recap(cx);
821 self.reload_pending(cx);
822 self.notice = None;
823 self.scheduled_failure = None;
824 self.app.update(cx, |state, cx| state.refresh_scheduled(cx));
825 self.rebuild(true, cx);
826 self.start_fetch(cx);
827 self.mark_read(ReadTrigger::Open, cx);
828 self.refresh_pin_previews(cx);
829 if let Some(chat_id) = self.chat_id() {
830 self.app
831 .update(cx, |state, cx| state.refresh_pins(&chat_id, cx));
832 }
833 let target = self
834 .current
835 .as_ref()
836 .map(|current| {
837 (
838 current.selection.conversation_id().to_owned(),
839 current.title.clone(),
840 )
841 })
842 .unwrap_or_default();
843 self.composer.update(cx, |composer, cx| {
844 composer.set_conversation(&target.0, &target.1, window, cx);
845 });
846 self.sync_reply_composer(window, cx);
847 if !self.draft_active && !self.in_feed() {
848 self.composer
849 .update(cx, |composer, cx| composer.focus(window, cx));
850 }
851 self.hovered_message = None;
852 self.apply_pending_jump(cx);
853 }
854
855 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
856 if !self.draft_active {
857 self.stop_typing(cx);
858 self.draft_active = true;
859 self.current = None;
860 self.clear_pending();
861 self.notice = None;
862 self.draft_created = None;
863 self.draft_error = None;
864 self.toolbar_hovered = None;
865 self.toolbar_pinned = None;
866 self.toolbar_suppressed = None;
867 self.hovered_message = None;
868 self.sync_generation += 1;
869 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
870 self.composer.update(cx, |composer, cx| {
871 composer.set_conversation("", "", window, cx)
872 });
873 self.on_draft_changed(window, cx);
874 self.rebuild(true, cx);
875 }
876 self.draft
877 .update(cx, |draft, cx| draft.focus_query(window, cx));
878 cx.notify();
879 }
880
881 fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
882 self.draft_active = false;
883 self.draft_created = None;
884 self.draft_error = None;
885 self.clear_pending();
886 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
887 }
888
889 fn on_draft_event(
890 &mut self,
891 _: &Entity<NewChatDraft>,
892 event: &NewChatEvent,
893 window: &mut Window,
894 cx: &mut Context<Self>,
895 ) {
896 match event {
897 NewChatEvent::Changed => self.on_draft_changed(window, cx),
898 NewChatEvent::FocusComposer => self
899 .composer
900 .update(cx, |composer, cx| composer.focus(window, cx)),
901 NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)),
902 }
903 }
904
905 fn draft_target_chat(&self, cx: &App) -> Option<String> {
906 let chips = self.draft.read(cx).chips();
907 let [chip] = chips else {
908 return None;
909 };
910 let state = self.app.read(cx);
911 existing_one_on_one(
912 &state.sidebar.chats,
913 state.directory.me.as_ref(),
914 &chip.user_id,
915 )
916 .map(|chat| chat.id.clone())
917 }
918
919 fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
920 if !self.draft_active {
921 return;
922 }
923 let target = self.draft_target_chat(cx);
924 if target != self.conversation_id() {
925 match target {
926 Some(chat_id) => {
927 self.composer.update(cx, |composer, _| {
928 composer.carry_images_into(chat_id.clone())
929 });
930 self.open(Selection::Chat(chat_id), window, cx)
931 }
932 None => {
933 self.composer.update(cx, |composer, cx| {
934 composer.carry_images_into(String::new());
935 composer.set_conversation("", "", window, cx);
936 });
937 self.current = None;
938 self.sync_generation += 1;
939 self.rebuild(true, cx);
940 }
941 }
942 }
943 let placeholder = {
944 let draft = self.draft.read(cx);
945 composer_placeholder(draft.chips(), &draft.group_name(cx))
946 };
947 self.composer.update(cx, |composer, cx| {
948 composer.set_placeholder(&placeholder, window, cx)
949 });
950 cx.notify();
951 }
952
953 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
954 let indices: Vec<usize> = self
955 .rows
956 .borrow()
957 .iter()
958 .enumerate()
959 .filter(|(_, row)| {
960 row.messages().any(|message| {
961 message.images.iter().any(|image| keys.contains(&image.url))
962 || message
963 .link_preview
964 .as_ref()
965 .and_then(LinkPreview::image)
966 .is_some_and(|image| keys.contains(&image.url))
967 })
968 })
969 .map(|(index, _)| index)
970 .collect();
971 self.scroller.update(cx, |scroller, cx| {
972 for index in indices {
973 scroller.remeasure_items(index..index + 1, cx);
974 }
975 });
976 cx.notify();
977 }
978
979 fn refresh_cards(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
980 let is_current = self
981 .current
982 .as_ref()
983 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
984 if !is_current {
985 return;
986 }
987 self.rebuild(false, cx);
988 let indices: Vec<usize> = self
989 .rows
990 .borrow()
991 .iter()
992 .enumerate()
993 .filter(|(_, row)| {
994 row.messages()
995 .any(|message| !message.adaptive_cards.is_empty())
996 })
997 .map(|(index, _)| index)
998 .collect();
999 self.scroller.update(cx, |scroller, cx| {
1000 for index in indices {
1001 scroller.remeasure_items(index..index + 1, cx);
1002 }
1003 });
1004 cx.notify();
1005 }
1006
1007 fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
1008 let Some(conversation_id) = self
1009 .current
1010 .as_ref()
1011 .map(|current| current.selection.conversation_id().to_owned())
1012 else {
1013 return;
1014 };
1015 let jump = self
1016 .app
1017 .update(cx, |state, _| match state.pending_jump.take() {
1018 Some((target, message_id)) if target == conversation_id => Some(message_id),
1019 other => {
1020 state.pending_jump = other;
1021 None
1022 }
1023 });
1024 if let Some(message_id) = jump {
1025 self.jump_to_message(&conversation_id, &message_id, cx);
1026 }
1027 }
1028
1029 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
1030 let store = self.app.read(cx).store.clone();
1031 let Some(record) = store
1032 .messages_by_id(conversation_id, &[message_id.to_owned()])
1033 .ok()
1034 .and_then(|mut found| found.remove(message_id))
1035 else {
1036 return;
1037 };
1038 let messages_from_target = store
1039 .messages(conversation_id, None, JUMP_SCAN_LIMIT)
1040 .ok()
1041 .and_then(|all| {
1042 all.iter()
1043 .position(|candidate| candidate.message_id == message_id)
1044 .map(|position| all.len() - position)
1045 })
1046 .unwrap_or_default();
1047 let row_key = record
1048 .reply_to_id
1049 .clone()
1050 .unwrap_or_else(|| message_id.to_owned());
1051 let Some(current) = self.current.as_mut() else {
1052 return;
1053 };
1054 current.loaded_limit = current
1055 .loaded_limit
1056 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
1057 current.first_unread = None;
1058 let in_channel = matches!(current.selection, Selection::Channel(_));
1059 if in_channel {
1060 self.pane = ChannelPane::Posts;
1061 match record.reply_to_id.clone() {
1062 Some(root_id) => {
1063 self.enter_thread_mode(root_id.clone(), cx);
1064 self.refresh_thread(root_id, cx);
1065 }
1066 None => {
1067 self.enter_feed_mode();
1068 }
1069 }
1070 }
1071 let in_thread = self
1072 .current
1073 .as_ref()
1074 .is_some_and(|current| matches!(current.mode, ViewMode::Thread(_)));
1075 let target_key = if in_thread {
1076 message_id.to_owned()
1077 } else {
1078 row_key
1079 };
1080 self.reload_pending(cx);
1081 self.rebuild(true, cx);
1082 let index = self
1083 .rows
1084 .borrow()
1085 .iter()
1086 .position(|row| row.key() == target_key);
1087 if let Some(index) = index {
1088 self.scroller
1089 .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx));
1090 self.highlight(target_key, cx);
1091 }
1092 }
1093
1094 fn highlight(&mut self, key: String, cx: &mut Context<Self>) {
1095 self.highlighted_message = Some(key.clone());
1096 cx.notify();
1097 cx.spawn(async move |this, cx| {
1098 cx.background_executor().timer(HIGHLIGHT_DURATION).await;
1099 this.update(cx, |this, cx| {
1100 if this.highlighted_message.as_deref() == Some(key.as_str()) {
1101 this.highlighted_message = None;
1102 cx.notify();
1103 }
1104 })
1105 .ok();
1106 })
1107 .detach();
1108 }
1109
1110 pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1111 self.composer
1112 .update(cx, |composer, cx| composer.set_text(text, window, cx));
1113 self.composer
1114 .update(cx, |composer, cx| composer.focus(window, cx));
1115 }
1116
1117 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1118 let key = self
1119 .rows
1120 .borrow()
1121 .iter()
1122 .rev()
1123 .flat_map(Row::messages)
1124 .find(|message| !message.own)
1125 .map(|message| message.key.clone());
1126 if let Some(key) = key {
1127 self.begin_reply(&key, window, cx);
1128 }
1129 }
1130
1131 pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1132 if let Some(message_id) = self.hovered_message.clone() {
1133 self.begin_reply(&message_id, window, cx);
1134 }
1135 }
1136
1137 fn reply_target(&self, message_id: &str, cx: &App) -> Option<(MessageRecord, ReplyPreview)> {
1138 let conversation_id = self.conversation_id()?;
1139 let record = self
1140 .app
1141 .read(cx)
1142 .store
1143 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1144 .ok()
1145 .and_then(|mut found| found.remove(message_id))
1146 .filter(|record| !record.deleted)?;
1147 let preview = ReplyPreview {
1148 message_id: record.message_id.clone(),
1149 author: record
1150 .sender_name
1151 .clone()
1152 .unwrap_or_else(|| "Unknown".to_owned()),
1153 excerpt: reply_excerpt(&record),
1154 };
1155 Some((record, preview))
1156 }
1157
1158 fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1159 let Some((record, preview)) = self.reply_target(message_id, cx) else {
1160 return;
1161 };
1162 if self.in_feed() {
1163 let root_id = record
1164 .reply_to_id
1165 .clone()
1166 .unwrap_or_else(|| record.message_id.clone());
1167 let quote = record.reply_to_id.is_some().then_some(preview);
1168 self.open_reply_editor(root_id, quote, window, cx);
1169 return;
1170 }
1171 self.composer.update(cx, |composer, cx| {
1172 composer.set_reply(Some(preview), cx);
1173 composer.focus(window, cx);
1174 });
1175 }
1176
1177 fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> {
1178 let Selection::Chat(chat_id) = selection else {
1179 return None;
1180 };
1181 let state = self.app.read(cx);
1182 if state.mode.demo {
1183 return crate::demo::first_unread(chat_id);
1184 }
1185 state.engine.as_ref()?.first_unread_message_id(chat_id)
1186 }
1187
1188 fn row_context(&self, cx: &App) -> RowContext {
1189 let now = Local::now();
1190 let app = self.app.read(cx);
1191 let names = local_names(app);
1192 let card_overrides = self
1193 .current
1194 .as_ref()
1195 .map(|current| app.cards.overrides_for(current.selection.conversation_id()))
1196 .unwrap_or_default();
1197 let translation = self
1198 .current
1199 .as_ref()
1200 .map(|current| {
1201 app.translation
1202 .context_for(current.selection.conversation_id())
1203 })
1204 .unwrap_or_default();
1205 RowContext {
1206 offset: now.offset().fix(),
1207 today: now.date_naive(),
1208 my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
1209 names,
1210 pending_reactions: self.pending_reactions.clone(),
1211 card_overrides,
1212 translation,
1213 }
1214 }
1215
1216 fn unknown_reactor_ids(&self) -> Vec<String> {
1217 self.rows
1218 .borrow()
1219 .iter()
1220 .flat_map(Row::messages)
1221 .flat_map(|message| message.reactions.iter())
1222 .flat_map(|chip| chip.reactors.iter())
1223 .filter(|reactor| reactor.name == UNKNOWN_REACTOR)
1224 .filter_map(|reactor| reactor.user_id.clone())
1225 .collect()
1226 }
1227
1228 fn refresh_reactor_names(&mut self, cx: &mut Context<Self>) {
1229 if self.current.is_none() {
1230 return;
1231 }
1232 let unknown = self.unknown_reactor_ids();
1233 if unknown.is_empty() {
1234 return;
1235 }
1236 let names = resolve_names(self.app.read(cx), &unknown);
1237 if !names.is_empty() {
1238 self.rebuild(false, cx);
1239 }
1240 }
1241
1242 fn drop_stale_reaction_details(&mut self) {
1243 let Some(details) = self.reaction_details.as_ref() else {
1244 return;
1245 };
1246 let present = self
1247 .rows
1248 .borrow()
1249 .iter()
1250 .flat_map(Row::messages)
1251 .any(|message| {
1252 message.key == details.message_key
1253 && message
1254 .reactions
1255 .iter()
1256 .any(|chip| chip.glyph() == details.anchor_glyph)
1257 });
1258 if !present {
1259 self.reaction_details = None;
1260 }
1261 }
1262
1263 fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) {
1264 let multiple_kinds = self
1265 .rows
1266 .borrow()
1267 .iter()
1268 .flat_map(Row::messages)
1269 .any(|message| message.key == message_key && message.reactions.len() > 1);
1270 self.reaction_details = Some(ReactionDetails {
1271 message_key: message_key.to_owned(),
1272 anchor_glyph: glyph.to_owned(),
1273 tab: multiple_kinds.then(|| glyph.to_owned()),
1274 });
1275 cx.notify();
1276 }
1277
1278 fn select_reaction_tab(&mut self, tab: Option<String>, cx: &mut Context<Self>) {
1279 if let Some(details) = self.reaction_details.as_mut() {
1280 details.tab = tab;
1281 cx.notify();
1282 }
1283 }
1284
1285 fn close_reaction_details(&mut self, cx: &mut Context<Self>) {
1286 if self.reaction_details.take().is_some() {
1287 cx.notify();
1288 }
1289 }
1290
1291 fn reaction_controls(&self, key: &str, view: WeakEntity<Self>) -> ReactionControls {
1292 let open = {
1293 let (view, key) = (view.clone(), key.to_owned());
1294 Rc::new(move |glyph: &str, cx: &mut App| {
1295 view.update(cx, |this, cx| this.open_reaction_details(&key, glyph, cx))
1296 .ok();
1297 })
1298 };
1299 let select_tab = {
1300 let view = view.clone();
1301 Rc::new(move |tab: Option<String>, cx: &mut App| {
1302 view.update(cx, |this, cx| this.select_reaction_tab(tab, cx))
1303 .ok();
1304 })
1305 };
1306 let close = Rc::new(move |cx: &mut App| {
1307 view.update(cx, |this, cx| this.close_reaction_details(cx))
1308 .ok();
1309 });
1310 let popover = self
1311 .reaction_details
1312 .as_ref()
1313 .filter(|details| details.message_key == key)
1314 .map(|details| ReactionPopover {
1315 anchor_glyph: details.anchor_glyph.clone(),
1316 tab: details.tab.clone(),
1317 });
1318 ReactionControls {
1319 open,
1320 select_tab,
1321 close,
1322 popover,
1323 }
1324 }
1325
1326 fn start_info(&self, cx: &App) -> Option<StartInfo> {
1327 let current = self.current.as_ref()?;
1328 let app = self.app.read(cx);
1329 let user_id = match &current.selection {
1330 Selection::Chat(chat_id) => app
1331 .sidebar
1332 .chats
1333 .iter()
1334 .find(|chat| &chat.id == chat_id)
1335 .filter(|chat| is_one_on_one(chat))
1336 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
1337 .and_then(|(user_id, _)| user_id),
1338 Selection::Channel(_) => None,
1339 };
1340 Some(StartInfo {
1341 title: current.title.clone(),
1342 user_id,
1343 })
1344 }
1345
1346 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
1347 let Some(current) = self.current.as_ref() else {
1348 let mut rows: Vec<Row> = self
1349 .pending
1350 .iter()
1351 .cloned()
1352 .map(|row| Row::Message(Box::new(row)))
1353 .collect();
1354 assign_series(&mut rows);
1355 self.apply_rows(rows, true, cx);
1356 return;
1357 };
1358 let conversation_id = current.selection.conversation_id().to_owned();
1359 let limit = if reset {
1360 current.loaded_limit
1361 } else {
1362 current
1363 .loaded_limit
1364 .max(current.loaded_count + GROWTH_HEADROOM)
1365 };
1366 let store = self.app.read(cx).store.clone();
1367 let thread_root = match &current.mode {
1368 ViewMode::Thread(root_id) => Some(root_id.clone()),
1369 ViewMode::Flat | ViewMode::ThreadList => None,
1370 };
1371 let records: Vec<MessageRecord> = match &thread_root {
1372 Some(root_id) => store.thread_messages(&conversation_id, root_id),
1373 None => store.messages(&conversation_id, None, limit),
1374 }
1375 .unwrap_or_default();
1376 let sync_has_more = store
1377 .sync_state(&conversation_id)
1378 .ok()
1379 .flatten()
1380 .is_none_or(|state| state.has_more);
1381 let mut context = self.row_context(cx);
1382 let reactor_ids: Vec<String> = records
1383 .iter()
1384 .flat_map(teams_core::reactions)
1385 .filter(|reaction| reaction.user_name.is_none())
1386 .filter_map(|reaction| reaction.user_id)
1387 .filter(|user_id| !context.names.contains_key(user_id))
1388 .collect();
1389 for (user_id, name) in resolve_names(self.app.read(cx), &reactor_ids) {
1390 context.names.entry(user_id).or_insert(name);
1391 }
1392 for record in &records {
1393 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
1394 context
1395 .names
1396 .entry(user_id.clone())
1397 .or_insert_with(|| name.clone());
1398 }
1399 }
1400 let can_load_older = self.app.read(cx).engine.is_some();
1401 let start = self.start_info(cx);
1402 let current = self.current.as_mut().expect("checked above");
1403 let first_unread = current.first_unread.clone();
1404 current.loaded_limit = limit;
1405 if thread_root.is_none() {
1406 current.loaded_count = records.len();
1407 }
1408 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1409 let placeholders = current.sync.messages
1410 && records.is_empty()
1411 && !matches!(current.mode, ViewMode::Thread(_));
1412 let in_feed = current.mode == ViewMode::ThreadList;
1413 let mut rows = match &current.mode {
1414 _ if placeholders => {
1415 current.has_older = false;
1416 placeholder_rows()
1417 }
1418 ViewMode::Flat => {
1419 current.has_older = has_older;
1420 let mut rows = flat_rows(&records, &context, has_older);
1421 if !has_older && let Some(start) = start {
1422 rows.insert(0, Row::Start(start));
1423 }
1424 rows
1425 }
1426 ViewMode::ThreadList => {
1427 current.has_older = has_older;
1428 thread_list_rows(&records, &context, has_older)
1429 }
1430 ViewMode::Thread(root_id) => {
1431 current.has_older = false;
1432 thread_rows(&records, root_id, &context)
1433 }
1434 };
1435 let local: Vec<MessageRow> = self
1436 .pending
1437 .iter()
1438 .cloned()
1439 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1440 .collect();
1441 if in_feed {
1442 place_local_rows(&mut rows, local);
1443 } else {
1444 rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));
1445 }
1446 let receipts = self.receipts(&records, cx);
1447 for row in rows.iter_mut() {
1448 if let Row::Message(message) = row
1449 && message.own
1450 {
1451 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
1452 }
1453 }
1454 if let Some(unread_id) = &first_unread {
1455 for row in rows.iter_mut() {
1456 if let Row::Message(message) = row
1457 && &message.key == unread_id
1458 {
1459 message.new_marker = true;
1460 }
1461 }
1462 }
1463 assign_series(&mut rows);
1464 self.apply_rows(rows, reset, cx);
1465 }
1466
1467 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
1468 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
1469 self.drop_stale_reaction_details();
1470 let new_len = self.rows.borrow().len();
1471 let in_feed = self.in_feed();
1472 if reset {
1473 let marker_index = self
1474 .rows
1475 .borrow()
1476 .iter()
1477 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1478 self.feed_at_top = true;
1479 self.scroller.update(cx, |scroller, cx| {
1480 scroller.reset(new_len, cx);
1481 if in_feed {
1482 scroller.scroll_to_item(0, cx);
1483 return;
1484 }
1485 match marker_index {
1486 Some(index) if !scroller.scroll_to_item(index, cx) => {
1487 scroller.scroll_to_end(cx)
1488 }
1489 Some(_) => {}
1490 None => scroller.scroll_to_end(cx),
1491 }
1492 });
1493 cx.notify();
1494 return;
1495 }
1496 let (splice, changed) = {
1497 let new_rows = self.rows.borrow();
1498 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
1499 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
1500 (
1501 diff_keys(&old_keys, &new_keys),
1502 changed_indices(&old_rows, &new_rows),
1503 )
1504 };
1505 let top_changed = splice
1506 .as_ref()
1507 .is_some_and(|splice| splice.range.start == 0);
1508 let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed));
1509 self.scroller.update(cx, |scroller, cx| {
1510 if let Some(splice) = splice
1511 && !scroller.splice(splice.range, splice.count, cx)
1512 {
1513 scroller.reset(new_len, cx);
1514 }
1515 if keep_top {
1516 scroller.scroll_to_item(0, cx);
1517 }
1518 for index in changed {
1519 scroller.remeasure_items(index..index + 1, cx);
1520 }
1521 });
1522 cx.notify();
1523 }
1524
1525 fn start_fetch(&mut self, cx: &mut Context<Self>) {
1526 let state = self.app.read(cx);
1527 let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
1528 if engine.is_none() && demo_sync.is_none() {
1529 return;
1530 }
1531 let Some(current) = self.current.as_mut() else {
1532 return;
1533 };
1534 if current.fetched {
1535 return;
1536 }
1537 current.fetched = true;
1538 let is_chat = matches!(current.selection, Selection::Chat(_));
1539 let newest_cached = self
1540 .rows
1541 .borrow()
1542 .iter()
1543 .flat_map(Row::messages)
1544 .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX))
1545 .map(|message| message.created_at)
1546 .max();
1547 let current = self.current.as_mut().expect("checked above");
1548 if current.sync.failed {
1549 self.notice = None;
1550 }
1551 current.sync = SyncProgress {
1552 messages: true,
1553 receipts: is_chat,
1554 empty_cache: newest_cached.is_none(),
1555 newest_cached,
1556 ..SyncProgress::default()
1557 };
1558 self.sync_generation += 1;
1559 let generation = self.sync_generation;
1560 let conversation_id = current.selection.conversation_id().to_owned();
1561 match (engine, demo_sync) {
1562 (Some(engine), _) => {
1563 let receiver =
1564 runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
1565 cx.spawn(async move |this, cx| {
1566 let result = receiver.await;
1567 this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
1568 .ok();
1569 })
1570 .detach();
1571 }
1572 (None, Some(delay)) => self.simulate_sync(generation, delay, cx),
1573 (None, None) => {}
1574 }
1575 self.schedule_progress(generation, cx);
1576 self.rebuild(false, cx);
1577 self.mark_read(ReadTrigger::Incoming, cx);
1578 self.refresh_receipts(generation, cx);
1579 }
1580
1581 fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
1582 cx.spawn(async move |this, cx| {
1583 cx.background_executor().timer(delay).await;
1584 this.update(cx, |this, cx| {
1585 if let Some(sync) = this.sync_of(generation) {
1586 sync.receipts = false;
1587 }
1588 this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
1589 })
1590 .ok();
1591 })
1592 .detach();
1593 }
1594
1595 fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
1596 if generation != self.sync_generation {
1597 return None;
1598 }
1599 self.current.as_mut().map(|current| &mut current.sync)
1600 }
1601
1602 fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1603 cx.spawn(async move |this, cx| {
1604 let stages = [
1605 (PROGRESS_DELAY, Duration::ZERO),
1606 (SLOW_AFTER, PROGRESS_DELAY),
1607 ];
1608 for (stage, (at, previous)) in stages.into_iter().enumerate() {
1609 cx.background_executor().timer(at - previous).await;
1610 let running = this
1611 .update(cx, |this, cx| this.advance_progress(generation, stage, cx))
1612 .unwrap_or(false);
1613 if !running {
1614 return;
1615 }
1616 }
1617 })
1618 .detach();
1619 }
1620
1621 fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
1622 let Some(sync) = self.sync_of(generation) else {
1623 return false;
1624 };
1625 if !sync.running() {
1626 return false;
1627 }
1628 match stage {
1629 0 => sync.shown_at = Some(Instant::now()),
1630 _ => sync.slow = true,
1631 }
1632 cx.notify();
1633 true
1634 }
1635
1636 fn finish_fetch(
1637 &mut self,
1638 generation: u64,
1639 result: Result<
1640 teams_core::Result<teams_core::Delta>,
1641 tokio::sync::oneshot::error::RecvError,
1642 >,
1643 cx: &mut Context<Self>,
1644 ) {
1645 let Some(sync) = self.sync_of(generation) else {
1646 return;
1647 };
1648 sync.messages = false;
1649 let newest_cached = sync.newest_cached;
1650 match result {
1651 Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx),
1652 Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),
1653 Err(error) => self.fail_sync(generation, short_error(&error)),
1654 }
1655 self.rebuild(false, cx);
1656 self.settle_progress(generation, cx);
1657 }
1658
1659 fn fail_sync(&mut self, generation: u64, error: String) {
1660 if let Some(sync) = self.sync_of(generation) {
1661 sync.failed = true;
1662 sync.receipts = false;
1663 }
1664 self.notice = Some(format!("Could not refresh: {error}"));
1665 }
1666
1667 fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) {
1668 let Some(newest_cached) = newest_cached else {
1669 return;
1670 };
1671 let Some(my_user_id) = self.row_context(cx).my_user_id else {
1672 return;
1673 };
1674 let store = self.app.read(cx).store.clone();
1675 let Some(current) = self.current.as_mut() else {
1676 return;
1677 };
1678 if current.first_unread.is_some() || current.mode != ViewMode::Flat {
1679 return;
1680 }
1681 let limit = current
1682 .loaded_limit
1683 .max(current.loaded_count + GROWTH_HEADROOM);
1684 current.first_unread = store
1685 .messages(current.selection.conversation_id(), None, limit)
1686 .unwrap_or_default()
1687 .into_iter()
1688 .find(|record| {
1689 record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id)
1690 })
1691 .map(|record| record.message_id);
1692 }
1693
1694 fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1695 let Some(sync) = self.sync_of(generation) else {
1696 return;
1697 };
1698 if sync.running() {
1699 return;
1700 }
1701 let remaining = sync
1702 .shown_at
1703 .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
1704 .unwrap_or_default();
1705 if remaining.is_zero() {
1706 sync.shown_at = None;
1707 sync.slow = false;
1708 cx.notify();
1709 return;
1710 }
1711 cx.spawn(async move |this, cx| {
1712 cx.background_executor().timer(remaining).await;
1713 this.update(cx, |this, cx| {
1714 if let Some(sync) = this.sync_of(generation) {
1715 sync.shown_at = None;
1716 sync.slow = false;
1717 cx.notify();
1718 }
1719 })
1720 .ok();
1721 })
1722 .detach();
1723 }
1724
1725 fn retry_fetch(&mut self, cx: &mut Context<Self>) {
1726 if let Some(current) = self.current.as_mut() {
1727 current.fetched = false;
1728 }
1729 self.start_fetch(cx);
1730 }
1731
1732 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1733 let state = self.app.read(cx);
1734 let receipts_syncing = self
1735 .current
1736 .as_ref()
1737 .is_some_and(|current| current.sync.receipts);
1738 if state.mode.demo {
1739 let read_ids = crate::demo::read_message_ids(records);
1740 return records
1741 .iter()
1742 .map(|record| {
1743 let receipt = if receipts_syncing {
1744 Receipt::Pending
1745 } else if read_ids.contains(&record.message_id) {
1746 Receipt::Read
1747 } else {
1748 Receipt::Sent
1749 };
1750 (record.message_id.clone(), receipt)
1751 })
1752 .collect();
1753 }
1754 let Some(engine) = state.engine.as_ref() else {
1755 return HashMap::new();
1756 };
1757 let unknown = if receipts_syncing {
1758 Receipt::Pending
1759 } else {
1760 Receipt::Hidden
1761 };
1762 records
1763 .iter()
1764 .map(|record| {
1765 let receipt = match engine.receipt_state_for(record) {
1766 teams_core::ReceiptState::Read { .. } => Receipt::Read,
1767 teams_core::ReceiptState::Sent => Receipt::Sent,
1768 teams_core::ReceiptState::Unknown => unknown,
1769 };
1770 (record.message_id.clone(), receipt)
1771 })
1772 .collect()
1773 }
1774
1775 fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
1776 let state = self.app.read(cx);
1777 let (Some(engine), Some(Selection::Chat(chat_id))) = (
1778 state.engine.clone(),
1779 self.current.as_ref().map(|c| c.selection.clone()),
1780 ) else {
1781 return;
1782 };
1783 let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
1784 cx.spawn(async move |this, cx| {
1785 receiver.await.ok();
1786 this.update(cx, |this, cx| {
1787 let Some(sync) = this.sync_of(generation) else {
1788 return;
1789 };
1790 sync.receipts = false;
1791 this.rebuild(false, cx);
1792 this.settle_progress(generation, cx);
1793 })
1794 .ok();
1795 })
1796 .detach();
1797 }
1798
1799 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
1800 if self.draft_active {
1801 return;
1802 }
1803 let state = self.app.read(cx);
1804 if state.viewing_call() && !self.pinned {
1805 return;
1806 }
1807 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
1808 else {
1809 return;
1810 };
1811 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
1812 return;
1813 }
1814 let unread = state
1815 .sidebar
1816 .chats
1817 .iter()
1818 .any(|chat| chat.id == chat_id && chat.unread)
1819 && !state.keeps_unread(&chat_id);
1820 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
1821 return;
1822 };
1823 self.app
1824 .update(cx, |state, cx| state.mark_chat_read(&chat_id, cx));
1825 if plan.clear_divider
1826 && let Some(current) = self.current.as_mut()
1827 && current.first_unread.take().is_some()
1828 {
1829 self.rebuild(false, cx);
1830 }
1831 }
1832
1833 fn request_older(&mut self, cx: &mut Context<Self>) {
1834 let Some(engine) = self.app.read(cx).engine.clone() else {
1835 return;
1836 };
1837 let Some(current) = self.current.as_mut() else {
1838 return;
1839 };
1840 if current.loading_older || current.older_blocked || !current.has_older {
1841 return;
1842 }
1843 current.loading_older = true;
1844 let conversation_id = current.selection.conversation_id().to_owned();
1845 let task_id = conversation_id.clone();
1846 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
1847 cx.spawn(async move |this, cx| {
1848 let result = receiver.await;
1849 this.update(cx, |this, cx| {
1850 this.finish_older(&conversation_id, result, cx)
1851 })
1852 .ok();
1853 })
1854 .detach();
1855 }
1856
1857 fn finish_older(
1858 &mut self,
1859 conversation_id: &str,
1860 result: Result<
1861 teams_core::Result<Vec<MessageRecord>>,
1862 tokio::sync::oneshot::error::RecvError,
1863 >,
1864 cx: &mut Context<Self>,
1865 ) {
1866 let Some(current) = self.current.as_mut() else {
1867 return;
1868 };
1869 if current.selection.conversation_id() != conversation_id {
1870 return;
1871 }
1872 current.loading_older = false;
1873 match result {
1874 Ok(Ok(records)) if !records.is_empty() => {
1875 current.loaded_limit = current.loaded_count + records.len();
1876 }
1877 Ok(Ok(_)) => current.older_blocked = true,
1878 Ok(Err(error)) => {
1879 current.older_blocked = true;
1880 self.notice = Some(format!(
1881 "Could not load older messages: {}",
1882 short_error(&error)
1883 ));
1884 }
1885 Err(_) => current.older_blocked = true,
1886 }
1887 self.rebuild(false, cx);
1888 }
1889
1890 fn clear_pending(&mut self) {
1891 self.pending.clear();
1892 self.pending_outgoing.clear();
1893 }
1894
1895 fn outbox_route(&self, reply_root: Option<String>) -> (OutboxTarget, Option<String>) {
1896 if let Some(root_id) = reply_root {
1897 return (OutboxTarget::Thread, Some(root_id));
1898 }
1899 match self.current.as_ref().map(|current| &current.mode) {
1900 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
1901 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
1902 _ => (OutboxTarget::Flat, None),
1903 }
1904 }
1905
1906 fn reload_pending(&mut self, cx: &App) {
1907 self.clear_pending();
1908 let state = self.app.read(cx);
1909 if state.mode.demo || state.mode.read_only {
1910 return;
1911 }
1912 let Some(current) = self.current.as_ref() else {
1913 return;
1914 };
1915 let conversation_id = current.selection.conversation_id().to_owned();
1916 let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else {
1917 return;
1918 };
1919 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
1920 let mut pending = Vec::new();
1921 for record in records {
1922 if !shown_in_view(&current.mode, &record) {
1923 continue;
1924 }
1925 let Some(outgoing) = outgoing_of(&record) else {
1926 continue;
1927 };
1928 let delivery = match record.state {
1929 OutboxState::Sending => Delivery::Sending,
1930 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
1931 };
1932 let mut row = pending_row(
1933 record.id.clone(),
1934 conversation_id.clone(),
1935 my_user_id.clone(),
1936 record.created_at,
1937 &outgoing,
1938 delivery,
1939 );
1940 row.reply_root = record.thread_root_id.clone();
1941 pending.push((row, record.id, outgoing));
1942 }
1943 for (row, id, outgoing) in pending {
1944 self.pending.push(row);
1945 self.pending_outgoing.insert(id, outgoing);
1946 }
1947 }
1948
1949 fn discard_outbox_row(&self, id: &str, cx: &mut Context<Self>) {
1950 self.app.read(cx).store.delete_outbox(id).ok();
1951 self.app
1952 .update(cx, |state, cx| state.refresh_local_previews(cx));
1953 }
1954
1955 fn delete_pending(&mut self, key: &str, cx: &mut Context<Self>) {
1956 self.pending.retain(|row| row.key != key);
1957 self.pending_outgoing.remove(key);
1958 self.discard_outbox_row(key, cx);
1959 self.rebuild(false, cx);
1960 }
1961
1962 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1963 self.send_as(new_outbox_id(), outgoing, None, window, cx);
1964 }
1965
1966 fn send_in_thread(
1967 &mut self,
1968 root_id: String,
1969 outgoing: Outgoing,
1970 window: &mut Window,
1971 cx: &mut Context<Self>,
1972 ) {
1973 self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx);
1974 }
1975
1976 fn send_as(
1977 &mut self,
1978 id: String,
1979 outgoing: Outgoing,
1980 reply_root: Option<String>,
1981 window: &mut Window,
1982 cx: &mut Context<Self>,
1983 ) {
1984 let state = self.app.read(cx);
1985 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1986 let Some(current) = self.current.as_ref() else {
1987 return;
1988 };
1989 if mode.read_only || mode.demo {
1990 self.restore_unsent(
1991 "Read-only mode: nothing was sent",
1992 &outgoing,
1993 reply_root.as_deref(),
1994 window,
1995 cx,
1996 );
1997 return;
1998 }
1999 let Some(engine) = engine else {
2000 self.discard_outbox_row(&id, cx);
2001 self.restore_unsent(
2002 "Not connected yet: nothing was sent",
2003 &outgoing,
2004 reply_root.as_deref(),
2005 window,
2006 cx,
2007 );
2008 return;
2009 };
2010 let conversation_id = current.selection.conversation_id().to_owned();
2011 let (target, thread_root_id) = self.outbox_route(reply_root);
2012 let created_at = Utc::now();
2013 self.push_pending(
2014 id.clone(),
2015 created_at,
2016 &outgoing,
2017 thread_root_id.clone(),
2018 cx,
2019 );
2020 if let Some(record) = outbox_record(
2021 &id,
2022 &conversation_id,
2023 target,
2024 thread_root_id.as_deref(),
2025 &outgoing,
2026 created_at,
2027 ) {
2028 store.put_outbox(&record).ok();
2029 }
2030 self.notice = None;
2031 self.rebuild(false, cx);
2032 if self.in_feed() {
2033 self.scroller
2034 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2035 } else {
2036 self.scroller
2037 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
2038 }
2039
2040 let receiver = runtime::spawn(async move {
2041 deliver(
2042 &engine,
2043 &conversation_id,
2044 target,
2045 thread_root_id.as_deref(),
2046 &outgoing,
2047 )
2048 .await
2049 });
2050 cx.spawn_in(window, async move |this, cx| {
2051 let result = receiver.await;
2052 this.update(cx, |this, cx| this.finish_send(&id, result, cx))
2053 .ok();
2054 })
2055 .detach();
2056 }
2057
2058 fn restore_unsent(
2059 &mut self,
2060 message: &str,
2061 outgoing: &Outgoing,
2062 reply_root: Option<&str>,
2063 window: &mut Window,
2064 cx: &mut Context<Self>,
2065 ) {
2066 self.notice = Some(message.to_owned());
2067 if let (Some(root_id), true) = (reply_root, self.in_feed()) {
2068 self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx);
2069 if let Some(composer) = self.reply_composer.clone() {
2070 composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2071 }
2072 } else {
2073 self.show_main_composer(cx);
2074 self.restore_subject(outgoing.subject.as_deref(), window, cx);
2075 self.composer
2076 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2077 }
2078 cx.notify();
2079 }
2080
2081 fn next_pending_key(&mut self) -> String {
2082 self.pending_counter += 1;
2083 format!("{PENDING_KEY_PREFIX}{}", self.pending_counter)
2084 }
2085
2086 fn push_pending(
2087 &mut self,
2088 key: String,
2089 created_at: DateTime<Utc>,
2090 outgoing: &Outgoing,
2091 reply_root: Option<String>,
2092 cx: &App,
2093 ) {
2094 let my_user_id = self.row_context(cx).my_user_id;
2095 let conversation_id = self
2096 .current
2097 .as_ref()
2098 .map(|current| current.selection.conversation_id().to_owned())
2099 .unwrap_or_default();
2100 let mut row = pending_row(
2101 key.clone(),
2102 conversation_id,
2103 my_user_id,
2104 created_at,
2105 outgoing,
2106 Delivery::Sending,
2107 );
2108 row.reply_root = reply_root;
2109 self.pending.push(row);
2110 self.pending_outgoing.insert(key, outgoing.clone());
2111 }
2112
2113 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2114 let (recipients, topic) = {
2115 let draft = self.draft.read(cx);
2116 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
2117 (draft.chips().to_vec(), topic)
2118 };
2119 if recipients.is_empty() {
2120 self.restore_unsent("Add at least one person first", &outgoing, None, window, cx);
2121 self.draft
2122 .update(cx, |draft, cx| draft.focus_query(window, cx));
2123 return;
2124 }
2125 if self
2126 .pending
2127 .iter()
2128 .any(|row| matches!(row.delivery, Delivery::Sending))
2129 {
2130 self.restore_unsent("Still creating the chat", &outgoing, None, window, cx);
2131 return;
2132 }
2133 let state = self.app.read(cx);
2134 let (mode, engine) = (state.mode, state.engine.clone());
2135 if mode.read_only {
2136 self.restore_unsent(
2137 "Read-only mode: nothing was sent",
2138 &outgoing,
2139 None,
2140 window,
2141 cx,
2142 );
2143 return;
2144 }
2145 if mode.demo && outgoing.has_attachments() {
2146 self.restore_unsent(
2147 "Read-only mode: nothing was sent",
2148 &outgoing,
2149 None,
2150 window,
2151 cx,
2152 );
2153 return;
2154 }
2155 if mode.demo {
2156 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
2157 return;
2158 }
2159 let Some(engine) = engine else {
2160 self.restore_unsent(
2161 "Not connected yet: nothing was sent",
2162 &outgoing,
2163 None,
2164 window,
2165 cx,
2166 );
2167 return;
2168 };
2169 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
2170 let known_chat = self
2171 .draft_created
2172 .as_ref()
2173 .filter(|(created_for, _)| *created_for == user_ids)
2174 .map(|(_, chat_id)| chat_id.clone())
2175 .or_else(|| self.draft_target_chat(cx));
2176 self.pending.clear();
2177 self.pending_outgoing.clear();
2178 self.draft_error = None;
2179 self.notice = None;
2180 let key = self.next_pending_key();
2181 self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx);
2182 self.rebuild(true, cx);
2183 let recipients_for_finish = user_ids.clone();
2184 let receiver = runtime::spawn(async move {
2185 let chat_id = match known_chat {
2186 Some(chat_id) => chat_id,
2187 None => {
2188 let created = match user_ids.as_slice() {
2189 [user_id] => engine.create_one_on_one(user_id).await,
2190 _ => engine.create_group(&user_ids, topic.as_deref()).await,
2191 };
2192 match created {
2193 Ok(chat_id) => chat_id,
2194 Err(error) => return (None, Some(short_error(&error))),
2195 }
2196 }
2197 };
2198 let sent = engine
2199 .send_message_with_extras(
2200 &chat_id,
2201 &outgoing.html(),
2202 None,
2203 &outgoing.mentions,
2204 &outgoing.extras(),
2205 )
2206 .await;
2207 if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {
2208 let _ = engine
2209 .attach_link_preview(&chat_id, &record.message_id, preview)
2210 .await;
2211 }
2212 (Some(chat_id), sent.err().map(|error| short_error(&error)))
2213 });
2214 cx.spawn_in(window, async move |this, cx| {
2215 let result = receiver.await;
2216 this.update_in(cx, |this, _, cx| {
2217 this.finish_new_chat(&key, recipients_for_finish, result, cx)
2218 })
2219 .ok();
2220 })
2221 .detach();
2222 }
2223
2224 fn finish_new_chat(
2225 &mut self,
2226 key: &str,
2227 user_ids: Vec<String>,
2228 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
2229 cx: &mut Context<Self>,
2230 ) {
2231 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
2232 return;
2233 }
2234 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
2235 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
2236 match (chat_id, error) {
2237 (Some(chat_id), None) => {
2238 self.app.update(cx, |state, cx| {
2239 state.reload_sidebar(cx);
2240 state.select(Selection::Chat(chat_id), cx);
2241 });
2242 }
2243 (created, error) => {
2244 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2245 row.delivery = Delivery::Failed(error.unwrap_or_default());
2246 }
2247 self.draft_error = Some(
2248 if created.is_some() {
2249 "Couldn't send the message."
2250 } else {
2251 "Couldn't create the chat."
2252 }
2253 .to_owned(),
2254 );
2255 self.rebuild(false, cx);
2256 }
2257 }
2258 }
2259
2260 fn send_demo_new_chat(
2261 &mut self,
2262 outgoing: &Outgoing,
2263 recipients: &[super::new_chat::Pick],
2264 topic: Option<&str>,
2265 cx: &mut Context<Self>,
2266 ) {
2267 let (store, chats) = {
2268 let state = self.app.read(cx);
2269 (state.store.clone(), state.sidebar.chats.clone())
2270 };
2271 let people: Vec<(String, String)> = recipients
2272 .iter()
2273 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
2274 .collect();
2275 let (chat, message) = match self.draft_target_chat(cx) {
2276 Some(chat_id) => {
2277 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
2278 return;
2279 };
2280 crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now())
2281 }
2282 None => crate::demo::new_chat(
2283 &chats,
2284 &people,
2285 topic,
2286 &outgoing.text(),
2287 &outgoing.html(),
2288 Utc::now(),
2289 ),
2290 };
2291 let _ = store.upsert_chats(std::slice::from_ref(&chat));
2292 let _ = store.upsert_messages(std::slice::from_ref(&message));
2293 self.app.update(cx, |state, cx| {
2294 state.reload_sidebar(cx);
2295 state.select(Selection::Chat(chat.id.clone()), cx);
2296 });
2297 }
2298
2299 fn conversation_id(&self) -> Option<String> {
2300 self.current
2301 .as_ref()
2302 .map(|current| current.selection.conversation_id().to_owned())
2303 }
2304
2305 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
2306 let conversation_id = self.conversation_id()?;
2307 let my_user_id = self.row_context(cx).my_user_id?;
2308 self.app
2309 .read(cx)
2310 .store
2311 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2312 .ok()?
2313 .remove(message_id)
2314 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
2315 }
2316
2317 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
2318 let target = match slot {
2319 HoverSlot::Row => &mut self.hovered_message,
2320 HoverSlot::Toolbar => &mut self.toolbar_hovered,
2321 };
2322 if hovered {
2323 *target = Some(key.to_owned());
2324 } else if target.as_deref() == Some(key) {
2325 *target = None;
2326 }
2327 if let Some(suppressed) = self.toolbar_suppressed.as_deref()
2328 && self.hovered_message.as_deref() != Some(suppressed)
2329 && self.toolbar_hovered.as_deref() != Some(suppressed)
2330 {
2331 self.toolbar_suppressed = None;
2332 }
2333 cx.notify();
2334 }
2335
2336 fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2337 if self.toolbar_hovered.as_deref() == Some(key) {
2338 self.toolbar_hovered = None;
2339 }
2340 self.toolbar_suppressed = Some(key.to_owned());
2341 cx.notify();
2342 }
2343
2344 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
2345 if open {
2346 self.toolbar_pinned = Some(key.to_owned());
2347 } else if self.toolbar_pinned.as_deref() == Some(key) {
2348 self.toolbar_pinned = None;
2349 }
2350 cx.notify();
2351 }
2352
2353 fn toolbar_visible(&self, key: &str) -> bool {
2354 self.toolbar_suppressed.as_deref() != Some(key)
2355 && self
2356 .toolbar_pinned
2357 .as_deref()
2358 .or(self.toolbar_hovered.as_deref())
2359 .or(self.hovered_message.as_deref())
2360 == Some(key)
2361 }
2362
2363 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
2364 let Some(conversation_id) = self.conversation_id() else {
2365 return;
2366 };
2367 let state = self.app.read(cx);
2368 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2369 let engine = engine.filter(|_| !mode.read_only);
2370 if !mode.demo && engine.is_none() {
2371 self.show_notice("Read-only mode: reaction not sent", cx);
2372 return;
2373 }
2374 let my_user_id = self.row_context(cx).my_user_id;
2375 let Some(mut record) = store
2376 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2377 .ok()
2378 .and_then(|mut found| found.remove(message_id))
2379 else {
2380 return;
2381 };
2382 let wanted = reaction_glyph(glyph);
2383 let mut visible = teams_core::reactions(&record);
2384 apply_pending_reactions(
2385 &mut visible,
2386 self.pending_reactions.get(message_id),
2387 my_user_id.as_deref(),
2388 Utc::now(),
2389 );
2390 let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref());
2391 let Some(engine) = engine.filter(|_| !mode.demo) else {
2392 let mut reactions = teams_core::reactions(&record);
2393 set_own_reaction(
2394 &mut reactions,
2395 glyph,
2396 my_user_id.as_deref(),
2397 added,
2398 Utc::now(),
2399 );
2400 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2401 let _ = store.upsert_messages(std::slice::from_ref(&record));
2402 if added {
2403 self.record_reaction_use(glyph, cx);
2404 }
2405 self.rebuild(false, cx);
2406 return;
2407 };
2408 let entries = self
2409 .pending_reactions
2410 .entry(message_id.to_owned())
2411 .or_default();
2412 entries.retain(|(pending, _)| *pending != wanted);
2413 entries.push((wanted.clone(), added));
2414 self.rebuild(false, cx);
2415 let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned());
2416 let reaction_type = api_reaction(&wanted);
2417 let receiver = runtime::spawn({
2418 let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone());
2419 async move {
2420 if added {
2421 engine
2422 .set_reaction(&conversation_id, &message_id, &reaction_type)
2423 .await
2424 } else {
2425 engine
2426 .unset_reaction(&conversation_id, &message_id, &reaction_type)
2427 .await
2428 }
2429 }
2430 });
2431 cx.spawn(async move |this, cx| {
2432 let outcome = match receiver.await {
2433 Ok(Ok(())) => Ok(()),
2434 Ok(Err(error)) => Err(short_error(&error)),
2435 Err(_) => Err("cancelled".to_owned()),
2436 };
2437 this.update(cx, |this, cx| {
2438 this.finish_reaction(&conversation_id, &message_id, &glyph, added, outcome, cx)
2439 })
2440 .ok();
2441 })
2442 .detach();
2443 }
2444
2445 fn finish_reaction(
2446 &mut self,
2447 conversation_id: &str,
2448 message_id: &str,
2449 glyph: &str,
2450 added: bool,
2451 outcome: Result<(), String>,
2452 cx: &mut Context<Self>,
2453 ) {
2454 let wanted = reaction_glyph(glyph);
2455 let store = self.app.read(cx).store.clone();
2456 if outcome.is_ok() {
2457 let my_user_id = self.row_context(cx).my_user_id;
2458 if let Some(mut record) = store
2459 .messages_by_id(conversation_id, &[message_id.to_owned()])
2460 .ok()
2461 .and_then(|mut found| found.remove(message_id))
2462 {
2463 let mut reactions = teams_core::reactions(&record);
2464 set_own_reaction(
2465 &mut reactions,
2466 glyph,
2467 my_user_id.as_deref(),
2468 added,
2469 Utc::now(),
2470 );
2471 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2472 let _ = store.upsert_messages(std::slice::from_ref(&record));
2473 }
2474 if added {
2475 self.record_reaction_use(glyph, cx);
2476 }
2477 }
2478 if let Some(entries) = self.pending_reactions.get_mut(message_id) {
2479 entries.retain(|entry| *entry != (wanted.clone(), added));
2480 if entries.is_empty() {
2481 self.pending_reactions.remove(message_id);
2482 }
2483 }
2484 self.rebuild(false, cx);
2485 if let Err(error) = outcome {
2486 self.show_notice(&format!("Reaction failed: {error}"), cx);
2487 }
2488 }
2489
2490 fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) {
2491 let store = self.app.read(cx).store.clone();
2492 self.recent.update(cx, |recent, cx| {
2493 recent.reload(&store);
2494 recent.record_use(glyph);
2495 recent.save(&store);
2496 cx.notify();
2497 });
2498 }
2499
2500 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
2501 let Some(record) = self.own_record(message_id, cx) else {
2502 return;
2503 };
2504 let edit = EditPreview {
2505 message_id: record.message_id.clone(),
2506 excerpt: reply_excerpt(&record),
2507 scheduled: None,
2508 };
2509 let in_chat = matches!(
2510 self.current.as_ref().map(|current| &current.selection),
2511 Some(Selection::Chat(_))
2512 );
2513 let mentions = if in_chat {
2514 teams_core::user_mention_inputs(&record)
2515 } else {
2516 Vec::new()
2517 };
2518 let draft = Outgoing {
2519 draft: message_draft(&record),
2520 subject: None,
2521 mentions,
2522 reply: None,
2523 edit: Some(edit),
2524 images: Vec::new(),
2525 files: Vec::new(),
2526 link_preview: None,
2527 };
2528 self.show_main_composer(cx);
2529 self.composer
2530 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2531 }
2532
2533 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2534 if self.draft_active {
2535 return;
2536 }
2537 let key = self
2538 .rows
2539 .borrow()
2540 .iter()
2541 .flat_map(Row::messages)
2542 .filter(|message| {
2543 message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX)
2544 })
2545 .max_by_key(|message| message.created_at)
2546 .map(|message| message.key.clone());
2547 if let Some(key) = key {
2548 self.begin_edit(&key, window, cx);
2549 }
2550 }
2551
2552 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2553 let Some(edit) = outgoing.edit.clone() else {
2554 return;
2555 };
2556 let Some(conversation_id) = self.conversation_id() else {
2557 return;
2558 };
2559 let state = self.app.read(cx);
2560 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2561 if mode.demo {
2562 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
2563 record.body_html = outgoing.html();
2564 record.edited_at = Some(Utc::now());
2565 let _ = store.upsert_messages(std::slice::from_ref(&record));
2566 self.rebuild(false, cx);
2567 }
2568 return;
2569 }
2570 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2571 self.notice = Some("Read-only mode: edit not saved".to_owned());
2572 self.show_main_composer(cx);
2573 self.composer
2574 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2575 cx.notify();
2576 return;
2577 };
2578 let sent = outgoing.clone();
2579 let receiver = runtime::spawn(async move {
2580 engine
2581 .edit_message_html(
2582 &conversation_id,
2583 &edit.message_id,
2584 &sent.html(),
2585 &sent.mentions,
2586 )
2587 .await
2588 });
2589 cx.spawn_in(window, async move |this, cx| {
2590 let failed = !matches!(receiver.await, Ok(Ok(())));
2591 this.update_in(cx, |this, window, cx| {
2592 if failed {
2593 this.show_main_composer(cx);
2594 if this.composer.read(cx).is_empty(cx) {
2595 this.notice =
2596 Some("Edit failed: your text is back in the composer".to_owned());
2597 this.composer
2598 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2599 } else {
2600 this.notice = Some("Edit failed".to_owned());
2601 }
2602 cx.notify();
2603 }
2604 })
2605 .ok();
2606 })
2607 .detach();
2608 }
2609
2610 fn delete(&mut self, message_id: &str, cx: &mut Context<Self>) {
2611 let Some(mut record) = self.own_record(message_id, cx) else {
2612 return;
2613 };
2614 let state = self.app.read(cx);
2615 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2616 if mode.demo {
2617 record.deleted = true;
2618 let _ = store.upsert_messages(std::slice::from_ref(&record));
2619 self.rebuild(false, cx);
2620 return;
2621 }
2622 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2623 self.show_notice("Read-only mode: message not deleted", cx);
2624 return;
2625 };
2626 let conversation_id = record.conversation_id.clone();
2627 let receiver = runtime::spawn(async move {
2628 engine
2629 .soft_delete_message(&conversation_id, &record.message_id)
2630 .await
2631 });
2632 self.report_failure(receiver, "Delete failed", cx);
2633 }
2634
2635 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2636 let Some(conversation_id) = self.conversation_id() else {
2637 return;
2638 };
2639 let record = self
2640 .app
2641 .read(cx)
2642 .store
2643 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2644 .ok()
2645 .and_then(|mut found| found.remove(message_id));
2646 if let Some(record) = record {
2647 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
2648 }
2649 }
2650
2651 fn refresh_card(
2652 &mut self,
2653 key: &str,
2654 card_index: usize,
2655 action: ExecuteAction,
2656 cx: &mut Context<Self>,
2657 ) {
2658 let Some(conversation_id) = self.conversation_id() else {
2659 return;
2660 };
2661 let scope = CardScope::message(&conversation_id, key, card_index);
2662 self.app.update(cx, |state, cx| {
2663 state.refresh_card_manually(scope, action, cx)
2664 });
2665 }
2666
2667 pub(super) fn translate_message(&mut self, key: &str, cx: &mut Context<Self>) {
2668 let Some(conversation_id) = self.conversation_id() else {
2669 return;
2670 };
2671 self.app.update(cx, |state, cx| {
2672 state.translate_message(&conversation_id, key, cx)
2673 });
2674 }
2675
2676 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2677 self.app.update(cx, |state, cx| {
2678 state.raise_notice(message.to_owned(), None, cx)
2679 });
2680 }
2681
2682 fn report_failure(
2683 &mut self,
2684 receiver: tokio::sync::oneshot::Receiver<teams_core::Result<()>>,
2685 label: &'static str,
2686 cx: &mut Context<Self>,
2687 ) {
2688 cx.spawn(async move |this, cx| {
2689 let error = match receiver.await {
2690 Ok(Ok(())) => return,
2691 Ok(Err(error)) => short_error(&error),
2692 Err(_) => "cancelled".to_owned(),
2693 };
2694 this.update(cx, |this, cx| {
2695 this.show_notice(&format!("{label}: {error}"), cx)
2696 })
2697 .ok();
2698 })
2699 .detach();
2700 }
2701
2702 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2703 let (Some(conversation_id), Some(runs)) =
2704 (self.conversation_id(), crate::agents::runs_handle(cx))
2705 else {
2706 return (Vec::new(), None);
2707 };
2708 if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) {
2709 return (Vec::new(), None);
2710 }
2711 let settings = runs.read(cx).settings();
2712 let entries: Vec<DelegateEntry> = settings
2713 .actions
2714 .iter()
2715 .map(|action| {
2716 let request = StartRequest {
2717 action_id: action.id.clone(),
2718 conversation_id: conversation_id.clone(),
2719 message_id: key.to_owned(),
2720 };
2721 let agent_name = settings
2722 .agents
2723 .iter()
2724 .find(|agent| agent.id == action.agent_id)
2725 .map(|agent| agent.name.clone())
2726 .unwrap_or_default();
2727 DelegateEntry {
2728 label: action.label.clone(),
2729 agent_name,
2730 action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)),
2731 }
2732 })
2733 .collect();
2734 let manage_agents = (!entries.is_empty()).then(|| {
2735 Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action
2736 });
2737 (entries, manage_agents)
2738 }
2739
2740 fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) {
2741 let Some(conversation_id) = self.conversation_id() else {
2742 return (false, HashSet::new());
2743 };
2744 let Some(runs) = crate::agents::runs_handle(cx) else {
2745 return (false, HashSet::new());
2746 };
2747 let mut snapshot: HashMap<String, AgentRun> = HashMap::new();
2748 for run in runs.read(cx).for_conversation(&conversation_id) {
2749 snapshot.insert(run.message_id.clone(), run.clone());
2750 }
2751 let layouts: HashMap<String, (usize, bool)> = snapshot
2752 .iter()
2753 .map(|(key, run)| (key.clone(), run.layout_key()))
2754 .collect();
2755 let layout_changed: HashSet<String> = layouts
2756 .iter()
2757 .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout))
2758 .map(|(key, _)| key.clone())
2759 .chain(
2760 self.agent_layouts
2761 .keys()
2762 .filter(|key| !layouts.contains_key(*key))
2763 .cloned(),
2764 )
2765 .collect();
2766 self.agent_layouts = layouts;
2767 let snapshot_changed = *self.agent_runs.borrow() != snapshot;
2768 *self.agent_runs.borrow_mut() = snapshot;
2769 (snapshot_changed, layout_changed)
2770 }
2771
2772 fn sync_agent_chips(&mut self, cx: &mut Context<Self>) {
2773 let (snapshot_changed, changed) = self.refresh_agent_runs(cx);
2774 let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running);
2775 if !changed.is_empty() {
2776 let indices: Vec<usize> = self
2777 .rows
2778 .borrow()
2779 .iter()
2780 .enumerate()
2781 .filter(|(_, row)| row.messages().any(|message| changed.contains(&message.key)))
2782 .map(|(index, _)| index)
2783 .collect();
2784 self.scroller.update(cx, |scroller, cx| {
2785 for index in indices {
2786 scroller.remeasure_items(index..index + 1, cx);
2787 }
2788 });
2789 }
2790 if snapshot_changed || any_running {
2791 cx.notify();
2792 }
2793 }
2794
2795 fn message_menu(
2796 &self,
2797 message: &MessageRow,
2798 mine: HashSet<String>,
2799 refresh: Option<(usize, ExecuteAction)>,
2800 view: WeakEntity<Self>,
2801 cx: &App,
2802 ) -> MessageMenu {
2803 let (key, own) = (message.key.as_str(), message.own);
2804 let translate_label = match message.translation {
2805 Some(TranslationLine::Translated {
2806 showing_original: false,
2807 ..
2808 }) => "See original",
2809 Some(TranslationLine::Translated { .. }) => "See translation",
2810 _ => "Translate",
2811 };
2812 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
2813 let (view, key) = (view.clone(), key.to_owned());
2814 Rc::new(move |window, cx| {
2815 view.update(cx, |this, cx| run(this, &key, window, cx)).ok();
2816 })
2817 };
2818 let react: PickHandler = {
2819 let (view, key) = (view.clone(), key.to_owned());
2820 Rc::new(move |glyph, _, cx| {
2821 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
2822 .ok();
2823 })
2824 };
2825 let hover = {
2826 let (view, key) = (view.clone(), key.to_owned());
2827 Rc::new(move |hovered: bool, cx: &mut App| {
2828 view.update(cx, |this, cx| {
2829 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
2830 })
2831 .ok();
2832 })
2833 };
2834 let pin = {
2835 let (view, key) = (view.clone(), key.to_owned());
2836 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
2837 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
2838 .ok();
2839 })
2840 };
2841 let refresh_card = refresh.map(|(card_index, refresh_action)| {
2842 let (view, key) = (view.clone(), key.to_owned());
2843 Rc::new(move |_: &mut Window, cx: &mut App| {
2844 view.update(cx, |this, cx| {
2845 this.refresh_card(&key, card_index, refresh_action.clone(), cx)
2846 })
2847 .ok();
2848 }) as Action
2849 });
2850 let chat_id = self.chat_id();
2851 let state = self.app.read(cx);
2852 let saved = self
2853 .conversation_id()
2854 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
2855 let pinned = chat_id
2856 .as_deref()
2857 .is_some_and(|chat_id| state.is_pinned(chat_id, key));
2858 let in_chat = chat_id.is_some();
2859 let (delegate, manage_agents) = self.delegate_entries(key, cx);
2860 MessageMenu {
2861 key: key.to_owned(),
2862 react,
2863 reply: Some(action(|this, key, window, cx| {
2864 this.begin_reply(key, window, cx)
2865 })),
2866 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
2867 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
2868 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
2869 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
2870 translate_label,
2871 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
2872 saved,
2873 toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
2874 pinned,
2875 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
2876 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
2877 mark_unread: (in_chat && !own)
2878 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2879 refresh_card,
2880 delegate,
2881 manage_agents,
2882 pin,
2883 hover,
2884 picker: self.picker.clone(),
2885 quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
2886 mine,
2887 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
2888 }
2889 }
2890
2891 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
2892 let Some(outgoing) = self.pending_outgoing.remove(key) else {
2893 return;
2894 };
2895 let reply_root = self
2896 .pending
2897 .iter()
2898 .find(|row| row.key == key)
2899 .and_then(|row| row.reply_root.clone());
2900 self.pending.retain(|row| row.key != key);
2901 if self.draft_active {
2902 self.send_new_chat(outgoing, window, cx);
2903 } else {
2904 self.send_as(key.to_owned(), outgoing, reply_root, window, cx);
2905 }
2906 }
2907
2908 fn finish_send(
2909 &mut self,
2910 key: &str,
2911 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
2912 cx: &mut Context<Self>,
2913 ) {
2914 let failure = match result {
2915 Ok(Ok(())) => None,
2916 Ok(Err(error)) => Some(short_error(&error)),
2917 Err(error) => Some(short_error(&error)),
2918 };
2919 let store = self.app.read(cx).store.clone();
2920 match failure {
2921 None => {
2922 store.delete_outbox(key).ok();
2923 self.pending.retain(|row| row.key != key);
2924 self.pending_outgoing.remove(key);
2925 }
2926 Some(error) => {
2927 store.mark_outbox_failed(key, &error).ok();
2928 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2929 row.delivery = Delivery::Failed(error.clone());
2930 self.notice = Some(format!("Not sent: {error}"));
2931 }
2932 }
2933 }
2934 self.app
2935 .update(cx, |state, cx| state.refresh_local_previews(cx));
2936 self.rebuild(false, cx);
2937 }
2938
2939 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
2940 let target = match self.current.as_ref().map(|current| &current.selection) {
2941 Some(Selection::Chat(_)) => DropTarget::Chat,
2942 Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
2943 Some(Selection::Channel(_)) => DropTarget::Channel,
2944 None => DropTarget::NewChat,
2945 };
2946 let title = self
2947 .current
2948 .as_ref()
2949 .map(|current| current.title.as_str())
2950 .unwrap_or_default();
2951 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
2952 let composer = self.composer.clone();
2953 div()
2954 .id("drop-overlay")
2955 .absolute()
2956 .top_0()
2957 .left_0()
2958 .size_full()
2959 .opacity(0.)
2960 .bg(theme::drop_background())
2961 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
2962 if composer.read(cx).is_editing() {
2963 style
2964 } else {
2965 style.opacity(1.)
2966 }
2967 })
2968 .on_drag_move(
2969 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
2970 let count = event.drag(cx).paths().len();
2971 if this.drag_file_count != count {
2972 this.drag_file_count = count;
2973 cx.notify();
2974 }
2975 }),
2976 )
2977 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
2978 let paths = dropped.paths().to_vec();
2979 if this.shared_active() {
2980 this.upload_paths(paths, cx);
2981 return;
2982 }
2983 this.composer
2984 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
2985 }))
2986 .child(
2987 div()
2988 .absolute()
2989 .inset(px(12.))
2990 .rounded(px(12.))
2991 .border_2()
2992 .border_dashed()
2993 .border_color(theme::accent())
2994 .flex()
2995 .items_center()
2996 .justify_center()
2997 .child(
2998 v_flex()
2999 .items_center()
3000 .gap(px(6.))
3001 .px(px(24.))
3002 .py(px(16.))
3003 .rounded(px(12.))
3004 .bg(black().opacity(0.55))
3005 .child(symbol("upload", 28., theme::accent_text()))
3006 .child(
3007 div()
3008 .text_size(px(15.))
3009 .font_weight(FontWeight::SEMIBOLD)
3010 .text_color(theme::text_strong())
3011 .child(heading),
3012 )
3013 .child(
3014 div()
3015 .text_size(px(12.))
3016 .text_color(theme::text_muted())
3017 .child(detail),
3018 ),
3019 ),
3020 )
3021 }
3022
3023 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
3024 let message = self.draft_error.clone()?;
3025 let failed_key = self
3026 .pending
3027 .iter()
3028 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
3029 .map(|row| row.key.clone())?;
3030 Some(
3031 h_flex()
3032 .w_full()
3033 .flex_none()
3034 .px(px(20.))
3035 .py(px(4.))
3036 .gap(px(8.))
3037 .items_center()
3038 .text_size(px(12.))
3039 .text_color(theme::red_soft())
3040 .child(message)
3041 .child(
3042 Button::new("retry-new-chat")
3043 .ghost()
3044 .compact()
3045 .label("Retry")
3046 .on_click(cx.listener(move |this, _, window, cx| {
3047 this.retry(&failed_key, window, cx)
3048 })),
3049 ),
3050 )
3051 }
3052
3053 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
3054 let app = self.app.read(cx);
3055 let directory = &app.directory;
3056 let me = directory.me.as_ref();
3057 let mut lead: Option<AnyElement> = None;
3058 let mut subline = String::new();
3059 let mut stack: Option<Div> = None;
3060 match &current.selection {
3061 Selection::Chat(chat_id) => {
3062 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3063 let faces = others(chat, me);
3064 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3065 let first = faces.first().cloned().map(face);
3066 if is_one_on_one(chat) || faces.len() < 2 {
3067 let name = first
3068 .as_ref()
3069 .map_or(current.title.as_str(), |face| face.name.as_str());
3070 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
3071 let avatar = person_avatar(directory, user_id, name, 36.);
3072 let presence = user_id.map(|id| directory.presence_of(id));
3073 let avatar = match presence {
3074 Some(kind) => with_presence(avatar, kind, 36., theme::surface())
3075 .into_any_element(),
3076 None => avatar,
3077 };
3078 lead = Some(
3079 opens_profile(div().id("header-avatar").flex_none(), user_id)
3080 .child(avatar)
3081 .into_any_element(),
3082 );
3083 subline = match (user_id, presence) {
3084 (Some(id), Some(presence)) => {
3085 directory.status_label(id, presence).to_owned()
3086 }
3087 _ => String::new(),
3088 };
3089 } else {
3090 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3091 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3092 subline = format!("{} participants", chat.members.len());
3093 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
3094 stack = Some(member_stack(directory, &shown, shown.len()));
3095 }
3096 }
3097 }
3098 Selection::Channel(channel_id) => {
3099 let team = app.sidebar.teams.iter().find(|entry| {
3100 entry
3101 .channels
3102 .iter()
3103 .any(|channel| &channel.id == channel_id)
3104 });
3105 let (name, key) = team
3106 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
3107 (entry.team.name.as_str(), entry.team.id.as_str())
3108 });
3109 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
3110 }
3111 }
3112 let mut header = h_flex()
3113 .w_full()
3114 .h(px(60.))
3115 .flex_none()
3116 .px(px(20.))
3117 .gap(px(12.))
3118 .items_center();
3119 if matches!(current.mode, ViewMode::Thread(_)) {
3120 header = header.child(
3121 h_flex()
3122 .id("back-to-channel")
3123 .flex_none()
3124 .gap(px(2.))
3125 .pl(px(4.))
3126 .pr(px(8.))
3127 .py(px(4.))
3128 .items_center()
3129 .rounded(px(6.))
3130 .cursor_pointer()
3131 .text_size(px(13.))
3132 .font_weight(FontWeight::SEMIBOLD)
3133 .text_color(theme::accent_text())
3134 .hover(|button| button.bg(theme::row_hover()))
3135 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx)))
3136 .child(icon(IconName::ChevronLeft, 16., theme::accent_text()))
3137 .child("Back to channel"),
3138 );
3139 }
3140 let channel_note = match current.mode {
3141 ViewMode::Flat => None,
3142 ViewMode::ThreadList => Some("Posts"),
3143 ViewMode::Thread(_) => Some("Conversation"),
3144 };
3145 if let Some(note) = channel_note {
3146 subline = note.to_owned();
3147 }
3148 let call_controls = if self.pinned {
3149 Vec::new()
3150 } else {
3151 header_call_controls(&self.app, app, &current.selection)
3152 };
3153 let sync = &current.sync;
3154 if sync.failed {
3155 subline = "Not up to date".to_owned();
3156 } else if sync.shown_at.is_some() {
3157 subline = if sync.slow {
3158 "Taking longer than usual ..."
3159 } else if sync.empty_cache {
3160 "Loading messages ..."
3161 } else {
3162 "Updating ..."
3163 }
3164 .to_owned();
3165 }
3166 header
3167 .relative()
3168 .when(sync.shown_at.is_some(), |header| {
3169 header.child(progress_bar())
3170 })
3171 .children(lead)
3172 .child(
3173 v_flex()
3174 .flex_1()
3175 .min_w_0()
3176 .overflow_hidden()
3177 .gap(px(1.))
3178 .child(
3179 div()
3180 .truncate()
3181 .text_size(px(15.))
3182 .font_weight(FontWeight::SEMIBOLD)
3183 .text_color(theme::text())
3184 .child(current.title.clone()),
3185 )
3186 .when(!subline.is_empty(), |column| {
3187 column.child(
3188 div()
3189 .text_size(px(12.))
3190 .text_color(theme::text_muted())
3191 .child(subline),
3192 )
3193 }),
3194 )
3195 .children(stack)
3196 .children(call_controls)
3197 }
3198}
3199
3200impl Render for ConversationView {
3201 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3202 let background = theme::surface();
3203 let mut root = v_flex()
3204 .when(!self.pinned, |root| {
3205 root.debug_selector(|| "shell/islands/main".into())
3206 })
3207 .flex_1()
3208 .w_full()
3209 .min_w_0()
3210 .h_full()
3211 .rounded(px(10.))
3212 .bg(background)
3213 .track_focus(&self.focus_handle);
3214 let drafting = self.draft_active;
3215 if self.current.is_none() && !drafting {
3216 return root
3217 .items_center()
3218 .justify_center()
3219 .text_color(theme::text_muted())
3220 .child("Select a chat or channel")
3221 .into_any_element();
3222 }
3223 let in_feed = self.in_feed();
3224 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3225 if in_feed && rows_seen != usize::MAX {
3226 self.feed_at_top = rows_seen == 0;
3227 }
3228 let rows = self.rows.clone();
3229 let rows_seen = self.feed_rows_seen.clone();
3230 let env = RenderEnv {
3231 view: cx.weak_entity(),
3232 app: self.app.clone(),
3233 highlighted: self.highlighted_message.clone(),
3234 drafting,
3235 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3236 timeline: self.timeline_bounds.clone(),
3237 agent_runs: self.agent_runs.clone(),
3238 };
3239 let scroller = MessageScroller::new(
3240 "messages",
3241 self.scroller.clone(),
3242 move |index, window, cx| {
3243 rows_seen.set(rows_seen.get().min(index));
3244 let rows = rows.borrow();
3245 match rows.get(index) {
3246 Some(Row::Message(message)) => {
3247 let actions = env.message_actions(message, window, cx);
3248 let state = env.app.read(cx);
3249 render_message_row(message, index, actions, &state.directory, cx)
3250 }
3251 Some(Row::Post(post)) => {
3252 let actions = env.post_actions(post, window, cx);
3253 let state = env.app.read(cx);
3254 render_post(post, index, actions, &state.directory, cx)
3255 }
3256 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
3257 Some(Row::LoadOlder) => {
3258 let view = env.view.clone();
3259 cx.defer(move |cx| {
3260 view.update(cx, |this, cx| this.request_older(cx)).ok();
3261 });
3262 h_flex()
3263 .w_full()
3264 .py_2()
3265 .gap(px(6.))
3266 .justify_center()
3267 .text_size(px(12.))
3268 .text_color(theme::text_muted())
3269 .child(icon(IconName::Loader, 12., theme::text_muted()))
3270 .child("Loading older messages")
3271 .into_any_element()
3272 }
3273 Some(Row::Start(start)) => {
3274 let state = env.app.read(cx);
3275 v_flex()
3276 .w_full()
3277 .items_center()
3278 .gap(px(8.))
3279 .pt(px(32.))
3280 .pb(px(16.))
3281 .child(person_avatar(
3282 &state.directory,
3283 start.user_id.as_deref(),
3284 &start.title,
3285 56.,
3286 ))
3287 .child(
3288 div()
3289 .text_size(px(16.))
3290 .font_weight(FontWeight::SEMIBOLD)
3291 .text_color(theme::text())
3292 .child(start.title.clone()),
3293 )
3294 .child(
3295 div()
3296 .text_size(px(12.))
3297 .text_color(theme::text_muted())
3298 .child("This is the beginning of the conversation"),
3299 )
3300 .into_any_element()
3301 }
3302 None => div().into_any_element(),
3303 }
3304 },
3305 )
3306 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3307 .jump_button(!in_feed)
3308 .with_bottom_fade(background);
3309
3310 root = match self.current.as_ref().filter(|_| !drafting) {
3311 Some(current) => root.child(self.render_header(current, cx)),
3312 None => root.child(self.draft.clone()),
3313 };
3314 let tab_bar = self
3315 .render_tab_bar(window, cx)
3316 .or_else(|| self.render_meeting_tab_bar(cx));
3317 root = root.children(tab_bar.filter(|_| !drafting));
3318 root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));
3319 let sync_failed = self
3320 .current
3321 .as_ref()
3322 .is_some_and(|current| current.sync.failed);
3323 if let Some(notice) = &self.notice {
3324 root = root.child(
3325 h_flex()
3326 .px(px(20.))
3327 .py_1()
3328 .gap(px(8.))
3329 .items_center()
3330 .text_xs()
3331 .bg(theme::amber().opacity(0.15))
3332 .text_color(theme::amber())
3333 .child(div().flex_1().min_w_0().child(notice.clone()))
3334 .when(sync_failed, |bar| {
3335 bar.child(
3336 Button::new("retry-fetch")
3337 .ghost()
3338 .compact()
3339 .label("Retry")
3340 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
3341 )
3342 }),
3343 );
3344 }
3345 let recap_active = self.recap_active();
3346 let empty_channel = in_feed && self.rows.borrow().is_empty();
3347 let new_post = self.render_new_post(window, cx);
3348 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
3349 let draft = self.draft.read(cx);
3350 let group_name = draft.group_name(cx);
3351 draft.render_empty(&self.app.read(cx).directory, &group_name)
3352 } else if self.shared_active() {
3353 self.render_shared(cx)
3354 } else if self.recap_active() {
3355 self.render_recap(cx)
3356 } else if empty_channel {
3357 div()
3358 .size_full()
3359 .flex()
3360 .items_center()
3361 .justify_center()
3362 .text_size(px(13.))
3363 .text_color(theme::text_muted())
3364 .child("No posts in this channel yet")
3365 .into_any_element()
3366 } else {
3367 scroller.into_any_element()
3368 };
3369 root.child(
3370 v_flex()
3371 .relative()
3372 .flex_1()
3373 .min_h_0()
3374 .children(new_post)
3375 .child(
3376 div()
3377 .relative()
3378 .flex_1()
3379 .min_h_0()
3380 .child(record_bounds(&self.timeline_bounds))
3381 .on_scroll_wheel(
3382 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
3383 )
3384 .child(body),
3385 )
3386 .children(self.render_draft_error(cx))
3387 .when(!in_feed && !recap_active, |column| {
3388 column
3389 .child(self.render_typing_line(cx))
3390 .children(self.render_proposal_card(cx))
3391 .child(self.composer.clone())
3392 })
3393 .child(self.render_drop_overlay(cx)),
3394 )
3395 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3396 if this.reaction_details.is_some() {
3397 this.close_reaction_details(cx);
3398 cx.stop_propagation();
3399 }
3400 }))
3401 .on_action(cx.listener(|this, _: &Escape, window, cx| {
3402 if this.draft_active {
3403 if this.draft.read(cx).has_focus(window, cx) {
3404 this.draft.update(cx, |draft, cx| draft.escape(cx));
3405 }
3406 } else if !this.on_escape(window, cx) {
3407 cx.propagate();
3408 }
3409 }))
3410 .into_any_element()
3411 }
3412}
3413
3414fn typing_dots() -> impl IntoElement {
3415 h_flex()
3416 .gap(px(3.))
3417 .flex_none()
3418 .children((0..TYPING_DOT_COUNT).map(|index| {
3419 let phase_offset = index as f32 / TYPING_DOT_COUNT as f32;
3420 div()
3421 .size(px(TYPING_DOT_SIZE))
3422 .rounded_full()
3423 .bg(theme::text_muted())
3424 .with_animation(
3425 ElementId::NamedInteger("typing-dot".into(), index as u64),
3426 Animation::new(TYPING_PULSE_PERIOD).repeat(),
3427 move |dot, delta| {
3428 let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs();
3429 dot.opacity(0.3 + 0.7 * wave)
3430 },
3431 )
3432 }))
3433}
3434
3435fn progress_bar() -> impl IntoElement {
3436 div()
3437 .absolute()
3438 .left_0()
3439 .right_0()
3440 .bottom(px(-1.))
3441 .h(px(2.))
3442 .overflow_hidden()
3443 .bg(theme::border())
3444 .child(
3445 div()
3446 .absolute()
3447 .top_0()
3448 .h_full()
3449 .w(relative(PROGRESS_BAR_WIDTH))
3450 .bg(theme::own_read())
3451 .with_animation(
3452 "sync-progress",
3453 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
3454 |bar, delta| {
3455 let travel = 1. + PROGRESS_BAR_WIDTH;
3456 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
3457 bar.left(relative(
3458 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
3459 ))
3460 },
3461 ),
3462 )
3463}
3464
3465#[cfg(test)]
3466mod tests {
3467 use std::sync::Arc;
3468
3469 use super::{DropTarget, drop_overlay_text};
3470
3471 use gpui_kit::test::TestWindowExt as _;
3472 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
3473 use store::Store;
3474
3475 use super::ConversationView;
3476 use crate::app_state::{AppState, Mode, Selection};
3477
3478 #[test]
3479 fn chat_overlay_names_the_chat_and_the_onedrive() {
3480 assert_eq!(
3481 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
3482 (
3483 "Drop to attach to Mara Lin".to_owned(),
3484 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
3485 )
3486 );
3487 }
3488
3489 #[test]
3490 fn channel_overlay_points_to_the_channel_files() {
3491 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
3492 assert_eq!(
3493 detail,
3494 "1 file. Images go into the message, other files to the channel's Files."
3495 );
3496 }
3497
3498 #[test]
3499 fn new_chat_overlay_says_files_wait_for_the_chat() {
3500 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
3501 assert_eq!(heading, "Drop to attach to the new chat");
3502 assert_eq!(
3503 detail,
3504 "2 files. Images go into the message. Files can be added once the chat exists."
3505 );
3506 }
3507
3508 #[gpui_kit::test]
3509 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
3510 cx.update(gpui_kit::init);
3511 let store = Arc::new(Store::open_in_memory().unwrap());
3512 crate::demo::seed(&store);
3513 let mode = Mode {
3514 demo: true,
3515 read_only: false,
3516 demo_sync: None,
3517 };
3518 let (handle, app, _view) = cx.update(|cx| {
3519 let app = cx.new(|_| {
3520 let mut state = AppState::new(store, mode);
3521 crate::demo::seed_directory(&mut state);
3522 state.selection = Some(crate::demo::first_selection());
3523 state
3524 });
3525 let shared = app.clone();
3526 let (handle, view) =
3527 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3528 cx.new(|cx| ConversationView::new(shared, window, cx))
3529 })
3530 .unwrap();
3531 (handle, app, view)
3532 });
3533 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
3534 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
3535 cx.update_window(handle, move |_, window, cx| {
3536 run(window, cx);
3537 window.render_frame(cx);
3538 })
3539 .unwrap();
3540 };
3541 step(cx, |window, cx| window.render_frame(cx));
3542 step(cx, |window, cx| window.input("lea", cx));
3543 step(cx, |window, cx| window.press("enter", cx));
3544 step(cx, |window, cx| window.press("enter", cx));
3545 step(cx, |window, cx| window.input("Hello Lea", cx));
3546 step(cx, |window, cx| window.press("enter", cx));
3547 cx.update(|cx| {
3548 let state = app.read(cx);
3549 assert!(!state.new_chat);
3550 assert_eq!(
3551 state.selection,
3552 Some(Selection::Chat("demo-chat-new-1".to_owned()))
3553 );
3554 let chat = state
3555 .sidebar
3556 .chats
3557 .iter()
3558 .find(|chat| chat.id == "demo-chat-new-1")
3559 .expect("new chat in the sidebar");
3560 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
3561 });
3562 }
3563
3564 #[gpui_kit::test]
3565 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
3566 cx.update(gpui_kit::init);
3567 let store = Arc::new(Store::open_in_memory().unwrap());
3568 crate::demo::seed(&store);
3569 let mode = Mode {
3570 demo: true,
3571 read_only: false,
3572 demo_sync: None,
3573 };
3574 let (handle, app) = cx.update(|cx| {
3575 let app = cx.new(|_| {
3576 let mut state = AppState::new(store, mode);
3577 crate::demo::seed_directory(&mut state);
3578 state.selection = Some(crate::demo::first_selection());
3579 state
3580 });
3581 let shared = app.clone();
3582 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
3583 cx.new(|cx| ConversationView::new(shared, window, cx))
3584 })
3585 .unwrap();
3586 (handle, app)
3587 });
3588 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
3589 cx.update_window(handle, |_, window, cx| {
3590 window.render_frame(cx);
3591 window.press("escape", cx);
3592 window.render_frame(cx);
3593 window.press("escape", cx);
3594 window.render_frame(cx);
3595 })
3596 .unwrap();
3597 cx.update(|cx| {
3598 let state = app.read(cx);
3599 assert!(!state.new_chat);
3600 assert_eq!(state.selection, Some(crate::demo::first_selection()));
3601 });
3602 }
3603}