BlueGit

ict rusty-teams

Files

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

conversation.rs

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