BlueGit

ict rusty-teams

Files

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

conversation.rs

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