BlueGit

ict rusty-teams

Files

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

conversation.rs

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