BlueGit

ict rusty-teams

Files

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

conversation.rs

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