BlueGit

ict rusty-teams

Files

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

conversation.rs

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