BlueGit

ict rusty-teams

Files

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

conversation.rs

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