BlueGit

ict rusty-teams

Files

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

conversation.rs

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