BlueGit

ict rusty-teams

Files

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

conversation.rs

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