BlueGit

ict rusty-teams

Files

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

conversation.rs

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