BlueGit

ict rusty-teams

Files

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

conversation.rs

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