BlueGit

ict rusty-teams

Files

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

conversation.rs

conversation.rs 163.4 KiB Download Raw
1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
5use std::time::{Duration, Instant};
6
7use chrono::{DateTime, Local, Offset, Utc};
8use gpui_kit::assets::IconName;
9use gpui_kit::component::{
10 button::{Button, ButtonVariants as _},
11 h_flex,
12 input::{Escape, InputState},
13 message_scroller::{MessageScroller, MessageScrollerState},
14 tooltip::Tooltip,
15 v_flex,
16};
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id};
20use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, is_notes_chat, without_islands,
22};
23
24mod channel_details;
25mod chat_header_actions;
26mod copilot;
27pub use channel_details::{
28 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
29 CHANNEL_DETAILS_TAG,
30};
31mod deletes;
32mod detached;
33mod feed;
34mod forward_select;
35#[cfg(test)]
36pub use forward_select::{
37 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
38};
39mod jump;
40mod notes_space;
41mod pins;
42mod proposal;
43mod recap;
44mod receipt_fade;
45mod render_env;
46mod scheduled;
47mod shared;
48
49use super::add_people_dialog::open_add_people;
50use super::attachments::FileActions;
51use super::avatar::{
52 bot_tile, member_stack, person_avatar, spec_avatar, team_avatar, with_presence,
53};
54use super::call_controls::header_call_controls;
55use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
56use super::chat_members::members_popover;
57use super::chat_pop_out;
58use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
59use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
60use super::group_name::{GroupNameSlot, group_name_button};
61use super::message_actions::{Action, DelegateEntry, MessageMenu};
62use super::message_row::{
63 AVATAR_GAP, AVATAR_SIZE, JUMP_HIGHLIGHT_PERIOD, render_message_row, render_skeleton_row,
64};
65use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
66use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
67use super::post_card::render_post;
68use super::profile_card::opens_profile;
69use super::reaction_picker::{PickHandler, ReactionPicker};
70use super::reaction_pills::{ReactionControls, ReactionPopover};
71use super::scroll_edge::edge_divider;
72use super::toolbar_placement::{TimelineBounds, record_bounds};
73use super::widgets::{icon, symbol};
74use crate::agents::{AgentRun, StartRequest};
75use crate::app_state::{AppEvent, AppState, Selection, selection_title};
76use crate::backend::Engine;
77use crate::card_state::CardScope;
78use crate::channel_files::DownloadSource;
79use crate::chat_settings_actions::shown_receipt;
80use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
81use crate::demo_library::DemoLibrary;
82use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
83use crate::emoji;
84use crate::emoticons;
85use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
86use crate::notice::short_error;
87use crate::outbox::{Delivered, deliver, new_outbox_id, outbox_record, outgoing_of};
88use crate::pending_rows::pending_row;
89use crate::people::{local_names, resolve_names};
90use crate::reaction_model::UNKNOWN_REACTOR;
91use crate::read_state::{ReadTrigger, missed_before_fetch, plan_read};
92use crate::rows::{
93 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
94 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
95 forward_sender_ids, has_own_reaction, message_draft, message_text, own_reaction_glyph,
96 place_local_rows, placeholder_rows, reaction_glyph, reply_excerpt, set_own_reaction,
97 thread_list_rows, thread_rows,
98};
99use crate::runtime;
100use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
101use crate::sidebar_model::{AvatarSpec, Face, channel_unread};
102use crate::theme;
103use crate::translation::TranslationLine;
104use crate::typing::typing_tooltip;
105use app_ui_kit::layout::{COMFY_RUNWAY_WIDTH, ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
106use detached::DetachedWindow;
107use feed::{FeedStash, subject_input};
108use mcp::ReactionProposal;
109use render_env::RenderEnv;
110use shared::SharedState;
111
112pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
113pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
114pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
115pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
116const POSTED_WITHOUT_BANNER: &str = "Posted, but Teams did not take the banner.";
117const QUIET_RETRY_DELAYS: [Duration; 3] = [
118 Duration::from_secs(2),
119 Duration::from_secs(5),
120 Duration::from_secs(15),
121];
122const HEADER_HEIGHT: f32 = 60.;
123const HEADER_PADDING: f32 = 20.;
124const HEADER_GAP: f32 = 12.;
125const HEADER_COMPACT_GAP: f32 = 4.;
126const POP_IN_BUTTON_SIZE: f32 = 32.;
127const HEADER_LEAD_SIZE: f32 = 36.;
128const TABS_INLINE_MIN_WIDTH: f32 = 560.;
129const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
130const TABS_ROW_HEIGHT: f32 = 36.;
131const CHAT_OPEN_LIMIT: usize = 60;
132const CHANNEL_OPEN_LIMIT: usize = 300;
133const GROWTH_HEADROOM: usize = 20;
134const META_USER_ID: &str = "me_user_id";
135const PENDING_KEY_PREFIX: &str = "pending-";
136const DEMO_DOWNLOAD_STEPS: u8 = 10;
137const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
138const JUMP_SCAN_LIMIT: usize = 5000;
139const JUMP_CONTEXT_MESSAGES: usize = 12;
140const PROGRESS_DELAY: Duration = Duration::from_millis(400);
141const SLOW_AFTER: Duration = Duration::from_secs(8);
142const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
143const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
144const PROGRESS_BAR_WIDTH: f32 = 0.35;
145const TYPING_LINE_HEIGHT: f32 = 22.;
146const TYPING_DOT_SIZE: f32 = 5.;
147const TYPING_DOT_COUNT: usize = 3;
148const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
149
150#[derive(Clone, Copy)]
151enum HoverSlot {
152 Row,
153 Toolbar,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
157enum ViewMode {
158 Flat,
159 ThreadList,
160 Thread(String),
161}
162
163#[derive(Default)]
164struct SyncProgress {
165 messages: bool,
166 receipts: bool,
167 empty_cache: bool,
168 newest_cached: Option<DateTime<Utc>>,
169 started_at: DateTime<Utc>,
170 shown_at: Option<Instant>,
171 slow: bool,
172 failed: bool,
173}
174
175impl SyncProgress {
176 fn running(&self) -> bool {
177 self.messages || self.receipts
178 }
179}
180
181struct Current {
182 selection: Selection,
183 title: String,
184 mode: ViewMode,
185 loaded_limit: usize,
186 loaded_count: usize,
187 has_older: bool,
188 loading_older: bool,
189 older_blocked: bool,
190 quiet_retries: usize,
191 fetched: bool,
192 first_unread: Option<String>,
193 posts_new_after: Option<DateTime<Utc>>,
194 sync: SyncProgress,
195 detached: Option<DetachedWindow>,
196 window_request: Option<String>,
197}
198
199struct ReactionDetails {
200 message_key: String,
201 anchor_glyph: String,
202 tab: Option<String>,
203}
204
205#[derive(Clone, Copy, PartialEq, Eq)]
206enum ReactionAttempt {
207 Acted,
208 Started,
209 AlreadyThere,
210 MissingMessage,
211 Blocked,
212}
213
214pub struct ConversationView {
215 app: Entity<AppState>,
216 pinned: bool,
217 popped_out: bool,
218 scroller: Entity<MessageScrollerState>,
219 composer: Entity<Composer>,
220 subject: Entity<InputState>,
221 new_post_open: bool,
222 reply_composer: Option<Entity<Composer>>,
223 reply_root: Option<String>,
224 feed_stash: Option<FeedStash>,
225 feed_rows_seen: Rc<Cell<usize>>,
226 feed_at_top: bool,
227 older_anchor: Option<String>,
228 draft: Entity<NewChatDraft>,
229 draft_active: bool,
230 draft_created: Option<(Vec<String>, String)>,
231 draft_error: Option<String>,
232 rows: Rc<RefCell<Vec<Row>>>,
233 current: Option<Current>,
234 pending: Vec<MessageRow>,
235 saving_edits: HashSet<String>,
236 pending_counter: usize,
237 pending_outgoing: HashMap<String, Outgoing>,
238 pending_reactions: PendingReactions,
239 downloads: Downloads,
240 hovered_message: Option<String>,
241 toolbar_hovered: Option<String>,
242 toolbar_opened: Option<String>,
243 timeline_bounds: TimelineBounds,
244 header_width: Rc<Cell<f32>>,
245 toolbar_pinned: Option<String>,
246 toolbar_suppressed: Option<String>,
247 recent: Entity<emoji::Recent>,
248 picker: Entity<ReactionPicker>,
249 reaction_details: Option<ReactionDetails>,
250 highlighted_message: Option<String>,
251 fetched_jump: Option<String>,
252 loading_post: Option<String>,
253 pin_index: usize,
254 channel_details_open: bool,
255 copilot: copilot::CopilotPane,
256 pinned_posts_expanded: bool,
257 channel_details_scroll: ScrollHandle,
258 scroller_watch: Option<(EntityId, Subscription)>,
259 pin_previews: HashMap<String, pins::PinPreview>,
260 pin_fetches: HashSet<String>,
261 notice: Option<String>,
262 scheduled_failure: Option<scheduled::ScheduledFailure>,
263 scheduled_in_flight: HashSet<String>,
264 drag_file_count: usize,
265 sync_generation: u64,
266 window_active: bool,
267 pane: ChannelPane,
268 recap: recap::RecapState,
269 recap_search: Entity<InputState>,
270 channel_tabs: Vec<ChannelTabRecord>,
271 tab_links: HashMap<String, String>,
272 focus_handle: FocusHandle,
273 shared: SharedState,
274 demo_library: DemoLibrary,
275 new_folder_input: Option<Entity<InputState>>,
276 agent_layouts: HashMap<String, (usize, bool)>,
277 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
278 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
279 receipt_fade: receipt_fade::ReceiptFade,
280 find_panel: Option<Entity<FindPanel>>,
281 find_subscription: Option<Subscription>,
282 group_name: GroupNameSlot,
283 _subscriptions: Vec<Subscription>,
284}
285
286fn open_limit(selection: &Selection) -> usize {
287 match selection {
288 Selection::Chat(_) => CHAT_OPEN_LIMIT,
289 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
290 }
291}
292
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294enum DropTarget {
295 Chat,
296 Channel,
297 Library,
298 NewChat,
299}
300
301fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
302 let files = if count == 1 {
303 "1 file".to_owned()
304 } else {
305 format!("{count} files")
306 };
307 match target {
308 DropTarget::Chat => (
309 format!("Drop to attach to {title}"),
310 format!("{files}. Images go into the message, other files to your OneDrive."),
311 ),
312 DropTarget::Channel => (
313 format!("Drop to attach to {title}"),
314 format!("{files}. Images go into the message, other files to the channel's Files."),
315 ),
316 DropTarget::Library => (
317 format!("Drop to upload to {title}"),
318 format!("{files}. Files go into the folder you have open."),
319 ),
320 DropTarget::NewChat => (
321 "Drop to attach to the new chat".to_owned(),
322 format!(
323 "{files}. Images go into the message. Files can be added once the chat exists."
324 ),
325 ),
326 }
327}
328
329fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool {
330 match mode {
331 ViewMode::Flat => record.target == OutboxTarget::Flat,
332 ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread),
333 ViewMode::Thread(root_id) => {
334 record.target == OutboxTarget::Thread
335 && record.thread_root_id.as_deref() == Some(root_id.as_str())
336 }
337 }
338}
339
340enum DownloadEvent {
341 Progress(u8),
342 Finished(Result<PathBuf, String>),
343}
344
345async fn save_file(
346 engine: &Engine,
347 card: &FileCard,
348 source: &DownloadSource,
349 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
350) -> Result<PathBuf, String> {
351 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
352 .map_err(|error| short_error(&error))?;
353 let write = |bytes: &[u8]| part.write(bytes);
354 let progress = |percent| {
355 let _ = events.send(DownloadEvent::Progress(percent));
356 };
357 match source {
358 DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,
359 DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,
360 }
361 .map_err(|error| short_error(&error))?;
362 part.finish().map_err(|error| short_error(&error))
363}
364
365impl ConversationView {
366 fn file_actions(
367 &self,
368 message_key: &str,
369 files: &[FileCard],
370 view: WeakEntity<Self>,
371 ) -> FileActions {
372 let conversation_id = self.conversation_id().unwrap_or_default();
373 let (key, cards) = (message_key.to_owned(), files.to_vec());
374 let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect();
375 FileActions {
376 states: self
377 .downloads
378 .states_for(&conversation_id, message_key, &open_urls),
379 activate: Rc::new(move |index, cx| {
380 let Some(card) = cards.get(index).cloned() else {
381 return;
382 };
383 let key = key.clone();
384 let conversation_id = conversation_id.clone();
385 view.update(cx, |this, cx| {
386 this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)
387 })
388 .ok();
389 }),
390 }
391 }
392
393 fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {
394 let Some(current) = self.current.as_ref() else {
395 return;
396 };
397 let now = Local::now();
398 let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());
399 let Some(index) = position_of(&items, message_key, url) else {
400 return;
401 };
402 let request = ViewerRequest {
403 conversation_id: current.selection.conversation_id().to_owned(),
404 conversation_title: selection_title(&self.app.read(cx).sidebar, &current.selection),
405 items,
406 index,
407 };
408 self.app
409 .update(cx, |state, cx| state.request_image_viewer(request, cx));
410 }
411
412 fn activate_file(
413 &mut self,
414 conversation_id: &str,
415 message_key: &str,
416 card: FileCard,
417 source: DownloadSource,
418 cx: &mut Context<Self>,
419 ) {
420 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
421 match downloads::click_action(self.downloads.state(&key)) {
422 ClickAction::Ignore => {}
423 ClickAction::Start => self.start_download(key, card, source, cx),
424 ClickAction::Reveal(path) => {
425 let folder = path
426 .parent()
427 .map(Path::to_path_buf)
428 .unwrap_or_else(downloads::downloads_directory);
429 match downloads::reveal_target(&path, path.exists(), folder) {
430 RevealTarget::File(path) => downloads::reveal_in_file_manager(&path),
431 RevealTarget::Folder(folder) => cx.open_with_system(&folder),
432 }
433 }
434 }
435 }
436
437 fn start_download(
438 &mut self,
439 key: DownloadKey,
440 card: FileCard,
441 source: DownloadSource,
442 cx: &mut Context<Self>,
443 ) {
444 if !self.downloads.begin(&key) {
445 return;
446 }
447 cx.notify();
448 let state = self.app.read(cx);
449 let (demo, engine) = (state.mode.demo, state.engine.clone());
450 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>();
451 if demo {
452 cx.spawn(async move |this, cx| {
453 for step in 1..=DEMO_DOWNLOAD_STEPS {
454 cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await;
455 let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8;
456 let progressed = this.update(cx, |this, cx| {
457 this.downloads.set_progress(&key, percent);
458 cx.notify();
459 });
460 if progressed.is_err() {
461 return;
462 }
463 }
464 let outcome =
465 downloads::write_demo_file(&card.name).map_err(|error| short_error(&error));
466 this.update(cx, |this, cx| {
467 this.downloads.finish(&key, outcome);
468 cx.notify();
469 })
470 .ok();
471 })
472 .detach();
473 return;
474 }
475 let Some(engine) = engine else {
476 self.downloads.finish(&key, Err("not connected".to_owned()));
477 return;
478 };
479 drop(runtime::spawn(async move {
480 let outcome = save_file(&engine, &card, &source, &sender).await;
481 let _ = sender.send(DownloadEvent::Finished(outcome));
482 }));
483 cx.spawn(async move |this, cx| {
484 while let Some(event) = receiver.recv().await {
485 let updated = this.update(cx, |this, cx| {
486 match event {
487 DownloadEvent::Progress(percent) => {
488 this.downloads.set_progress(&key, percent)
489 }
490 DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome),
491 }
492 cx.notify();
493 });
494 if updated.is_err() {
495 break;
496 }
497 }
498 })
499 .detach();
500 }
501
502 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
503 Self::build(app, None, window, cx)
504 }
505
506 pub fn pinned_to(
507 app: Entity<AppState>,
508 selection: Selection,
509 window: &mut Window,
510 cx: &mut Context<Self>,
511 ) -> Self {
512 Self::build(app, Some(selection), window, cx)
513 }
514
515 pub fn popped_out(
516 app: Entity<AppState>,
517 selection: Selection,
518 window: &mut Window,
519 cx: &mut Context<Self>,
520 ) -> Self {
521 let mut view = Self::build(app, Some(selection), window, cx);
522 view.popped_out = true;
523 view
524 }
525
526 fn build(
527 app: Entity<AppState>,
528 pinned: Option<Selection>,
529 window: &mut Window,
530 cx: &mut Context<Self>,
531 ) -> Self {
532 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
533 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
534 let subject = subject_input(window, cx);
535 let recap_search = recap::search_input(window, cx);
536 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
537 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
538 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
539 let mut subscriptions = vec![
540 cx.subscribe_in(&app, window, Self::on_app_event),
541 cx.observe(&app, |_, _, cx| cx.notify()),
542 cx.subscribe_in(&composer, window, Self::on_composer_event),
543 cx.subscribe_in(&draft, window, Self::on_draft_event),
544 cx.subscribe_in(&subject, window, Self::on_subject_event),
545 cx.subscribe_in(&recap_search, window, Self::on_recap_search_event),
546 cx.observe_window_activation(window, Self::on_window_activation),
547 cx.on_app_quit(|this, cx| {
548 this.composer
549 .update(cx, |composer, cx| composer.save_draft_now(cx));
550 async {}
551 }),
552 cx.observe_keystrokes(|this, event, _, cx| {
553 if event.keystroke.key == "escape" {
554 this.close_reaction_details(cx);
555 }
556 }),
557 ];
558 if let Some(runs) = crate::agents::runs_handle(cx) {
559 subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx)));
560 }
561 if let Some(api) = crate::agent_api::handle(cx) {
562 subscriptions.push(cx.observe(&api, |this, _, cx| this.sync_reaction_pills(cx)));
563 }
564 let mut view = ConversationView {
565 group_name: GroupNameSlot::default(),
566 app,
567 pinned: pinned.is_some(),
568 popped_out: false,
569 scroller,
570 composer,
571 subject,
572 new_post_open: false,
573 reply_composer: None,
574 reply_root: None,
575 feed_stash: None,
576 feed_rows_seen: Rc::new(Cell::new(usize::MAX)),
577 feed_at_top: true,
578 older_anchor: None,
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 let older_anchor = self.older_anchor.take().and_then(|key| {
1861 let top_was_loader = matches!(old_rows.first(), Some(Row::LoadOlder));
1862 let index = self.rows.borrow().iter().position(|row| row.key() == key)?;
1863 (top_was_loader && !in_feed).then_some(index)
1864 });
1865 if reset {
1866 let marker_index = self
1867 .rows
1868 .borrow()
1869 .iter()
1870 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1871 self.feed_at_top = true;
1872 self.scroller.update(cx, |scroller, cx| {
1873 scroller.reset(new_len, cx);
1874 if in_feed {
1875 scroller.scroll_to_item(0, cx);
1876 return;
1877 }
1878 match marker_index {
1879 Some(index) if !scroller.scroll_to_item(index, cx) => {
1880 scroller.scroll_to_end(cx)
1881 }
1882 Some(_) => {}
1883 None => scroller.scroll_to_end(cx),
1884 }
1885 });
1886 cx.notify();
1887 return;
1888 }
1889 let (splice, changed) = {
1890 let new_rows = self.rows.borrow();
1891 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
1892 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
1893 (
1894 diff_keys(&old_keys, &new_keys),
1895 changed_indices(&old_rows, &new_rows),
1896 )
1897 };
1898 let top_changed = splice
1899 .as_ref()
1900 .is_some_and(|splice| splice.range.start == 0);
1901 let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed));
1902 self.scroller.update(cx, |scroller, cx| {
1903 if let Some(splice) = splice
1904 && !scroller.splice(splice.range, splice.count, cx)
1905 {
1906 scroller.reset(new_len, cx);
1907 }
1908 if keep_top {
1909 scroller.scroll_to_item(0, cx);
1910 } else if let Some(index) = older_anchor {
1911 scroller.scroll_to_item(index, cx);
1912 }
1913 for index in changed {
1914 scroller.remeasure_items(index..index + 1, cx);
1915 }
1916 });
1917 cx.notify();
1918 }
1919
1920 fn start_fetch(&mut self, cx: &mut Context<Self>) {
1921 let state = self.app.read(cx);
1922 let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
1923 if engine.is_none() && demo_sync.is_none() {
1924 return;
1925 }
1926 let Some(current) = self.current.as_mut() else {
1927 return;
1928 };
1929 if current.fetched {
1930 return;
1931 }
1932 current.fetched = true;
1933 let is_chat = matches!(current.selection, Selection::Chat(_));
1934 let newest_cached = self
1935 .rows
1936 .borrow()
1937 .iter()
1938 .flat_map(Row::messages)
1939 .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX))
1940 .map(|message| message.created_at)
1941 .max();
1942 let current = self.current.as_mut().expect("checked above");
1943 if current.sync.failed {
1944 self.notice = None;
1945 }
1946 current.sync = SyncProgress {
1947 messages: true,
1948 receipts: is_chat,
1949 empty_cache: newest_cached.is_none(),
1950 newest_cached,
1951 started_at: Utc::now(),
1952 ..SyncProgress::default()
1953 };
1954 self.sync_generation += 1;
1955 let generation = self.sync_generation;
1956 let conversation_id = current.selection.conversation_id().to_owned();
1957 match (engine, demo_sync) {
1958 (Some(engine), _) => {
1959 let receiver =
1960 runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
1961 cx.spawn(async move |this, cx| {
1962 let result = receiver.await;
1963 this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
1964 .ok();
1965 })
1966 .detach();
1967 }
1968 (None, Some(delay)) => self.simulate_sync(generation, delay, cx),
1969 (None, None) => {}
1970 }
1971 self.schedule_progress(generation, cx);
1972 self.rebuild(false, cx);
1973 self.mark_read(ReadTrigger::Incoming, cx);
1974 self.refresh_receipts(generation, cx);
1975 }
1976
1977 fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
1978 cx.spawn(async move |this, cx| {
1979 cx.background_executor().timer(delay).await;
1980 this.update(cx, |this, cx| {
1981 if let Some(sync) = this.sync_of(generation) {
1982 sync.receipts = false;
1983 }
1984 this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
1985 })
1986 .ok();
1987 })
1988 .detach();
1989 }
1990
1991 fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
1992 if generation != self.sync_generation {
1993 return None;
1994 }
1995 self.current.as_mut().map(|current| &mut current.sync)
1996 }
1997
1998 fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1999 cx.spawn(async move |this, cx| {
2000 let stages = [
2001 (PROGRESS_DELAY, Duration::ZERO),
2002 (SLOW_AFTER, PROGRESS_DELAY),
2003 ];
2004 for (stage, (at, previous)) in stages.into_iter().enumerate() {
2005 cx.background_executor().timer(at - previous).await;
2006 let running = this
2007 .update(cx, |this, cx| this.advance_progress(generation, stage, cx))
2008 .unwrap_or(false);
2009 if !running {
2010 return;
2011 }
2012 }
2013 })
2014 .detach();
2015 }
2016
2017 fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
2018 let Some(sync) = self.sync_of(generation) else {
2019 return false;
2020 };
2021 if !sync.running() || !sync.empty_cache {
2022 return false;
2023 }
2024 match stage {
2025 0 => sync.shown_at = Some(Instant::now()),
2026 _ => sync.slow = true,
2027 }
2028 cx.notify();
2029 true
2030 }
2031
2032 fn finish_fetch(
2033 &mut self,
2034 generation: u64,
2035 result: Result<
2036 teams_core::Result<teams_core::Delta>,
2037 tokio::sync::oneshot::error::RecvError,
2038 >,
2039 cx: &mut Context<Self>,
2040 ) {
2041 let Some(sync) = self.sync_of(generation) else {
2042 return;
2043 };
2044 sync.messages = false;
2045 let (newest_cached, started_at) = (sync.newest_cached, sync.started_at);
2046 match result {
2047 Ok(Ok(_)) => {
2048 if let Some(current) = self.current.as_mut() {
2049 current.quiet_retries = 0;
2050 }
2051 self.mark_fetched_new(newest_cached, started_at, cx)
2052 }
2053 Ok(Err(error)) => self.fail_sync(generation, short_error(&error), cx),
2054 Err(error) => self.fail_sync(generation, short_error(&error), cx),
2055 }
2056 self.rebuild(false, cx);
2057 self.settle_progress(generation, cx);
2058 }
2059
2060 fn fail_sync(&mut self, generation: u64, error: String, cx: &mut Context<Self>) {
2061 let quiet_retry = self.current.as_mut().and_then(|current| {
2062 let delay = QUIET_RETRY_DELAYS.get(current.quiet_retries).copied()?;
2063 current.quiet_retries += 1;
2064 Some(delay)
2065 });
2066 if let Some(delay) = quiet_retry {
2067 cx.spawn(async move |this, cx| {
2068 cx.background_executor().timer(delay).await;
2069 this.update(cx, |this, cx| {
2070 if this.sync_generation == generation {
2071 this.retry_fetch(cx);
2072 }
2073 })
2074 .ok();
2075 })
2076 .detach();
2077 return;
2078 }
2079 if let Some(sync) = self.sync_of(generation) {
2080 sync.failed = true;
2081 sync.receipts = false;
2082 }
2083 self.notice = Some(format!("Could not refresh: {error}"));
2084 }
2085
2086 fn mark_fetched_new(
2087 &mut self,
2088 newest_cached: Option<DateTime<Utc>>,
2089 started_at: DateTime<Utc>,
2090 cx: &mut Context<Self>,
2091 ) {
2092 let Some(newest_cached) = newest_cached else {
2093 return;
2094 };
2095 let Some(my_user_id) = self.row_context(cx).my_user_id else {
2096 return;
2097 };
2098 let store = self.app.read(cx).store.clone();
2099 let Some(current) = self.current.as_mut() else {
2100 return;
2101 };
2102 if current.first_unread.is_some() || current.mode != ViewMode::Flat {
2103 return;
2104 }
2105 let limit = current
2106 .loaded_limit
2107 .max(current.loaded_count + GROWTH_HEADROOM);
2108 current.first_unread = store
2109 .messages(current.selection.conversation_id(), None, limit)
2110 .unwrap_or_default()
2111 .into_iter()
2112 .find(|record| {
2113 missed_before_fetch(record.created_at, newest_cached, started_at)
2114 && record.sender_id.as_ref() != Some(&my_user_id)
2115 })
2116 .map(|record| record.message_id);
2117 }
2118
2119 fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
2120 let Some(sync) = self.sync_of(generation) else {
2121 return;
2122 };
2123 if sync.running() {
2124 return;
2125 }
2126 let remaining = sync
2127 .shown_at
2128 .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
2129 .unwrap_or_default();
2130 if remaining.is_zero() {
2131 sync.shown_at = None;
2132 sync.slow = false;
2133 cx.notify();
2134 return;
2135 }
2136 cx.spawn(async move |this, cx| {
2137 cx.background_executor().timer(remaining).await;
2138 this.update(cx, |this, cx| {
2139 if let Some(sync) = this.sync_of(generation) {
2140 sync.shown_at = None;
2141 sync.slow = false;
2142 cx.notify();
2143 }
2144 })
2145 .ok();
2146 })
2147 .detach();
2148 }
2149
2150 fn retry_fetch(&mut self, cx: &mut Context<Self>) {
2151 if let Some(current) = self.current.as_mut() {
2152 current.fetched = false;
2153 }
2154 self.start_fetch(cx);
2155 }
2156
2157 fn receipts(
2158 &self,
2159 records: &[MessageRecord],
2160 cx: &App,
2161 ) -> (HashMap<String, Receipt>, HashMap<String, String>) {
2162 let settings = self.app.read(cx).account_chat_settings();
2163 let (mut receipts, mut labels) = self.raw_receipts(records, cx);
2164 for receipt in receipts.values_mut() {
2165 *receipt = shown_receipt(&settings, *receipt);
2166 }
2167 labels.retain(|key, _| receipts.get(key).is_some_and(|receipt| *receipt != Receipt::Hidden));
2168 (receipts, labels)
2169 }
2170
2171 fn raw_receipts(
2172 &self,
2173 records: &[MessageRecord],
2174 cx: &App,
2175 ) -> (HashMap<String, Receipt>, HashMap<String, String>) {
2176 let state = self.app.read(cx);
2177 if state.mode.demo {
2178 let read_ids = crate::demo::read_message_ids(records);
2179 let receipts: HashMap<String, Receipt> = records
2180 .iter()
2181 .map(|record| {
2182 let receipt = if read_ids.contains(&record.message_id) {
2183 Receipt::Read
2184 } else {
2185 Receipt::Sent
2186 };
2187 (record.message_id.clone(), receipt)
2188 })
2189 .collect();
2190 let labels = receipts
2191 .iter()
2192 .map(|(key, receipt)| {
2193 let label = if *receipt == Receipt::Read { "Seen" } else { "Sent" };
2194 (key.clone(), label.to_owned())
2195 })
2196 .collect();
2197 return (receipts, labels);
2198 }
2199 let Some(engine) = state.engine.as_ref() else {
2200 return (HashMap::new(), HashMap::new());
2201 };
2202 let mut receipts = HashMap::new();
2203 let mut labels = HashMap::new();
2204 for record in records {
2205 let receipt_state = engine.receipt_state_for(record);
2206 if let Some(label) = crate::rows::receipt_label(&receipt_state) {
2207 labels.insert(record.message_id.clone(), label);
2208 }
2209 let receipt = match receipt_state {
2210 teams_core::ReceiptState::Read { .. } => Receipt::Read,
2211 teams_core::ReceiptState::Sent => Receipt::Sent,
2212 teams_core::ReceiptState::Unknown => Receipt::Hidden,
2213 };
2214 receipts.insert(record.message_id.clone(), receipt);
2215 }
2216 (receipts, labels)
2217 }
2218
2219 fn track_receipt_fades(&mut self, receipts: &mut HashMap<String, Receipt>) -> bool {
2220 let Some(current) = self.current.as_ref() else {
2221 return false;
2222 };
2223 let settled = !current.sync.receipts;
2224 let conversation_id = current.selection.conversation_id().to_owned();
2225 self.receipt_fade
2226 .apply(&conversation_id, settled, receipts, Instant::now())
2227 }
2228
2229 fn schedule_fade_end(&mut self, cx: &mut Context<Self>) {
2230 cx.spawn(async move |this, cx| {
2231 cx.background_executor()
2232 .timer(receipt_fade::RECEIPT_FADE)
2233 .await;
2234 this.update(cx, |this, cx| this.rebuild(false, cx)).ok();
2235 })
2236 .detach();
2237 }
2238
2239 fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
2240 let state = self.app.read(cx);
2241 let (Some(engine), Some(Selection::Chat(chat_id))) = (
2242 state.engine.clone(),
2243 self.current.as_ref().map(|c| c.selection.clone()),
2244 ) else {
2245 return;
2246 };
2247 let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
2248 cx.spawn(async move |this, cx| {
2249 receiver.await.ok();
2250 this.update(cx, |this, cx| {
2251 let Some(sync) = this.sync_of(generation) else {
2252 return;
2253 };
2254 sync.receipts = false;
2255 this.rebuild(false, cx);
2256 this.settle_progress(generation, cx);
2257 })
2258 .ok();
2259 })
2260 .detach();
2261 }
2262
2263 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
2264 if self.draft_active {
2265 return;
2266 }
2267 let state = self.app.read(cx);
2268 let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else {
2269 return;
2270 };
2271 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
2272 return;
2273 }
2274 let unread = match &selection {
2275 Selection::Chat(chat_id) => {
2276 state
2277 .sidebar
2278 .chats
2279 .iter()
2280 .any(|chat| &chat.id == chat_id && chat.unread)
2281 && !state.keeps_unread(chat_id)
2282 }
2283 Selection::Channel(channel_id) => channel_unread(&state.sidebar, channel_id),
2284 };
2285 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
2286 return;
2287 };
2288 self.app.update(cx, |state, cx| match &selection {
2289 Selection::Chat(chat_id) => {
2290 state.ack_urgent_messages(chat_id, cx);
2291 state.mark_chat_read(chat_id, cx)
2292 }
2293 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
2294 });
2295 if plan.clear_divider
2296 && let Some(current) = self.current.as_mut()
2297 && current.first_unread.take().is_some()
2298 {
2299 self.rebuild(false, cx);
2300 }
2301 }
2302
2303 fn request_older(&mut self, cx: &mut Context<Self>) {
2304 if self.is_detached() {
2305 return self.request_window_page(WindowDirection::Backward, cx);
2306 }
2307 let Some(engine) = self.app.read(cx).engine.clone() else {
2308 return;
2309 };
2310 let Some(current) = self.current.as_mut() else {
2311 return;
2312 };
2313 if current.loading_older || current.older_blocked || !current.has_older {
2314 return;
2315 }
2316 current.loading_older = true;
2317 let conversation_id = current.selection.conversation_id().to_owned();
2318 let task_id = conversation_id.clone();
2319 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
2320 cx.spawn(async move |this, cx| {
2321 let result = receiver.await;
2322 this.update(cx, |this, cx| {
2323 this.finish_older(&conversation_id, result, cx)
2324 })
2325 .ok();
2326 })
2327 .detach();
2328 }
2329
2330 fn finish_older(
2331 &mut self,
2332 conversation_id: &str,
2333 result: Result<
2334 teams_core::Result<Vec<MessageRecord>>,
2335 tokio::sync::oneshot::error::RecvError,
2336 >,
2337 cx: &mut Context<Self>,
2338 ) {
2339 let Some(current) = self.current.as_mut() else {
2340 return;
2341 };
2342 if current.selection.conversation_id() != conversation_id {
2343 return;
2344 }
2345 current.loading_older = false;
2346 match result {
2347 Ok(Ok(records)) if !records.is_empty() => {
2348 app_base::diagnostics::record(&format!("chat: older page, {} messages", records.len()));
2349 current.loaded_limit = current.loaded_count + records.len();
2350 self.older_anchor = self
2351 .rows
2352 .borrow()
2353 .iter()
2354 .find(|row| matches!(row, Row::Message(_) | Row::Post(_)))
2355 .map(|row| row.key().to_owned());
2356 }
2357 Ok(Ok(_)) => {
2358 app_base::diagnostics::record("chat: no older messages");
2359 current.older_blocked = true;
2360 }
2361 Ok(Err(error)) => {
2362 app_base::diagnostics::record(&format!("chat: older page failed: {}", short_error(&error)));
2363 current.older_blocked = true;
2364 self.notice = Some(format!(
2365 "Could not load older messages: {}",
2366 short_error(&error)
2367 ));
2368 }
2369 Err(_) => current.older_blocked = true,
2370 }
2371 self.rebuild(false, cx);
2372 }
2373
2374 fn clear_pending(&mut self) {
2375 self.pending.clear();
2376 self.pending_outgoing.clear();
2377 }
2378
2379 fn outbox_route(&self, reply_root: Option<String>) -> (OutboxTarget, Option<String>) {
2380 if let Some(root_id) = reply_root {
2381 return (OutboxTarget::Thread, Some(root_id));
2382 }
2383 match self.current.as_ref().map(|current| &current.mode) {
2384 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
2385 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
2386 _ => (OutboxTarget::Flat, None),
2387 }
2388 }
2389
2390 fn reload_pending(&mut self, cx: &App) {
2391 self.clear_pending();
2392 let state = self.app.read(cx);
2393 if state.mode.demo || state.mode.read_only {
2394 return;
2395 }
2396 let Some(current) = self.current.as_ref() else {
2397 return;
2398 };
2399 let conversation_id = current.selection.conversation_id().to_owned();
2400 let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else {
2401 return;
2402 };
2403 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
2404 let mut pending = Vec::new();
2405 for record in records {
2406 if !shown_in_view(&current.mode, &record) {
2407 continue;
2408 }
2409 let Some(outgoing) = outgoing_of(&record) else {
2410 continue;
2411 };
2412 let delivery = match record.state {
2413 OutboxState::Sending => Delivery::Sending,
2414 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
2415 };
2416 let mut row = pending_row(
2417 record.id.clone(),
2418 conversation_id.clone(),
2419 my_user_id.clone(),
2420 record.created_at,
2421 &outgoing,
2422 delivery,
2423 );
2424 row.reply_root = record.thread_root_id.clone();
2425 pending.push((row, record.id, outgoing));
2426 }
2427 for (row, id, outgoing) in pending {
2428 self.pending.push(row);
2429 self.pending_outgoing.insert(id, outgoing);
2430 }
2431 }
2432
2433 fn discard_outbox_row(&self, id: &str, cx: &mut Context<Self>) {
2434 self.app.read(cx).store.delete_outbox(id).ok();
2435 self.app
2436 .update(cx, |state, cx| state.refresh_local_previews(cx));
2437 }
2438
2439 fn delete_pending(&mut self, key: &str, cx: &mut Context<Self>) {
2440 self.pending.retain(|row| row.key != key);
2441 self.pending_outgoing.remove(key);
2442 self.discard_outbox_row(key, cx);
2443 self.rebuild(false, cx);
2444 }
2445
2446 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2447 self.leave_detached(cx);
2448 self.send_as(new_outbox_id(), outgoing, None, window, cx);
2449 }
2450
2451 fn send_in_thread(
2452 &mut self,
2453 root_id: String,
2454 outgoing: Outgoing,
2455 window: &mut Window,
2456 cx: &mut Context<Self>,
2457 ) {
2458 self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx);
2459 }
2460
2461 fn send_as(
2462 &mut self,
2463 id: String,
2464 outgoing: Outgoing,
2465 reply_root: Option<String>,
2466 window: &mut Window,
2467 cx: &mut Context<Self>,
2468 ) {
2469 let state = self.app.read(cx);
2470 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2471 let Some(current) = self.current.as_ref() else {
2472 return;
2473 };
2474 if mode.read_only || mode.demo {
2475 self.restore_unsent(
2476 "Read-only mode: nothing was sent",
2477 &outgoing,
2478 reply_root.as_deref(),
2479 window,
2480 cx,
2481 );
2482 return;
2483 }
2484 let Some(engine) = engine else {
2485 self.discard_outbox_row(&id, cx);
2486 self.restore_unsent(
2487 "Not connected yet: nothing was sent",
2488 &outgoing,
2489 reply_root.as_deref(),
2490 window,
2491 cx,
2492 );
2493 return;
2494 };
2495 let conversation_id = current.selection.conversation_id().to_owned();
2496 let (target, thread_root_id) = self.outbox_route(reply_root);
2497 let created_at = Utc::now();
2498 self.push_pending(
2499 id.clone(),
2500 created_at,
2501 &outgoing,
2502 thread_root_id.clone(),
2503 cx,
2504 );
2505 if let Some(record) = outbox_record(
2506 &id,
2507 &conversation_id,
2508 target,
2509 thread_root_id.as_deref(),
2510 &outgoing,
2511 created_at,
2512 ) {
2513 store.put_outbox(&record).ok();
2514 }
2515 self.notice = None;
2516 self.rebuild(false, cx);
2517 if self.in_feed() {
2518 self.scroller
2519 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2520 } else {
2521 self.scroller
2522 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
2523 }
2524
2525 let receiver = runtime::spawn(async move {
2526 deliver(
2527 &engine,
2528 &conversation_id,
2529 target,
2530 thread_root_id.as_deref(),
2531 &outgoing,
2532 )
2533 .await
2534 });
2535 cx.spawn_in(window, async move |this, cx| {
2536 let result = receiver.await;
2537 this.update(cx, |this, cx| this.finish_send(&id, result, cx))
2538 .ok();
2539 })
2540 .detach();
2541 }
2542
2543 fn restore_unsent(
2544 &mut self,
2545 message: &str,
2546 outgoing: &Outgoing,
2547 reply_root: Option<&str>,
2548 window: &mut Window,
2549 cx: &mut Context<Self>,
2550 ) {
2551 self.notice = Some(message.to_owned());
2552 if let (Some(root_id), true) = (reply_root, self.in_feed()) {
2553 self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx);
2554 if let Some(composer) = self.reply_composer.clone() {
2555 composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2556 }
2557 } else {
2558 self.show_main_composer(cx);
2559 self.restore_subject(outgoing.subject.as_deref(), window, cx);
2560 self.composer
2561 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2562 }
2563 cx.notify();
2564 }
2565
2566 fn next_pending_key(&mut self) -> String {
2567 self.pending_counter += 1;
2568 format!("{PENDING_KEY_PREFIX}{}", self.pending_counter)
2569 }
2570
2571 fn push_pending(
2572 &mut self,
2573 key: String,
2574 created_at: DateTime<Utc>,
2575 outgoing: &Outgoing,
2576 reply_root: Option<String>,
2577 cx: &App,
2578 ) {
2579 let my_user_id = self.row_context(cx).my_user_id;
2580 let conversation_id = self
2581 .current
2582 .as_ref()
2583 .map(|current| current.selection.conversation_id().to_owned())
2584 .unwrap_or_default();
2585 let mut row = pending_row(
2586 key.clone(),
2587 conversation_id,
2588 my_user_id,
2589 created_at,
2590 outgoing,
2591 Delivery::Sending,
2592 );
2593 row.reply_root = reply_root;
2594 self.pending.push(row);
2595 self.pending_outgoing.insert(key, outgoing.clone());
2596 }
2597
2598 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2599 let (recipients, topic) = {
2600 let draft = self.draft.read(cx);
2601 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
2602 (draft.chips().to_vec(), topic)
2603 };
2604 if recipients.is_empty() {
2605 self.restore_unsent("Add at least one person first", &outgoing, None, window, cx);
2606 self.draft
2607 .update(cx, |draft, cx| draft.focus_query(window, cx));
2608 return;
2609 }
2610 if self
2611 .pending
2612 .iter()
2613 .any(|row| matches!(row.delivery, Delivery::Sending))
2614 {
2615 self.restore_unsent("Still creating the chat", &outgoing, None, window, cx);
2616 return;
2617 }
2618 let state = self.app.read(cx);
2619 let (mode, engine) = (state.mode, state.engine.clone());
2620 if mode.read_only {
2621 self.restore_unsent(
2622 "Read-only mode: nothing was sent",
2623 &outgoing,
2624 None,
2625 window,
2626 cx,
2627 );
2628 return;
2629 }
2630 if mode.demo && outgoing.has_attachments() {
2631 self.restore_unsent(
2632 "Read-only mode: nothing was sent",
2633 &outgoing,
2634 None,
2635 window,
2636 cx,
2637 );
2638 return;
2639 }
2640 if mode.demo {
2641 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
2642 return;
2643 }
2644 let Some(engine) = engine else {
2645 self.restore_unsent(
2646 "Not connected yet: nothing was sent",
2647 &outgoing,
2648 None,
2649 window,
2650 cx,
2651 );
2652 return;
2653 };
2654 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
2655 let known_chat = self
2656 .draft_created
2657 .as_ref()
2658 .filter(|(created_for, _)| *created_for == user_ids)
2659 .map(|(_, chat_id)| chat_id.clone())
2660 .or_else(|| self.draft_target_chat(cx));
2661 self.pending.clear();
2662 self.pending_outgoing.clear();
2663 self.draft_error = None;
2664 self.notice = None;
2665 let key = self.next_pending_key();
2666 self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx);
2667 self.rebuild(true, cx);
2668 let recipients_for_finish = user_ids.clone();
2669 let receiver = runtime::spawn(async move {
2670 let chat_id = match known_chat {
2671 Some(chat_id) => chat_id,
2672 None => {
2673 let created = match user_ids.as_slice() {
2674 [user_id] => engine.create_one_on_one(user_id).await,
2675 _ => engine.create_group(&user_ids, topic.as_deref()).await,
2676 };
2677 match created {
2678 Ok(chat_id) => chat_id,
2679 Err(error) => return (None, Some(short_error(&error))),
2680 }
2681 }
2682 };
2683 let sent = engine
2684 .send_message_with_extras(
2685 &chat_id,
2686 &outgoing.html(),
2687 None,
2688 &outgoing.mentions,
2689 &outgoing.extras(),
2690 )
2691 .await;
2692 if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {
2693 let _ = engine
2694 .attach_link_preview(&chat_id, &record.message_id, preview)
2695 .await;
2696 }
2697 (Some(chat_id), sent.err().map(|error| short_error(&error)))
2698 });
2699 cx.spawn_in(window, async move |this, cx| {
2700 let result = receiver.await;
2701 this.update_in(cx, |this, _, cx| {
2702 this.finish_new_chat(&key, recipients_for_finish, result, cx)
2703 })
2704 .ok();
2705 })
2706 .detach();
2707 }
2708
2709 fn finish_new_chat(
2710 &mut self,
2711 key: &str,
2712 user_ids: Vec<String>,
2713 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
2714 cx: &mut Context<Self>,
2715 ) {
2716 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
2717 return;
2718 }
2719 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
2720 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
2721 match (chat_id, error) {
2722 (Some(chat_id), None) => {
2723 self.app.update(cx, |state, cx| {
2724 state.reload_sidebar(cx);
2725 state.select(Selection::Chat(chat_id), cx);
2726 });
2727 }
2728 (created, error) => {
2729 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2730 row.delivery = Delivery::Failed(error.unwrap_or_default());
2731 }
2732 self.draft_error = Some(
2733 if created.is_some() {
2734 "Couldn't send the message."
2735 } else {
2736 "Couldn't create the chat."
2737 }
2738 .to_owned(),
2739 );
2740 self.rebuild(false, cx);
2741 }
2742 }
2743 }
2744
2745 fn send_demo_new_chat(
2746 &mut self,
2747 outgoing: &Outgoing,
2748 recipients: &[super::new_chat::Pick],
2749 topic: Option<&str>,
2750 cx: &mut Context<Self>,
2751 ) {
2752 let (store, chats) = {
2753 let state = self.app.read(cx);
2754 (state.store.clone(), state.sidebar.chats.clone())
2755 };
2756 let people: Vec<(String, String)> = recipients
2757 .iter()
2758 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
2759 .collect();
2760 let (chat, message) = match self.draft_target_chat(cx) {
2761 Some(chat_id) => {
2762 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
2763 return;
2764 };
2765 crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now())
2766 }
2767 None => crate::demo::new_chat(
2768 &chats,
2769 &people,
2770 topic,
2771 &outgoing.text(),
2772 &outgoing.html(),
2773 Utc::now(),
2774 ),
2775 };
2776 let _ = store.upsert_chats(std::slice::from_ref(&chat));
2777 let _ = store.upsert_messages(std::slice::from_ref(&message));
2778 self.app.update(cx, |state, cx| {
2779 state.reload_sidebar(cx);
2780 state.select(Selection::Chat(chat.id.clone()), cx);
2781 });
2782 }
2783
2784 fn conversation_id(&self) -> Option<String> {
2785 self.current
2786 .as_ref()
2787 .map(|current| current.selection.conversation_id().to_owned())
2788 }
2789
2790 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
2791 let conversation_id = self.conversation_id()?;
2792 let my_user_id = self.row_context(cx).my_user_id?;
2793 self.app
2794 .read(cx)
2795 .store
2796 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2797 .ok()?
2798 .remove(message_id)
2799 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
2800 }
2801
2802 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
2803 if hovered && matches!(slot, HoverSlot::Row) {
2804 self.request_post_follow(key, cx);
2805 }
2806 let target = match slot {
2807 HoverSlot::Row => &mut self.hovered_message,
2808 HoverSlot::Toolbar => &mut self.toolbar_hovered,
2809 };
2810 if hovered {
2811 *target = Some(key.to_owned());
2812 } else if target.as_deref() == Some(key) {
2813 *target = None;
2814 }
2815 if !hovered && matches!(slot, HoverSlot::Row) && self.toolbar_opened.as_deref() == Some(key) {
2816 self.toolbar_opened = None;
2817 }
2818 if hovered
2819 && matches!(slot, HoverSlot::Row)
2820 && self.toolbar_hovered.as_deref().is_some_and(|toolbar| toolbar != key)
2821 {
2822 self.toolbar_hovered = None;
2823 }
2824 if let Some(suppressed) = self.toolbar_suppressed.as_deref()
2825 && self.hovered_message.as_deref() != Some(suppressed)
2826 && self.toolbar_hovered.as_deref() != Some(suppressed)
2827 {
2828 self.toolbar_suppressed = None;
2829 }
2830 cx.notify();
2831 }
2832
2833 fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2834 if self.toolbar_hovered.as_deref() == Some(key) {
2835 self.toolbar_hovered = None;
2836 }
2837 self.toolbar_suppressed = Some(key.to_owned());
2838 cx.notify();
2839 }
2840
2841 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
2842 if open {
2843 self.toolbar_pinned = Some(key.to_owned());
2844 } else if self.toolbar_pinned.as_deref() == Some(key) {
2845 self.toolbar_pinned = None;
2846 }
2847 cx.notify();
2848 }
2849
2850 fn toolbar_visible(&self, key: &str, cx: &App) -> bool {
2851 let row_trigger = if self.app.read(cx).actions_on_right_click {
2852 self.toolbar_opened.as_deref()
2853 } else {
2854 self.hovered_message.as_deref()
2855 };
2856 self.toolbar_suppressed.as_deref() != Some(key)
2857 && self
2858 .toolbar_pinned
2859 .as_deref()
2860 .or(self.toolbar_hovered.as_deref())
2861 .or(row_trigger)
2862 == Some(key)
2863 }
2864
2865 fn open_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2866 self.toolbar_opened = Some(key.to_owned());
2867 self.toolbar_suppressed = None;
2868 cx.notify();
2869 }
2870
2871 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
2872 self.change_reaction(message_id, glyph, false, None, cx);
2873 }
2874
2875 fn change_reaction(
2876 &mut self,
2877 message_id: &str,
2878 glyph: &str,
2879 only_add: bool,
2880 accepted_proposal: Option<String>,
2881 cx: &mut Context<Self>,
2882 ) -> ReactionAttempt {
2883 let Some(conversation_id) = self.conversation_id() else {
2884 return ReactionAttempt::Blocked;
2885 };
2886 let state = self.app.read(cx);
2887 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2888 let engine = engine.filter(|_| !mode.read_only);
2889 if !mode.demo && engine.is_none() {
2890 self.show_notice("Read-only mode: reaction not sent", cx);
2891 return ReactionAttempt::Blocked;
2892 }
2893 let my_user_id = self.row_context(cx).my_user_id;
2894 let Some(mut record) = store
2895 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2896 .ok()
2897 .and_then(|mut found| found.remove(message_id))
2898 else {
2899 return ReactionAttempt::MissingMessage;
2900 };
2901 let wanted = reaction_glyph(glyph);
2902 let mut visible = teams_core::reactions(&record);
2903 apply_pending_reactions(
2904 &mut visible,
2905 self.pending_reactions.get(message_id),
2906 my_user_id.as_deref(),
2907 Utc::now(),
2908 );
2909 let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref());
2910 if only_add && !added {
2911 return ReactionAttempt::AlreadyThere;
2912 }
2913 let skin_tone = teams_core::skin_tone(&store);
2914 let wanted = if added {
2915 wanted
2916 } else {
2917 let own = own_reaction_glyph(&visible, glyph, my_user_id.as_deref()).unwrap_or(wanted);
2918 if emoticons::without_tone(&own) == own {
2919 emoticons::with_tone(&own, skin_tone)
2920 } else {
2921 own
2922 }
2923 };
2924 let glyph = wanted.as_str();
2925 let Some(engine) = engine.filter(|_| !mode.demo) else {
2926 let mut reactions = teams_core::reactions(&record);
2927 set_own_reaction(
2928 &mut reactions,
2929 glyph,
2930 my_user_id.as_deref(),
2931 added,
2932 Utc::now(),
2933 );
2934 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2935 let _ = store.upsert_messages(std::slice::from_ref(&record));
2936 if added {
2937 self.record_reaction_use(glyph, cx);
2938 }
2939 self.rebuild(false, cx);
2940 return ReactionAttempt::Acted;
2941 };
2942 let entries = self
2943 .pending_reactions
2944 .entry(message_id.to_owned())
2945 .or_default();
2946 entries.retain(|(pending, _)| {
2947 emoticons::without_tone(pending) != emoticons::without_tone(&wanted)
2948 });
2949 entries.push((wanted.clone(), added));
2950 self.rebuild(false, cx);
2951 let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned());
2952 let reaction_type = api_reaction(&wanted);
2953 let receiver = runtime::spawn({
2954 let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone());
2955 async move {
2956 if added {
2957 engine
2958 .set_reaction(&conversation_id, &message_id, &reaction_type)
2959 .await
2960 } else {
2961 engine
2962 .unset_reaction(&conversation_id, &message_id, &reaction_type)
2963 .await
2964 }
2965 }
2966 });
2967 cx.spawn(async move |this, cx| {
2968 let outcome = match receiver.await {
2969 Ok(Ok(())) => Ok(()),
2970 Ok(Err(error)) => Err(short_error(&error)),
2971 Err(_) => Err("cancelled".to_owned()),
2972 };
2973 this.update(cx, |this, cx| {
2974 this.finish_reaction(
2975 &conversation_id,
2976 &message_id,
2977 &glyph,
2978 added,
2979 accepted_proposal.as_deref(),
2980 outcome,
2981 cx,
2982 )
2983 })
2984 .ok();
2985 })
2986 .detach();
2987 ReactionAttempt::Started
2988 }
2989
2990 fn finish_reaction(
2991 &mut self,
2992 conversation_id: &str,
2993 message_id: &str,
2994 glyph: &str,
2995 added: bool,
2996 accepted_proposal: Option<&str>,
2997 outcome: Result<(), String>,
2998 cx: &mut Context<Self>,
2999 ) {
3000 let wanted = reaction_glyph(glyph);
3001 let store = self.app.read(cx).store.clone();
3002 if let Some(proposal_id) = accepted_proposal.filter(|_| outcome.is_ok()) {
3003 crate::agent_api::resolve_reaction_proposal(
3004 conversation_id,
3005 message_id,
3006 proposal_id,
3007 mcp::ReactionOutcome::Accepted,
3008 cx,
3009 );
3010 }
3011 if outcome.is_ok() {
3012 let my_user_id = self.row_context(cx).my_user_id;
3013 if let Some(mut record) = store
3014 .messages_by_id(conversation_id, &[message_id.to_owned()])
3015 .ok()
3016 .and_then(|mut found| found.remove(message_id))
3017 {
3018 let mut reactions = teams_core::reactions(&record);
3019 set_own_reaction(
3020 &mut reactions,
3021 glyph,
3022 my_user_id.as_deref(),
3023 added,
3024 Utc::now(),
3025 );
3026 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
3027 let _ = store.upsert_messages(std::slice::from_ref(&record));
3028 }
3029 if added {
3030 self.record_reaction_use(glyph, cx);
3031 }
3032 }
3033 if let Some(entries) = self.pending_reactions.get_mut(message_id) {
3034 entries.retain(|entry| *entry != (wanted.clone(), added));
3035 if entries.is_empty() {
3036 self.pending_reactions.remove(message_id);
3037 }
3038 }
3039 self.rebuild(false, cx);
3040 if let Err(error) = outcome {
3041 self.show_notice(&format!("Reaction failed: {error}"), cx);
3042 }
3043 }
3044
3045 fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) {
3046 if chatsvc::custom_emoji(glyph).is_some() {
3047 return;
3048 }
3049 let store = self.app.read(cx).store.clone();
3050 self.recent.update(cx, |recent, cx| {
3051 recent.reload(&store);
3052 recent.record_use(&emoticons::without_tone(glyph));
3053 recent.save(&store);
3054 cx.notify();
3055 });
3056 }
3057
3058 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
3059 let Some(record) = self.own_record(message_id, cx) else {
3060 return;
3061 };
3062 let edit = EditPreview {
3063 message_id: record.message_id.clone(),
3064 excerpt: reply_excerpt(&record),
3065 scheduled: None,
3066 };
3067 let in_chat = matches!(
3068 self.current.as_ref().map(|current| &current.selection),
3069 Some(Selection::Chat(_))
3070 );
3071 let mentions = if in_chat {
3072 teams_core::user_mention_inputs(&record)
3073 } else {
3074 Vec::new()
3075 };
3076 let draft = Outgoing {
3077 banner: None,
3078 draft: message_draft(&record),
3079 subject: None,
3080 mentions,
3081 reply: None,
3082 edit: Some(edit),
3083 images: Vec::new(),
3084 files: Vec::new(),
3085 link_preview: None,
3086 importance: Default::default(),
3087 };
3088 self.show_main_composer(cx);
3089 self.composer
3090 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
3091 }
3092
3093 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3094 if self.draft_active {
3095 return;
3096 }
3097 let key = self
3098 .rows
3099 .borrow()
3100 .iter()
3101 .flat_map(Row::messages)
3102 .filter(|message| {
3103 message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX)
3104 })
3105 .max_by_key(|message| message.created_at)
3106 .map(|message| message.key.clone());
3107 if let Some(key) = key {
3108 self.begin_edit(&key, window, cx);
3109 }
3110 }
3111
3112 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
3113 let Some(edit) = outgoing.edit.clone() else {
3114 return;
3115 };
3116 let Some(conversation_id) = self.conversation_id() else {
3117 return;
3118 };
3119 let state = self.app.read(cx);
3120 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
3121 if mode.demo {
3122 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
3123 record.body_html = outgoing.html();
3124 record.edited_at = Some(Utc::now());
3125 let _ = store.upsert_messages(std::slice::from_ref(&record));
3126 self.rebuild(false, cx);
3127 }
3128 return;
3129 }
3130 let Some(engine) = engine.filter(|_| !mode.read_only) else {
3131 self.notice = Some("Read-only mode: edit not saved".to_owned());
3132 self.show_main_composer(cx);
3133 self.composer
3134 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
3135 cx.notify();
3136 return;
3137 };
3138 let original = self.own_record(&edit.message_id, cx);
3139 if let Some(mut record) = original.clone() {
3140 record.body_html = outgoing.html();
3141 record.edited_at = Some(Utc::now());
3142 let _ = store.upsert_messages(std::slice::from_ref(&record));
3143 }
3144 let message_id = edit.message_id.clone();
3145 self.saving_edits.insert(message_id.clone());
3146 self.rebuild(false, cx);
3147 let sent = outgoing.clone();
3148 let receiver = runtime::spawn(async move {
3149 engine
3150 .edit_message_html(
3151 &conversation_id,
3152 &edit.message_id,
3153 &sent.html(),
3154 &sent.mentions,
3155 )
3156 .await
3157 });
3158 cx.spawn_in(window, async move |this, cx| {
3159 let failed = !matches!(receiver.await, Ok(Ok(())));
3160 this.update_in(cx, |this, window, cx| {
3161 this.saving_edits.remove(&message_id);
3162 if failed && let Some(record) = &original {
3163 let _ = store.upsert_messages(std::slice::from_ref(record));
3164 }
3165 this.rebuild(false, cx);
3166 if failed {
3167 this.show_main_composer(cx);
3168 if this.composer.read(cx).is_empty(cx) {
3169 this.notice =
3170 Some("Edit failed: your text is back in the composer".to_owned());
3171 this.composer
3172 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
3173 } else {
3174 this.notice = Some("Edit failed".to_owned());
3175 }
3176 cx.notify();
3177 }
3178 })
3179 .ok();
3180 })
3181 .detach();
3182 }
3183
3184 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
3185 let Some(conversation_id) = self.conversation_id() else {
3186 return;
3187 };
3188 let record = self
3189 .app
3190 .read(cx)
3191 .store
3192 .messages_by_id(&conversation_id, &[message_id.to_owned()])
3193 .ok()
3194 .and_then(|mut found| found.remove(message_id));
3195 if let Some(record) = record {
3196 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
3197 }
3198 }
3199
3200 fn refresh_card(
3201 &mut self,
3202 key: &str,
3203 card_index: usize,
3204 action: ExecuteAction,
3205 cx: &mut Context<Self>,
3206 ) {
3207 let Some(conversation_id) = self.conversation_id() else {
3208 return;
3209 };
3210 let scope = CardScope::message(&conversation_id, key, card_index);
3211 self.app.update(cx, |state, cx| {
3212 state.refresh_card_manually(scope, action, cx)
3213 });
3214 }
3215
3216 pub(super) fn translate_message(&mut self, key: &str, cx: &mut Context<Self>) {
3217 let Some(conversation_id) = self.conversation_id() else {
3218 return;
3219 };
3220 self.app.update(cx, |state, cx| {
3221 state.translate_message(&conversation_id, key, cx)
3222 });
3223 }
3224
3225 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
3226 self.app.update(cx, |state, cx| {
3227 state.raise_notice(message.to_owned(), None, cx)
3228 });
3229 }
3230
3231 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
3232 let (Some(conversation_id), Some(runs)) =
3233 (self.conversation_id(), crate::agents::runs_handle(cx))
3234 else {
3235 return (Vec::new(), None);
3236 };
3237 if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) {
3238 return (Vec::new(), None);
3239 }
3240 let settings = runs.read(cx).settings();
3241 let entries: Vec<DelegateEntry> = settings
3242 .actions
3243 .iter()
3244 .map(|action| {
3245 let request = StartRequest {
3246 action_id: action.id.clone(),
3247 conversation_id: conversation_id.clone(),
3248 message_id: key.to_owned(),
3249 };
3250 let agent_name = settings
3251 .agents
3252 .iter()
3253 .find(|agent| agent.id == action.agent_id)
3254 .map(|agent| agent.name.clone())
3255 .unwrap_or_default();
3256 DelegateEntry {
3257 label: action.label.clone(),
3258 agent_name,
3259 action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)),
3260 }
3261 })
3262 .collect();
3263 let manage_agents = (!entries.is_empty()).then(|| {
3264 Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action
3265 });
3266 (entries, manage_agents)
3267 }
3268
3269 fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) {
3270 let Some(conversation_id) = self.conversation_id() else {
3271 return (false, HashSet::new());
3272 };
3273 let Some(runs) = crate::agents::runs_handle(cx) else {
3274 return (false, HashSet::new());
3275 };
3276 let mut snapshot: HashMap<String, AgentRun> = HashMap::new();
3277 for run in runs.read(cx).for_conversation(&conversation_id) {
3278 snapshot.insert(run.message_id.clone(), run.clone());
3279 }
3280 let layouts: HashMap<String, (usize, bool)> = snapshot
3281 .iter()
3282 .map(|(key, run)| (key.clone(), run.layout_key()))
3283 .collect();
3284 let layout_changed: HashSet<String> = layouts
3285 .iter()
3286 .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout))
3287 .map(|(key, _)| key.clone())
3288 .chain(
3289 self.agent_layouts
3290 .keys()
3291 .filter(|key| !layouts.contains_key(*key))
3292 .cloned(),
3293 )
3294 .collect();
3295 self.agent_layouts = layouts;
3296 let snapshot_changed = *self.agent_runs.borrow() != snapshot;
3297 *self.agent_runs.borrow_mut() = snapshot;
3298 (snapshot_changed, layout_changed)
3299 }
3300
3301 fn sync_agent_chips(&mut self, cx: &mut Context<Self>) {
3302 let (snapshot_changed, changed) = self.refresh_agent_runs(cx);
3303 let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running);
3304 self.remeasure_rows_of(&changed, cx);
3305 if snapshot_changed || any_running {
3306 cx.notify();
3307 }
3308 }
3309
3310 fn remeasure_rows_of(&mut self, keys: &HashSet<String>, cx: &mut Context<Self>) {
3311 if keys.is_empty() {
3312 return;
3313 }
3314 let indices: Vec<usize> = self
3315 .rows
3316 .borrow()
3317 .iter()
3318 .enumerate()
3319 .filter(|(_, row)| row.messages().any(|message| keys.contains(&message.key)))
3320 .map(|(index, _)| index)
3321 .collect();
3322 self.scroller.update(cx, |scroller, cx| {
3323 for index in indices {
3324 scroller.remeasure_items(index..index + 1, cx);
3325 }
3326 });
3327 }
3328
3329 fn message_menu(
3330 &self,
3331 message: &MessageRow,
3332 mine: HashSet<String>,
3333 refresh: Option<(usize, ExecuteAction)>,
3334 view: WeakEntity<Self>,
3335 cx: &App,
3336 ) -> MessageMenu {
3337 let (key, own) = (message.key.as_str(), message.own);
3338 let translate_label = match message.translation {
3339 Some(TranslationLine::Translated {
3340 showing_original: false,
3341 ..
3342 }) => "See original",
3343 Some(TranslationLine::Translated { .. }) => "See translation",
3344 _ => "Translate",
3345 };
3346 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
3347 let (view, key) = (view.clone(), key.to_owned());
3348 Rc::new(move |window, cx| {
3349 view.update(cx, |this, cx| {
3350 this.set_pinned(&key, false, cx);
3351 run(this, &key, window, cx)
3352 })
3353 .ok();
3354 })
3355 };
3356 let react: PickHandler = {
3357 let (view, key) = (view.clone(), key.to_owned());
3358 Rc::new(move |glyph, _, cx| {
3359 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
3360 .ok();
3361 })
3362 };
3363 let hover = {
3364 let (view, key) = (view.clone(), key.to_owned());
3365 Rc::new(move |hovered: bool, cx: &mut App| {
3366 view.update(cx, |this, cx| {
3367 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
3368 })
3369 .ok();
3370 })
3371 };
3372 let pin = {
3373 let (view, key) = (view.clone(), key.to_owned());
3374 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
3375 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
3376 .ok();
3377 })
3378 };
3379 let refresh_card = refresh.map(|(card_index, refresh_action)| {
3380 let (view, key) = (view.clone(), key.to_owned());
3381 Rc::new(move |_: &mut Window, cx: &mut App| {
3382 view.update(cx, |this, cx| {
3383 this.refresh_card(&key, card_index, refresh_action.clone(), cx)
3384 })
3385 .ok();
3386 }) as Action
3387 });
3388 let chat_id = self.chat_id();
3389 let state = self.app.read(cx);
3390 let saved = self
3391 .conversation_id()
3392 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3393 let quick = state.quick_reactions();
3394 let in_chat = chat_id.is_some();
3395 let pin_conversation_id = self.pin_conversation_id();
3396 let pinned = pin_conversation_id
3397 .as_deref()
3398 .is_some_and(|conversation_id| state.is_pinned(conversation_id, key));
3399 let pinnable = in_chat
3400 || pin_conversation_id.as_deref().is_some_and(|channel_id| {
3401 state
3402 .message_record(channel_id, key)
3403 .is_some_and(|record| record.reply_to_id.is_none())
3404 });
3405 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3406 let post_followed = self.post_follow(key, cx);
3407 MessageMenu {
3408 key: key.to_owned(),
3409 react,
3410 reply: Some(action(|this, key, window, cx| {
3411 this.begin_reply(key, window, cx)
3412 })),
3413 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
3414 forward_multiple: in_chat
3415 .then(|| action(|this, key, _, cx| this.start_forward_selection(key, cx))),
3416 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
3417 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
3418 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
3419 translate_label,
3420 share_to_outlook: Some(action(|this, key, _, cx| this.share_to_outlook(key, cx))),
3421 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3422 saved,
3423 toggle_pinned: pinnable
3424 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3425 pinned,
3426 toggle_follow: post_followed
3427 .map(|_| action(|this, key, _, cx| this.toggle_post_follow(key, cx))),
3428 followed: post_followed.unwrap_or_default(),
3429 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3430 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3431 mark_unread: (in_chat && !own)
3432 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
3433 refresh_card,
3434 delegate,
3435 manage_agents,
3436 pin,
3437 hover,
3438 picker: self.picker.clone(),
3439 quick,
3440 mine,
3441 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3442 }
3443 }
3444
3445 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
3446 let Some(outgoing) = self.pending_outgoing.remove(key) else {
3447 return;
3448 };
3449 let reply_root = self
3450 .pending
3451 .iter()
3452 .find(|row| row.key == key)
3453 .and_then(|row| row.reply_root.clone());
3454 self.pending.retain(|row| row.key != key);
3455 if self.draft_active {
3456 self.send_new_chat(outgoing, window, cx);
3457 } else {
3458 self.send_as(key.to_owned(), outgoing, reply_root, window, cx);
3459 }
3460 }
3461
3462 fn finish_send(
3463 &mut self,
3464 key: &str,
3465 result: Result<teams_core::Result<Delivered>, tokio::sync::oneshot::error::RecvError>,
3466 cx: &mut Context<Self>,
3467 ) {
3468 if matches!(result, Ok(Ok(Delivered::WithoutBanner))) {
3469 self.notice = Some(POSTED_WITHOUT_BANNER.to_owned());
3470 }
3471 let failure = match result {
3472 Ok(Ok(_)) => None,
3473 Ok(Err(error)) => Some(short_error(&error)),
3474 Err(error) => Some(short_error(&error)),
3475 };
3476 let store = self.app.read(cx).store.clone();
3477 match failure {
3478 None => {
3479 store.delete_outbox(key).ok();
3480 self.pending.retain(|row| row.key != key);
3481 self.pending_outgoing.remove(key);
3482 }
3483 Some(error) => {
3484 store.mark_outbox_failed(key, &error).ok();
3485 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
3486 row.delivery = Delivery::Failed(error.clone());
3487 self.notice = Some(format!("Not sent: {error}"));
3488 }
3489 }
3490 }
3491 self.app
3492 .update(cx, |state, cx| state.refresh_local_previews(cx));
3493 self.rebuild(false, cx);
3494 }
3495
3496 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
3497 let target = match self.current.as_ref().map(|current| &current.selection) {
3498 Some(Selection::Chat(_)) => DropTarget::Chat,
3499 Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
3500 Some(Selection::Channel(_)) => DropTarget::Channel,
3501 None => DropTarget::NewChat,
3502 };
3503 let title = self
3504 .current
3505 .as_ref()
3506 .map(|current| current.title.as_str())
3507 .unwrap_or_default();
3508 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
3509 let composer = self.composer.clone();
3510 div()
3511 .id("drop-overlay")
3512 .absolute()
3513 .top_0()
3514 .left_0()
3515 .size_full()
3516 .opacity(0.)
3517 .bg(theme::drop_background())
3518 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
3519 if composer.read(cx).is_editing() {
3520 style
3521 } else {
3522 style.opacity(1.)
3523 }
3524 })
3525 .on_drag_move(
3526 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
3527 let count = event.drag(cx).paths().len();
3528 if this.drag_file_count != count {
3529 this.drag_file_count = count;
3530 cx.notify();
3531 }
3532 }),
3533 )
3534 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
3535 let paths = dropped.paths().to_vec();
3536 if this.shared_active() {
3537 this.upload_paths(paths, cx);
3538 return;
3539 }
3540 this.composer
3541 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
3542 }))
3543 .child(
3544 div()
3545 .absolute()
3546 .inset(px(12.))
3547 .rounded(px(12.))
3548 .border_2()
3549 .border_color(theme::accent())
3550 .flex()
3551 .items_center()
3552 .justify_center()
3553 .child(
3554 v_flex()
3555 .items_center()
3556 .gap(px(6.))
3557 .px(px(24.))
3558 .py(px(16.))
3559 .rounded(px(12.))
3560 .bg(black().opacity(0.55))
3561 .child(symbol("upload", 28., theme::accent_text()))
3562 .child(
3563 div()
3564 .text_size(px(15.))
3565 .font_weight(FontWeight::SEMIBOLD)
3566 .text_color(theme::text_strong())
3567 .child(heading),
3568 )
3569 .child(
3570 div()
3571 .text_size(px(12.))
3572 .text_color(theme::text_muted())
3573 .child(detail),
3574 ),
3575 ),
3576 )
3577 }
3578
3579 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
3580 let message = self.draft_error.clone()?;
3581 let failed_key = self
3582 .pending
3583 .iter()
3584 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
3585 .map(|row| row.key.clone())?;
3586 Some(
3587 h_flex()
3588 .w_full()
3589 .flex_none()
3590 .px(px(20.))
3591 .py(px(4.))
3592 .gap(px(8.))
3593 .items_center()
3594 .text_size(px(12.))
3595 .text_color(theme::red_soft())
3596 .child(message)
3597 .child(
3598 Button::new("retry-new-chat")
3599 .ghost()
3600 .compact()
3601 .label("Retry")
3602 .on_click(cx.listener(move |this, _, window, cx| {
3603 this.retry(&failed_key, window, cx)
3604 })),
3605 ),
3606 )
3607 }
3608
3609 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3610 if self.pinned || self.draft_active {
3611 return;
3612 }
3613 let Some(selection) = self
3614 .current
3615 .as_ref()
3616 .map(|current| current.selection.clone())
3617 else {
3618 return;
3619 };
3620 self.channel_details_open = false;
3621 self.close_copilot();
3622 if let Some(panel) = &self.find_panel {
3623 panel.update(cx, |panel, cx| panel.focus(window, cx));
3624 return;
3625 }
3626 let app = self.app.clone();
3627 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3628 let subscription = cx.subscribe_in(
3629 &panel,
3630 window,
3631 move |this, _, event: &FindPanelEvent, window, cx| match event {
3632 FindPanelEvent::Close => this.close_find(window, cx),
3633 FindPanelEvent::Jump(message_id) => {
3634 let (selection, message_id) = (selection.clone(), message_id.clone());
3635 this.app.update(cx, |state, cx| {
3636 state.jump_to_message(selection, message_id, cx)
3637 });
3638 }
3639 },
3640 );
3641 panel.update(cx, |panel, cx| panel.focus(window, cx));
3642 self.find_panel = Some(panel);
3643 self.find_subscription = Some(subscription);
3644 cx.notify();
3645 }
3646
3647 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3648 self.find_panel = None;
3649 self.find_subscription = None;
3650 self.composer
3651 .update(cx, |composer, cx| composer.focus(window, cx));
3652 cx.notify();
3653 }
3654
3655 fn header_width(&self, window: &Window) -> f32 {
3656 match self.header_width.get() {
3657 width if width > 0. => width,
3658 _ => {
3659 f32::from(window.viewport_size().width)
3660 - RAIL_WIDTH
3661 - SIDEBAR_WIDTH
3662 - 2. * ISLAND_GAP
3663 }
3664 }
3665 }
3666
3667 fn tabs_below_title(&self, window: &Window) -> bool {
3668 self.header_width(window) < TABS_INLINE_MIN_WIDTH
3669 }
3670
3671 fn render_header(
3672 &self,
3673 current: &Current,
3674 tabs: Option<AnyElement>,
3675 cx: &mut Context<Self>,
3676 ) -> impl IntoElement {
3677 let app = self.app.read(cx);
3678 let directory = &app.directory;
3679 let me = directory.me.as_ref();
3680 let mut lead: Option<AnyElement> = None;
3681 let mut subline = String::new();
3682 let mut stack: Option<AnyElement> = None;
3683 let mut rename: Option<AnyElement> = None;
3684 let mut names_title: Option<Div> = None;
3685 let mut header_title = current.title.clone();
3686 match &current.selection {
3687 Selection::Chat(chat_id) => {
3688 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3689 let faces = others(chat, me);
3690 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3691 let first = faces.first().cloned().map(face);
3692 if let Some(bot) = one_on_one_bot(chat, me) {
3693 lead = Some(bot_tile(directory, &face(bot), 36.));
3694 } else if is_one_on_one(chat) || faces.len() < 2 {
3695 let name = first
3696 .as_ref()
3697 .map_or(current.title.as_str(), |face| face.name.as_str());
3698 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
3699 let avatar = person_avatar(directory, user_id, name, 36.);
3700 let presence = user_id.map(|id| directory.presence_of(id));
3701 let avatar = match presence {
3702 Some(kind) => with_presence(avatar, kind, 36., theme::surface())
3703 .into_any_element(),
3704 None => avatar,
3705 };
3706 lead = Some(
3707 opens_profile(div().id("header-avatar").flex_none(), user_id)
3708 .child(avatar)
3709 .into_any_element(),
3710 );
3711 subline = match (user_id, presence) {
3712 (Some(id), Some(presence)) => {
3713 directory.status_label(id, presence).to_owned()
3714 }
3715 _ => String::new(),
3716 };
3717 if is_one_on_one(chat) && !is_notes_chat(chat_id) {
3718 stack = Some(add_people_button(&self.app, chat_id));
3719 }
3720 } else {
3721 if chat.kind == GROUP_KIND
3722 && me.is_some_and(|me| {
3723 chat.members
3724 .iter()
3725 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3726 })
3727 {
3728 rename = Some(group_name_button(&self.app, &self.group_name, chat_id, &chat.title));
3729 }
3730 if chat.title.trim().is_empty() {
3731 names_title = Some(chat_header_actions::group_title(directory, &faces));
3732 }
3733 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3734 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3735 stack = Some(members_popover(
3736 &self.app,
3737 chat_id,
3738 chat_header_actions::member_count(chat.members.len())
3739 .debug_selector(|| MEMBERS_BUTTON.into()),
3740 ));
3741 }
3742 }
3743 }
3744 Selection::Channel(channel_id) => {
3745 let team = app.sidebar.teams.iter().find(|entry| {
3746 entry
3747 .channels
3748 .iter()
3749 .any(|channel| &channel.id == channel_id)
3750 });
3751 let (name, key) = team
3752 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
3753 (entry.team.name.as_str(), entry.team.id.as_str())
3754 });
3755 let photo = team.and_then(|entry| {
3756 app.directory
3757 .avatar(&teams_core::team_avatar_key(&entry.team.id))
3758 });
3759 lead = Some(team_avatar(photo, name, key, 36., 9.));
3760 if let Some(channel) = team
3761 .and_then(|entry| entry.channels.iter().find(|channel| &channel.id == channel_id))
3762 {
3763 header_title = channel.name.clone();
3764 }
3765 }
3766 }
3767 let mut header = h_flex()
3768 .w_full()
3769 .h(px(HEADER_HEIGHT))
3770 .flex_none()
3771 .px(px(HEADER_PADDING))
3772 .gap(px(HEADER_GAP))
3773 .items_center();
3774 if matches!(current.mode, ViewMode::Thread(_)) {
3775 header = header.child(
3776 h_flex()
3777 .id("back-to-channel")
3778 .flex_none()
3779 .gap(px(2.))
3780 .pl(px(4.))
3781 .pr(px(8.))
3782 .py(px(4.))
3783 .items_center()
3784 .rounded(px(6.))
3785 .cursor_pointer()
3786 .text_size(px(13.))
3787 .font_weight(FontWeight::SEMIBOLD)
3788 .text_color(theme::accent_text())
3789 .hover(|button| button.bg(theme::row_hover()))
3790 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx)))
3791 .child(icon(IconName::ChevronLeft, 16., theme::accent_text()))
3792 .child("Back to channel"),
3793 );
3794 }
3795 let channel_note = match current.mode {
3796 ViewMode::Flat => None,
3797 ViewMode::ThreadList => Some("Posts"),
3798 ViewMode::Thread(_) => Some("Conversation"),
3799 };
3800 if let Some(note) = channel_note {
3801 subline = note.to_owned();
3802 }
3803 let call_controls = if self.pinned && !self.popped_out {
3804 Vec::new()
3805 } else {
3806 header_call_controls(&self.app, app, &current.selection, self.header_overflows())
3807 };
3808 let sync = &current.sync;
3809 let loading_window = current.window_request.is_some();
3810 if sync.failed {
3811 subline = "Not up to date".to_owned();
3812 } else if loading_window {
3813 subline = "Loading message ...".to_owned();
3814 } else if sync.shown_at.is_some() {
3815 subline = if sync.slow { "Taking longer than usual ..." } else { "Loading messages ..." }.to_owned();
3816 }
3817 let inline_tabs = tabs.map(|tabs| h_flex().h_full().flex_1().child(tabs));
3818 let overflow = self.header_overflows();
3819 let divided = !overflow
3820 && matches!(current.selection, Selection::Chat(_))
3821 && (!call_controls.is_empty() || stack.is_some());
3822 header
3823 .relative()
3824 .child(record_width(&self.header_width))
3825 .when(sync.shown_at.is_some() || loading_window, |header| {
3826 header.child(progress_bar())
3827 })
3828 .when(overflow, |header| header.gap(px(HEADER_COMPACT_GAP)))
3829 .when(!overflow, |header| header.children(lead))
3830 .child(
3831 v_flex()
3832 .map(|column| match inline_tabs {
3833 Some(_) => column.flex_shrink(1.).max_w(px(HEADER_TITLE_MAX_WIDTH)),
3834 None => column.flex_1(),
3835 })
3836 .min_w_0()
3837 .overflow_hidden()
3838 .gap(px(1.))
3839 .child(
3840 h_flex()
3841 .min_w_0()
3842 .gap(px(2.))
3843 .items_center()
3844 .child(
3845 div()
3846 .truncate()
3847 .text_size(px(15.))
3848 .font_weight(FontWeight::SEMIBOLD)
3849 .text_color(theme::text())
3850 .map(|title| match names_title {
3851 Some(names) => title.child(names),
3852 None => title.child(header_title),
3853 }),
3854 )
3855 .children(rename),
3856 )
3857 .when(!subline.is_empty(), |column| {
3858 column.child(
3859 div()
3860 .text_size(px(12.))
3861 .text_color(theme::text_muted())
3862 .child(subline),
3863 )
3864 }),
3865 )
3866 .children(inline_tabs)
3867 .children(call_controls)
3868 .children(stack)
3869 .when(divided, |header| header.child(header_divider()))
3870 .when(!overflow, |header| {
3871 header
3872 .children(self.copilot_button(cx))
3873 .children(self.chat_find_button(cx))
3874 })
3875 .children(self.channel_find_button(cx))
3876 .when(!overflow, |header| header.children(self.channel_details_button(cx)))
3877 .children(self.channel_more_button(cx))
3878 .children(self.chat_more_button(overflow, cx))
3879 .children(self.pop_in_button(current))
3880 }
3881
3882 fn pop_in_button(&self, current: &Current) -> Option<AnyElement> {
3883 let Selection::Chat(chat_id) = &current.selection else {
3884 return None;
3885 };
3886 if !self.popped_out {
3887 return None;
3888 }
3889 let (app, chat_id) = (self.app.clone(), chat_id.clone());
3890 Some(
3891 Button::new("chat-pop-in")
3892 .icon(IconName::SquareArrowDownLeft)
3893 .ghost()
3894 .size(px(POP_IN_BUTTON_SIZE))
3895 .rounded(px(8.))
3896 .tooltip(chat_pop_out::POP_IN_TOOLTIP)
3897 .on_click(move |_, window, cx| {
3898 chat_pop_out::return_to_main_window(&app, &chat_id, window, cx)
3899 })
3900 .into_any_element(),
3901 )
3902 }
3903}
3904
3905const GROUP_KIND: &str = "group";
3906const HEADER_DIVIDER_HEIGHT: f32 = 20.;
3907
3908fn header_divider() -> Div {
3909 div()
3910 .w(px(1.))
3911 .h(px(HEADER_DIVIDER_HEIGHT))
3912 .mx(px(4.))
3913 .flex_none()
3914 .bg(theme::border())
3915}
3916
3917impl Render for ConversationView {
3918 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3919 let background = theme::surface();
3920 let mut root = v_flex()
3921 .when(!self.pinned, |root| {
3922 root.debug_selector(|| "shell/islands/main".into())
3923 })
3924 .flex_1()
3925 .w_full()
3926 .min_w_0()
3927 .h_full()
3928 .rounded(px(10.))
3929 .bg(background)
3930 .overflow_hidden()
3931 .track_focus(&self.focus_handle);
3932 let drafting = self.draft_active;
3933 if self.current.is_none() && !drafting {
3934 return root
3935 .items_center()
3936 .justify_center()
3937 .text_color(theme::text_muted())
3938 .child("Select a chat or channel")
3939 .into_any_element();
3940 }
3941 let in_feed = self.in_feed();
3942 let detached = self.is_detached();
3943 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3944 if in_feed && rows_seen != usize::MAX {
3945 self.feed_at_top = rows_seen == 0;
3946 }
3947 let forward_selection = self.active_forward_selection(cx);
3948 let rows = self.rows.clone();
3949 let rows_seen = self.feed_rows_seen.clone();
3950 let env = RenderEnv {
3951 view: cx.weak_entity(),
3952 app: self.app.clone(),
3953 highlighted: self.highlighted_message.clone(),
3954 drafting,
3955 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3956 timeline: self.timeline_bounds.clone(),
3957 agent_runs: self.agent_runs.clone(),
3958 reaction_proposals: self.reaction_proposals.clone(),
3959 forward_selection: forward_selection.clone(),
3960 };
3961 let pin_banner = self
3962 .render_pin_banner(cx)
3963 .filter(|_| !drafting && !self.shared_active() && !self.recap_active());
3964 let timeline_top_inset = pin_banner_inset(pin_banner.is_some());
3965 let comfy = self.app.read(cx).account_chat_settings().message_density
3966 != teams_core::MessageDensity::Compact;
3967 let scroller = MessageScroller::new(
3968 "messages",
3969 self.scroller.clone(),
3970 move |index, window, cx| {
3971 rows_seen.set(rows_seen.get().min(index));
3972 let rows = rows.borrow();
3973 let row = match rows.get(index) {
3974 Some(Row::Message(message)) => {
3975 let actions = env.message_actions(message, window, cx);
3976 let state = env.app.read(cx);
3977 render_message_row(message, index, actions, &state.directory, cx)
3978 }
3979 Some(Row::Post(post)) => {
3980 let actions = env.post_actions(post, window, cx);
3981 let state = env.app.read(cx);
3982 render_post(post, index, actions, &state.directory, cx)
3983 }
3984 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
3985 Some(Row::LoadOlder) => {
3986 let view = env.view.clone();
3987 cx.defer(move |cx| {
3988 view.update(cx, |this, cx| this.request_older(cx)).ok();
3989 });
3990 h_flex()
3991 .w_full()
3992 .py_2()
3993 .gap(px(6.))
3994 .justify_center()
3995 .text_size(px(12.))
3996 .text_color(theme::text_muted())
3997 .child(icon(IconName::Loader, 12., theme::text_muted()))
3998 .child("Loading older messages")
3999 .into_any_element()
4000 }
4001 Some(Row::LoadNewer) => {
4002 let view = env.view.clone();
4003 cx.defer(move |cx| {
4004 view.update(cx, |this, cx| {
4005 this.request_window_page(WindowDirection::Forward, cx)
4006 })
4007 .ok();
4008 });
4009 h_flex()
4010 .w_full()
4011 .py_2()
4012 .gap(px(6.))
4013 .justify_center()
4014 .text_size(px(12.))
4015 .text_color(theme::text_muted())
4016 .child(icon(IconName::Loader, 12., theme::text_muted()))
4017 .child("Loading newer messages")
4018 .into_any_element()
4019 }
4020 Some(Row::Start(start)) => {
4021 let state = env.app.read(cx);
4022 v_flex()
4023 .w_full()
4024 .items_center()
4025 .gap(px(8.))
4026 .pt(px(32.))
4027 .pb(px(16.))
4028 .child(match start.user_id.as_deref() {
4029 Some(user_id) if is_bot_id(user_id) => bot_tile(
4030 &state.directory,
4031 &Face {
4032 user_id: Some(user_id.to_owned()),
4033 name: start.title.clone(),
4034 },
4035 56.,
4036 ),
4037 user_id => person_avatar(
4038 &state.directory,
4039 user_id,
4040 &start.avatar_name,
4041 56.,
4042 ),
4043 })
4044 .child(
4045 div()
4046 .text_size(px(16.))
4047 .font_weight(FontWeight::SEMIBOLD)
4048 .text_color(theme::text())
4049 .child(start.title.clone()),
4050 )
4051 .child(
4052 div()
4053 .text_size(px(12.))
4054 .text_color(theme::text_muted())
4055 .child("This is the beginning of the conversation"),
4056 )
4057 .into_any_element()
4058 }
4059 None => div().into_any_element(),
4060 };
4061 runway(row, comfy)
4062 },
4063 )
4064 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
4065 .jump_button(!in_feed)
4066 .force_jump_button(detached)
4067 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
4068 .with_jump_button_renderer(|button| {
4069 button
4070 .label(jump::JUMP_TO_NEWEST_LABEL)
4071 .tooltip(jump::jump_to_newest_tooltip())
4072 .border_0()
4073 .bg(theme::accent())
4074 .text_color(theme::on_accent())
4075 })
4076 .when(detached, |scroller| {
4077 let view = cx.weak_entity();
4078 scroller.on_jump(move |_, cx| {
4079 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
4080 })
4081 })
4082 .with_bottom_fade(background)
4083 .with_top_inset(timeline_top_inset);
4084
4085 root = match self.current.as_ref().filter(|_| !drafting) {
4086 Some(current) => {
4087 let tab_bar = self
4088 .render_tab_bar(window, cx)
4089 .or_else(|| self.render_chat_tab_bar(cx));
4090 let (inline_tabs, tabs_row) = match tab_bar {
4091 Some(tabs) if self.tabs_below_title(window) => (None, Some(tabs)),
4092 tabs => (tabs, None),
4093 };
4094 root.child(self.render_header(current, inline_tabs, cx))
4095 .children(tabs_row.map(|tabs| {
4096 h_flex()
4097 .w_full()
4098 .h(px(TABS_ROW_HEIGHT))
4099 .flex_none()
4100 .px(px(HEADER_PADDING))
4101 .child(tabs)
4102 }))
4103 .child(edge_divider(HEADER_DIVIDER))
4104 }
4105 None => root.child(self.draft.clone()),
4106 };
4107 let sync_failed = self
4108 .current
4109 .as_ref()
4110 .is_some_and(|current| current.sync.failed);
4111 if let Some(notice) = &self.notice {
4112 root = root.child(
4113 h_flex()
4114 .px(px(20.))
4115 .py_1()
4116 .gap(px(8.))
4117 .items_center()
4118 .text_xs()
4119 .bg(theme::amber().opacity(0.15))
4120 .text_color(theme::amber())
4121 .child(div().flex_1().min_w_0().child(notice.clone()))
4122 .when(sync_failed, |bar| {
4123 bar.child(
4124 Button::new("retry-fetch")
4125 .ghost()
4126 .compact()
4127 .label("Retry")
4128 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
4129 )
4130 }),
4131 );
4132 }
4133 let recap_active = self.recap_active();
4134 let empty_channel = in_feed && self.rows.borrow().is_empty();
4135 let new_post = self.render_new_post(cx);
4136 self.watch_feed_scroll(cx);
4137 let feed_scrolled = new_post.is_some() && self.scroller.read(cx).is_scrolled_from_top();
4138 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
4139 let draft = self.draft.read(cx);
4140 let group_name = draft.group_name(cx);
4141 draft.render_empty(&self.app.read(cx).directory, &group_name)
4142 } else if self.shared_active() {
4143 self.render_shared(cx)
4144 } else if self.recap_active() {
4145 self.render_recap(cx)
4146 } else if let Some(start) = self.notes_space() {
4147 notes_space::render_notes_space(&self.app.read(cx).directory, &start)
4148 } else if empty_channel {
4149 div()
4150 .size_full()
4151 .flex()
4152 .items_center()
4153 .justify_center()
4154 .text_size(px(13.))
4155 .text_color(theme::text_muted())
4156 .child("No posts in this channel yet")
4157 .into_any_element()
4158 } else {
4159 scroller.into_any_element()
4160 };
4161 let channel_details = self.render_channel_details(cx);
4162 let copilot_island = self.render_copilot(cx);
4163 let find_panel = self.find_panel.clone().filter(|_| !drafting);
4164 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
4165 let content = v_flex()
4166 .relative()
4167 .flex_1()
4168 .min_w_0()
4169 .min_h_0()
4170 .children(new_post.map(|post| runway(post, comfy)))
4171 .child(
4172 div()
4173 .debug_selector(|| TIMELINE_TAG.into())
4174 .relative()
4175 .flex_1()
4176 .min_h_0()
4177 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
4178 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
4179 .child(body)
4180 .when(feed_scrolled, |timeline| {
4181 timeline.child(
4182 edge_divider(FEED_EDGE_TAG)
4183 .absolute()
4184 .top_0()
4185 .left_0()
4186 .right_0(),
4187 )
4188 })
4189 .children(pin_banner.map(|banner| pin_banner_overlay(runway(banner, comfy)))),
4190 )
4191 .children(self.render_draft_error(cx).map(|error| runway(error, comfy)))
4192 .when(
4193 !in_feed && !recap_active && !self.shared_active(),
4194 |column| match &forward_selection {
4195 Some(snapshot) => {
4196 column.child(runway(self.render_forward_footer(snapshot, cx), comfy))
4197 }
4198 None => column.child(runway(
4199 v_flex()
4200 .w_full()
4201 .child(self.render_typing_line(cx))
4202 .children(self.render_proposal_card(cx))
4203 .child(self.composer.clone()),
4204 comfy,
4205 )),
4206 },
4207 )
4208 .child(self.render_drop_overlay(cx));
4209 let root = root.child(
4210 h_flex()
4211 .relative()
4212 .flex_1()
4213 .min_h_0()
4214 .w_full()
4215 .items_stretch()
4216 .child(content)
4217 .children(channel_details)
4218 .children(find_panel.map(|panel| {
4219 div()
4220 .h_full()
4221 .w(px(FIND_PANEL_WIDTH))
4222 .min_w_0()
4223 .flex_shrink(1.)
4224 .when(find_overlays, |slot| {
4225 slot.absolute().top_0().right_0().bottom_0().max_w_full()
4226 })
4227 .child(panel)
4228 })),
4229 )
4230 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
4231 if this.reaction_details.is_some() {
4232 this.close_reaction_details(cx);
4233 cx.stop_propagation();
4234 }
4235 }))
4236 .on_action(cx.listener(|this, _: &Escape, window, cx| {
4237 if this.draft_active {
4238 if this.draft.read(cx).has_focus(window, cx) {
4239 this.draft.update(cx, |draft, cx| draft.escape(cx));
4240 }
4241 } else if this.cancel_forward_selection(cx) {
4242 } else if !this.on_escape(window, cx) {
4243 cx.propagate();
4244 }
4245 }));
4246 let root = root.child(crate::inline_video::sentinel());
4247 match copilot_island {
4248 Some(island) => h_flex()
4249 .size_full()
4250 .min_w_0()
4251 .gap(px(ISLAND_GAP))
4252 .child(root)
4253 .child(island)
4254 .into_any_element(),
4255 None => root.into_any_element(),
4256 }
4257 }
4258}
4259
4260fn typing_dots() -> impl IntoElement {
4261 h_flex()
4262 .gap(px(3.))
4263 .flex_none()
4264 .children((0..TYPING_DOT_COUNT).map(|index| {
4265 let phase_offset = index as f32 / TYPING_DOT_COUNT as f32;
4266 div()
4267 .size(px(TYPING_DOT_SIZE))
4268 .rounded_full()
4269 .bg(theme::text_muted())
4270 .with_animation(
4271 ElementId::NamedInteger("typing-dot".into(), index as u64),
4272 Animation::new(TYPING_PULSE_PERIOD).repeat(),
4273 move |dot, delta| {
4274 let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs();
4275 dot.opacity(0.3 + 0.7 * wave)
4276 },
4277 )
4278 }))
4279}
4280
4281fn record_width(width: &Rc<Cell<f32>>) -> impl IntoElement {
4282 let width = width.clone();
4283 canvas(
4284 move |bounds, window, _| {
4285 let measured = f32::from(bounds.size.width);
4286 if (measured - width.replace(measured)).abs() > 0.5 {
4287 window.request_animation_frame();
4288 }
4289 },
4290 |_, _, _, _| {},
4291 )
4292 .absolute()
4293 .top_0()
4294 .left_0()
4295 .size_full()
4296}
4297
4298fn progress_bar() -> impl IntoElement {
4299 div()
4300 .absolute()
4301 .left_0()
4302 .right_0()
4303 .bottom(px(-1.))
4304 .h(px(2.))
4305 .overflow_hidden()
4306 .bg(theme::border())
4307 .child(
4308 div()
4309 .absolute()
4310 .top_0()
4311 .h_full()
4312 .w(relative(PROGRESS_BAR_WIDTH))
4313 .bg(theme::own_read())
4314 .with_animation(
4315 "sync-progress",
4316 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
4317 |bar, delta| {
4318 let travel = 1. + PROGRESS_BAR_WIDTH;
4319 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
4320 bar.left(relative(
4321 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
4322 ))
4323 },
4324 ),
4325 )
4326}
4327
4328fn add_people_button(app: &Entity<AppState>, chat_id: &str) -> AnyElement {
4329 let (app, chat_id) = (app.clone(), chat_id.to_owned());
4330 Button::new("chat-add-people")
4331 .ghost()
4332 .compact()
4333 .icon(IconName::UserPlus)
4334 .tooltip("Add people")
4335 .on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx))
4336 .into_any_element()
4337}
4338
4339fn runway(content: impl IntoElement, comfy: bool) -> AnyElement {
4340 if comfy {
4341 h_flex()
4342 .w_full()
4343 .justify_center()
4344 .child(div().w_full().max_w(px(COMFY_RUNWAY_WIDTH)).child(content))
4345 .into_any_element()
4346 } else {
4347 content.into_any_element()
4348 }
4349}
4350
4351#[cfg(test)]
4352mod tests {
4353 use std::sync::Arc;
4354
4355 use super::{DropTarget, drop_overlay_text};
4356
4357 use gpui_kit::test::TestWindowExt as _;
4358 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
4359 use store::Store;
4360
4361 use super::ConversationView;
4362 use crate::app_state::{AppState, Mode, Selection};
4363
4364 #[test]
4365 fn chat_overlay_names_the_chat_and_the_onedrive() {
4366 assert_eq!(
4367 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
4368 (
4369 "Drop to attach to Mara Lin".to_owned(),
4370 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
4371 )
4372 );
4373 }
4374
4375 #[test]
4376 fn channel_overlay_points_to_the_channel_files() {
4377 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
4378 assert_eq!(
4379 detail,
4380 "1 file. Images go into the message, other files to the channel's Files."
4381 );
4382 }
4383
4384 #[test]
4385 fn new_chat_overlay_says_files_wait_for_the_chat() {
4386 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
4387 assert_eq!(heading, "Drop to attach to the new chat");
4388 assert_eq!(
4389 detail,
4390 "2 files. Images go into the message. Files can be added once the chat exists."
4391 );
4392 }
4393
4394 #[gpui_kit::test]
4395 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
4396 cx.update(gpui_kit::init);
4397 let store = Arc::new(Store::open_in_memory().unwrap());
4398 crate::demo::seed(&store);
4399 let mode = Mode {
4400 demo: true,
4401 read_only: false,
4402 demo_sync: None,
4403 };
4404 let (handle, app, _view) = cx.update(|cx| {
4405 let app = cx.new(|_| {
4406 let mut state = AppState::new(store, mode);
4407 crate::demo::seed_directory(&mut state);
4408 state.selection = Some(crate::demo::first_selection());
4409 state
4410 });
4411 let shared = app.clone();
4412 let (handle, view) =
4413 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
4414 cx.new(|cx| ConversationView::new(shared, window, cx))
4415 })
4416 .unwrap();
4417 (handle, app, view)
4418 });
4419 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
4420 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
4421 cx.update_window(handle, move |_, window, cx| {
4422 run(window, cx);
4423 window.render_frame(cx);
4424 })
4425 .unwrap();
4426 };
4427 step(cx, |window, cx| window.render_frame(cx));
4428 step(cx, |window, cx| window.input("lea", cx));
4429 step(cx, |window, cx| window.press("enter", cx));
4430 step(cx, |window, cx| window.press("enter", cx));
4431 step(cx, |window, cx| window.input("Hello Lea", cx));
4432 step(cx, |window, cx| window.press("enter", cx));
4433 cx.update(|cx| {
4434 let state = app.read(cx);
4435 assert!(!state.new_chat);
4436 assert_eq!(
4437 state.selection,
4438 Some(Selection::Chat("demo-chat-new-1".to_owned()))
4439 );
4440 let chat = state
4441 .sidebar
4442 .chats
4443 .iter()
4444 .find(|chat| chat.id == "demo-chat-new-1")
4445 .expect("new chat in the sidebar");
4446 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
4447 });
4448 }
4449
4450 #[gpui_kit::test]
4451 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
4452 cx.update(gpui_kit::init);
4453 let store = Arc::new(Store::open_in_memory().unwrap());
4454 crate::demo::seed(&store);
4455 let mode = Mode {
4456 demo: true,
4457 read_only: false,
4458 demo_sync: None,
4459 };
4460 let (handle, app) = cx.update(|cx| {
4461 let app = cx.new(|_| {
4462 let mut state = AppState::new(store, mode);
4463 crate::demo::seed_directory(&mut state);
4464 state.selection = Some(crate::demo::first_selection());
4465 state
4466 });
4467 let shared = app.clone();
4468 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
4469 cx.new(|cx| ConversationView::new(shared, window, cx))
4470 })
4471 .unwrap();
4472 (handle, app)
4473 });
4474 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
4475 cx.update_window(handle, |_, window, cx| {
4476 window.render_frame(cx);
4477 window.press("escape", cx);
4478 window.render_frame(cx);
4479 window.press("escape", cx);
4480 window.render_frame(cx);
4481 })
4482 .unwrap();
4483 cx.update(|cx| {
4484 let state = app.read(cx);
4485 assert!(!state.new_chat);
4486 assert_eq!(state.selection, Some(crate::demo::first_selection()));
4487 });
4488 }
4489}