BlueGit

ict rusty-teams

Files

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

conversation.rs

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