BlueGit

ict rusty-teams

Files

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

conversation.rs

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